Skip to content

Commit

Permalink
Optimize multiple encodes
Browse files Browse the repository at this point in the history
  • Loading branch information
shargon committed Sep 16, 2020
1 parent 64c3a87 commit 2f3079a
Showing 1 changed file with 10 additions and 1 deletion.
11 changes: 10 additions & 1 deletion src/neo/Cryptography/ECC/ECPoint.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ public class ECPoint : IComparable<ECPoint>, IEquatable<ECPoint>, ISerializable
{
internal ECFieldElement X, Y;
internal readonly ECCurve Curve;
private byte[] _compressedPoint, _uncompressedPoint;

public bool IsInfinity
{
Expand Down Expand Up @@ -51,6 +52,7 @@ public static ECPoint DecodePoint(ReadOnlySpan<byte> encoded, ECCurve curve)
int yTilde = encoded[0] & 1;
BigInteger X1 = new BigInteger(encoded[1..], isUnsigned: true, isBigEndian: true);
p = DecompressPoint(yTilde, X1, curve);
p._compressedPoint = encoded.ToArray();
break;
}
case 0x04: // uncompressed
Expand All @@ -59,7 +61,10 @@ public static ECPoint DecodePoint(ReadOnlySpan<byte> encoded, ECCurve curve)
throw new FormatException("Incorrect length for uncompressed/hybrid encoding");
BigInteger X1 = new BigInteger(encoded[1..(1 + curve.ExpectedECPointLength)], isUnsigned: true, isBigEndian: true);
BigInteger Y1 = new BigInteger(encoded[(1 + curve.ExpectedECPointLength)..], isUnsigned: true, isBigEndian: true);
p = new ECPoint(new ECFieldElement(X1, curve), new ECFieldElement(Y1, curve), curve);
p = new ECPoint(new ECFieldElement(X1, curve), new ECFieldElement(Y1, curve), curve)
{
_uncompressedPoint = encoded.ToArray()
};
break;
}
default:
Expand Down Expand Up @@ -134,17 +139,21 @@ public byte[] EncodePoint(bool commpressed)
byte[] data;
if (commpressed)
{
if (_compressedPoint != null) return _compressedPoint;
data = new byte[33];
}
else
{
if (_uncompressedPoint != null) return _uncompressedPoint;
data = new byte[65];
byte[] yBytes = Y.Value.ToByteArray(isUnsigned: true, isBigEndian: true);
Buffer.BlockCopy(yBytes, 0, data, 65 - yBytes.Length, yBytes.Length);
}
byte[] xBytes = X.Value.ToByteArray(isUnsigned: true, isBigEndian: true);
Buffer.BlockCopy(xBytes, 0, data, 33 - xBytes.Length, xBytes.Length);
data[0] = commpressed ? Y.Value.IsEven ? (byte)0x02 : (byte)0x03 : (byte)0x04;
if (commpressed) _compressedPoint = data;
else _uncompressedPoint = data;
return data;
}

Expand Down

0 comments on commit 2f3079a

Please sign in to comment.