Fix point encoding for short X coordinate

Public keys can have X coordinate value shorter than 32 byte.
In this case `encodePoint()` should return 32 byte value with
leading zeros.

This commit also adds unit test for public key with 31 byte
X coordinate value.
This commit is contained in:
alexvanin 2019-11-17 20:45:00 +03:00
parent 5bcaeeca4e
commit f5ad619450
2 changed files with 20 additions and 1 deletions

View file

@ -103,7 +103,8 @@ func decompressPoints(x *big.Int, yBit uint) (*big.Int, *big.Int) {
func encodePoint(x, y *big.Int) []byte {
data := make([]byte, PublicKeyCompressedSize)
copy(data[1:], x.Bytes())
i := PublicKeyCompressedSize - len(x.Bytes())
copy(data[i:], x.Bytes())
if y.Bit(0) == 0x1 {
data[0] = 0x3

View file

@ -94,6 +94,24 @@ func TestMarshalUnmarshal(t *testing.T) {
require.Equal(t, hex.EncodeToString(MarshalPublicKey(&privateKey.PublicKey)), walletPublicKey)
require.Equal(t, data, MarshalPrivateKey(privateKey))
})
t.Run("marshal / unmarshal public key with 31 byte X point", func(t *testing.T) {
privateKeyString := "4dd8baa41612a74c1cc664102330115f9b3f4d0fc9b7e4f95c4aceb5cbf335d6"
privateKeyHex, err := hex.DecodeString(privateKeyString)
require.NoError(t, err)
privateKey, err := UnmarshalPrivateKey(privateKeyHex)
require.NoError(t, err)
require.Len(t, privateKey.PublicKey.X.Bytes(), 31)
publicKeyHex := MarshalPublicKey(&privateKey.PublicKey)
require.Len(t, publicKeyHex, PublicKeyCompressedSize)
publicKey := UnmarshalPublicKey(publicKeyHex)
require.NotNil(t, publicKey)
require.Equal(t, *publicKey, privateKey.PublicKey)
})
}
func TestSignVerify(t *testing.T) {