Skip to content

Commit

Permalink
renames for consistency
Browse files Browse the repository at this point in the history
  • Loading branch information
shruggr committed Oct 18, 2024
1 parent b30eeef commit f5aee91
Show file tree
Hide file tree
Showing 17 changed files with 86 additions and 66 deletions.
2 changes: 1 addition & 1 deletion compat/bip32/derive.go
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ func (k *ExtendedKey) DerivePublicKeyFromPath(derivationPath string) ([]byte, er
if err != nil {
return nil, fmt.Errorf("failed to generate public key %w", err)
}
return pubKey.SerializeCompressed(), nil
return pubKey.Compressed(), nil
}

func childInt(child string) (uint32, error) {
Expand Down
4 changes: 2 additions & 2 deletions compat/bip32/derive_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -198,7 +198,7 @@ func TestDerivePublicKeyFromPath(t *testing.T) {
require.NoError(t, err)
pubKey, err := xpubKey.ECPubKey()
require.NoError(t, err)
return pubKey.SerializeCompressed()
return pubKey.Compressed()
}(),
expectedErr: nil,
},
Expand All @@ -215,7 +215,7 @@ func TestDerivePublicKeyFromPath(t *testing.T) {
require.NoError(t, err)
pubKey, err := xpubKey.ECPubKey()
require.NoError(t, err)
return pubKey.SerializeCompressed()
return pubKey.Compressed()
}(),
expectedErr: nil,
},
Expand Down
4 changes: 2 additions & 2 deletions compat/bip32/extendedkey.go
Original file line number Diff line number Diff line change
Expand Up @@ -158,7 +158,7 @@ func (k *ExtendedKey) pubKeyBytes() []byte {
if len(k.pubKey) == 0 {
pkx, pky := ec.S256().ScalarBaseMult(k.key)
pubKey := ec.PublicKey{Curve: ec.S256(), X: pkx, Y: pky}
k.pubKey = pubKey.SerializeCompressed()
k.pubKey = pubKey.Compressed()
}
})

Expand Down Expand Up @@ -324,7 +324,7 @@ func (k *ExtendedKey) Child(i uint32) (*ExtendedKey, error) {
// childKey = serP(point(parse256(Il)) + parentKey)
childX, childY := ec.S256().Add(ilx, ily, pubKey.X, pubKey.Y)
pk := ec.PublicKey{Curve: ec.S256(), X: childX, Y: childY}
childKey = pk.SerializeCompressed()
childKey = pk.Compressed()
}

// The fingerprint of the parent for the derived child is the first 4
Expand Down
16 changes: 8 additions & 8 deletions compat/bip32/hd_key_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -643,8 +643,8 @@ func TestGetPublicKeyFromHDKey(t *testing.T) {
t.Fatalf("%s Failed: [%v] inputted and was nil but not expected", t.Name(), test.input)
} else if publicKey != nil && test.expectedNil {
t.Fatalf("%s Failed: [%v] inputted and was NOT nil but expected to be nil", t.Name(), test.input)
} else if publicKey != nil && hex.EncodeToString(publicKey.SerializeCompressed()) != test.expectedKey {
t.Fatalf("%s Failed: [%v] inputted [%s] expected but got: %s", t.Name(), test.input, test.expectedKey, hex.EncodeToString(publicKey.SerializeCompressed()))
} else if publicKey != nil && hex.EncodeToString(publicKey.Compressed()) != test.expectedKey {
t.Fatalf("%s Failed: [%v] inputted [%s] expected but got: %s", t.Name(), test.input, test.expectedKey, hex.EncodeToString(publicKey.Compressed()))
}
}
}
Expand Down Expand Up @@ -674,7 +674,7 @@ func ExampleGetPublicKeyFromHDKey() {
return
}

fmt.Printf("public key: %s", hex.EncodeToString(publicKey.SerializeCompressed()))
fmt.Printf("public key: %s", hex.EncodeToString(publicKey.Compressed()))
// Output:public key: 03a25f6c10eedcd41eebac22c6bbc5278690fa1aab3afc2bbe8f2277c85e5c5def
}

Expand Down Expand Up @@ -856,10 +856,10 @@ func TestGetPublicKeysForPath(t *testing.T) {
t.Fatalf("%s Failed: [%v] [%d] inputted and was nil but not expected", t.Name(), test.input, test.inputNum)
} else if pubKeys != nil && test.expectedNil {
t.Fatalf("%s Failed: [%v] [%d] inputted and was NOT nil but expected to be nil", t.Name(), test.input, test.inputNum)
} else if pubKeys != nil && hex.EncodeToString(pubKeys[0].SerializeCompressed()) != test.expectedPubKey1 {
t.Fatalf("%s Failed: [%v] [%d] inputted key 1 [%s] expected but got: %s", t.Name(), test.input, test.inputNum, test.expectedPubKey1, hex.EncodeToString(pubKeys[0].SerializeCompressed()))
} else if pubKeys != nil && hex.EncodeToString(pubKeys[1].SerializeCompressed()) != test.expectedPubKey2 {
t.Fatalf("%s Failed: [%v] [%d] inputted key 2 [%s] expected but got: %s", t.Name(), test.input, test.inputNum, test.expectedPubKey2, hex.EncodeToString(pubKeys[1].SerializeCompressed()))
} else if pubKeys != nil && hex.EncodeToString(pubKeys[0].Compressed()) != test.expectedPubKey1 {
t.Fatalf("%s Failed: [%v] [%d] inputted key 1 [%s] expected but got: %s", t.Name(), test.input, test.inputNum, test.expectedPubKey1, hex.EncodeToString(pubKeys[0].Compressed()))
} else if pubKeys != nil && hex.EncodeToString(pubKeys[1].Compressed()) != test.expectedPubKey2 {
t.Fatalf("%s Failed: [%v] [%d] inputted key 2 [%s] expected but got: %s", t.Name(), test.input, test.inputNum, test.expectedPubKey2, hex.EncodeToString(pubKeys[1].Compressed()))
}
}
}
Expand Down Expand Up @@ -890,7 +890,7 @@ func ExampleGetPublicKeysForPath() {
return
}

fmt.Printf("found [%d] keys! Key 1: %s Key 2: %s", len(publicKeys), hex.EncodeToString(publicKeys[0].SerializeCompressed()), hex.EncodeToString(publicKeys[1].SerializeCompressed()))
fmt.Printf("found [%d] keys! Key 1: %s Key 2: %s", len(publicKeys), hex.EncodeToString(publicKeys[0].Compressed()), hex.EncodeToString(publicKeys[1].Compressed()))
// Output:found [2] keys! Key 1: 03f87ac38fb0cfca12988b51a2f1cd3e85bb4aeb1b05f549682190ac8205a67d30 Key 2: 02e78303aeef1acce1347c6493fadc1914e6d85ef3189a8856afb3accd53fbd9c5
}

Expand Down
10 changes: 5 additions & 5 deletions compat/ecies/ecies.go
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ func ElectrumEncrypt(message []byte,

// Derive ECDH key
x, y := toPublicKey.Curve.ScalarMult(toPublicKey.X, toPublicKey.Y, ephemeralPrivateKey.D.Bytes())
ecdhKey := (&ec.PublicKey{X: x, Y: y}).SerializeCompressed()
ecdhKey := (&ec.PublicKey{X: x, Y: y}).Compressed()

// SHA512(ECDH_KEY)
key := c.Sha512(ecdhKey)
Expand All @@ -94,7 +94,7 @@ func ElectrumEncrypt(message []byte,
encrypted = append([]byte("BIE1"), cipherText...)
} else {
// encrypted = magic_bytes(4 bytes) + ephemeral_public_key(33 bytes) + cipher
encrypted = append(append([]byte("BIE1"), ephemeralPublicKey.SerializeCompressed()...), cipherText...)
encrypted = append(append([]byte("BIE1"), ephemeralPublicKey.Compressed()...), cipherText...)
}

mac := c.Sha256HMAC(encrypted, keyM)
Expand All @@ -119,7 +119,7 @@ func ElectrumDecrypt(encryptedData []byte, toPrivateKey *ec.PrivateKey, fromPubl
if fromPublicKey != nil {
// Use counterparty public key to derive shared secret
x, y := toPrivateKey.Curve.ScalarMult(fromPublicKey.X, fromPublicKey.Y, toPrivateKey.D.Bytes())
sharedSecret = (&ec.PublicKey{X: x, Y: y}).SerializeCompressed()
sharedSecret = (&ec.PublicKey{X: x, Y: y}).Compressed()
if len(encryptedData) > 69 { // 4 (magic) + 33 (pubkey) + 32 (mac)
cipherText = encryptedData[37 : len(encryptedData)-32]
} else {
Expand All @@ -132,7 +132,7 @@ func ElectrumDecrypt(encryptedData []byte, toPrivateKey *ec.PrivateKey, fromPubl
return nil, err
}
x, y := ephemeralPublicKey.Curve.ScalarMult(ephemeralPublicKey.X, ephemeralPublicKey.Y, toPrivateKey.D.Bytes())
sharedSecret = (&ec.PublicKey{X: x, Y: y}).SerializeCompressed()
sharedSecret = (&ec.PublicKey{X: x, Y: y}).Compressed()
cipherText = encryptedData[37 : len(encryptedData)-32]
}

Expand Down Expand Up @@ -172,7 +172,7 @@ func BitcoreEncrypt(message []byte,
fromPrivateKey, _ = ec.NewPrivateKey()
}

RBuf := fromPrivateKey.PubKey().ToDERBytes()
RBuf := fromPrivateKey.PubKey().ToDER()
P := toPublicKey.Mul(fromPrivateKey.D)

Sbuf := P.X.Bytes()
Expand Down
2 changes: 1 addition & 1 deletion docs/examples/keyshares_pk_to_backup/to_backup.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import (

func main() {
pk, _ := ec.PrivateKeyFromWif("KxPEP4DCP2a4g3YU5amfXjFH4kWmz8EHWrTugXocGWgWBbhGsX7a")
log.Println("Private key:", hex.EncodeToString(pk.PubKey().ToHash())[:8])
log.Println("Private key:", hex.EncodeToString(pk.PubKey().Hash())[:8])
totalShares := 5
threshold := 3
shares, _ := pk.ToBackupShares(threshold, totalShares)
Expand Down
10 changes: 5 additions & 5 deletions message/encrypted.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ func Encrypt(message []byte, sender *ec.PrivateKey, recipient *ec.PublicKey) ([]
return nil, err
}

priv := ec.NewSymmetricKey(sharedSecret.SerializeCompressed()[1:])
priv := ec.NewSymmetricKey(sharedSecret.Compressed()[1:])
skey := ec.NewSymmetricKey(priv.ToBytes())
ciphertext, err := skey.Encrypt(message)
if err != nil {
Expand All @@ -48,8 +48,8 @@ func Encrypt(message []byte, sender *ec.PrivateKey, recipient *ec.PublicKey) ([]
return nil, err
}

senderPublicKey := sender.PubKey().SerializeCompressed()
recipientDER := recipient.SerializeCompressed()
senderPublicKey := sender.PubKey().Compressed()
recipientDER := recipient.Compressed()

encryptedMessage := append(version, senderPublicKey...)
encryptedMessage = append(encryptedMessage, recipientDER...)
Expand Down Expand Up @@ -91,7 +91,7 @@ func Decrypt(message []byte, recipient *ec.PrivateKey) ([]byte, error) {
if err != nil {
return nil, err
}
actualRecipientDER := recipient.PubKey().SerializeCompressed()
actualRecipientDER := recipient.PubKey().Compressed()
if !bytes.Equal(expectedRecipientDER, actualRecipientDER) {
errorStr := "the encrypted message expects a recipient public key of %x, but the provided key is %x"
return nil, fmt.Errorf(errorStr, expectedRecipientDER, actualRecipientDER)
Expand Down Expand Up @@ -120,7 +120,7 @@ func Decrypt(message []byte, recipient *ec.PrivateKey) ([]byte, error) {
return nil, err
}

priv := ec.NewSymmetricKey(sharedSecret.SerializeCompressed()[1:])
priv := ec.NewSymmetricKey(sharedSecret.Compressed()[1:])
skey := ec.NewSymmetricKey(priv.ToBytes())
return skey.Decrypt(encrypted)
}
2 changes: 1 addition & 1 deletion message/encrypted_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ func TestEncryptedMessage(t *testing.T) {
if err == nil {
t.Fatalf("Expected an error, but got none")
}
expectedError := fmt.Sprintf("the encrypted message expects a recipient public key of %x, but the provided key is %x", recipientPub.SerializeCompressed(), wrongRecipient.PubKey().SerializeCompressed())
expectedError := fmt.Sprintf("the encrypted message expects a recipient public key of %x, but the provided key is %x", recipientPub.Compressed(), wrongRecipient.PubKey().Compressed())
if err.Error() != expectedError {
t.Errorf("Expected error: %s, but got: %s", expectedError, err.Error())
}
Expand Down
6 changes: 3 additions & 3 deletions message/signed.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,11 +40,11 @@ func Sign(message []byte, signer *ec.PrivateKey, verifier *ec.PublicKey) ([]byte
}
senderPublicKey := signer.PubKey()

sig := append(VERSION_BYTES, senderPublicKey.SerializeCompressed()...)
sig := append(VERSION_BYTES, senderPublicKey.Compressed()...)
if recipientAnyone {
sig = append(sig, 0)
} else {
sig = append(sig, verifier.SerializeCompressed()...)
sig = append(sig, verifier.Compressed()...)
}
sig = append(sig, keyID...)
signatureDER, err := signature.ToDER()
Expand Down Expand Up @@ -79,7 +79,7 @@ func Verify(message []byte, sig []byte, recipient *ec.PrivateKey) (bool, error)
if recipient == nil {
return false, nil
}
recipientDER := recipient.PubKey().SerializeCompressed()
recipientDER := recipient.PubKey().Compressed()
if !bytes.Equal(verifierDER, recipientDER) {
errorStr := "the recipient public key is %x but the signature requres the recipient to have public key %x"
err = fmt.Errorf(errorStr, recipientDER, verifierDER)
Expand Down
4 changes: 2 additions & 2 deletions primitives/ec/privatekey.go
Original file line number Diff line number Diff line change
Expand Up @@ -263,7 +263,7 @@ func (p *PrivateKey) ToKeyShares(threshold int, totalShares int) (keyShares *key
points = append(points, keyshares.NewPointInFiniteField(x, y))
}

integrity := hex.EncodeToString(p.PubKey().ToHash())[:8]
integrity := hex.EncodeToString(p.PubKey().Hash())[:8]
return keyshares.NewKeyShares(points, threshold, integrity), nil
}

Expand All @@ -289,7 +289,7 @@ func PrivateKeyFromKeyShares(keyShares *keyshares.KeyShares) (*PrivateKey, error
poly := keyshares.NewPolynomial(keyShares.Points, keyShares.Threshold)
polyBytes := poly.ValueAt(big.NewInt(0)).Bytes()
privateKey, publicKey := PrivateKeyFromBytes(polyBytes)
integrityHash := hex.EncodeToString(publicKey.ToHash())[:8]
integrityHash := hex.EncodeToString(publicKey.Hash())[:8]
if keyShares.Integrity != integrityHash {
return nil, fmt.Errorf("integrity hash mismatch %s != %s", keyShares.Integrity, integrityHash)
}
Expand Down
2 changes: 1 addition & 1 deletion primitives/ec/privatekey_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ func TestPrivKeys(t *testing.T) {
for _, test := range tests {
priv, pub := PrivateKeyFromBytes(test.key)

_, err := ParsePubKey(pub.SerializeUncompressed())
_, err := ParsePubKey(pub.Uncompressed())
if err != nil {
t.Errorf("%s privkey: %v", test.name, err)
continue
Expand Down
22 changes: 11 additions & 11 deletions primitives/ec/publickey.go
Original file line number Diff line number Diff line change
Expand Up @@ -142,17 +142,17 @@ func (p *PublicKey) ToECDSA() *ecdsa.PublicKey {
return (*ecdsa.PublicKey)(p)
}

// SerializeUncompressed serializes a public key in a 65-byte uncompressed
// Uncompressed serializes a public key in a 65-byte uncompressed
// format.
func (p *PublicKey) SerializeUncompressed() []byte {
func (p *PublicKey) Uncompressed() []byte {
b := make([]byte, 0, PubKeyBytesLenUncompressed)
b = append(b, pubkeyUncompressed)
b = paddedAppend(32, b, p.X.Bytes())
return paddedAppend(32, b, p.Y.Bytes())
}

// SerializeCompressed serializes a public key in a 33-byte compressed format.
func (p *PublicKey) SerializeCompressed() []byte {
// Compressed serializes a public key in a 33-byte compressed format.
func (p *PublicKey) Compressed() []byte {
b := make([]byte, 0, PubKeyBytesLenCompressed)
format := pubkeyCompressed
if isOdd(p.Y) {
Expand All @@ -162,8 +162,8 @@ func (p *PublicKey) SerializeCompressed() []byte {
return paddedAppend(32, b, p.X.Bytes())
}

// SerializeHybrid serializes a public key in a 65-byte hybrid format.
func (p *PublicKey) SerializeHybrid() []byte {
// Hybrid serializes a public key in a 65-byte hybrid format.
func (p *PublicKey) Hybrid() []byte {
b := make([]byte, 0, PubKeyBytesLenHybrid)
format := pubkeyHybrid
if isOdd(p.Y) {
Expand Down Expand Up @@ -226,9 +226,9 @@ func (p *PublicKey) Mul(k *big.Int) *PublicKey {
* @returns Returns the hash of the public key.
*
* @example
* const publicKeyHash = pubkey.ToHash()
* const publicKeyHash = pubkey.Hash()
*/
func (p *PublicKey) ToHash() []byte {
func (p *PublicKey) Hash() []byte {
return crypto.Ripemd160(crypto.Sha256(p.encode(true)))
}

Expand Down Expand Up @@ -259,13 +259,13 @@ func (p *PublicKey) encode(compact bool) []byte {
return append(append([]byte{0x04}, xBytes...), yBytes...)
}

func (p *PublicKey) ToDERBytes() []byte {
func (p *PublicKey) ToDER() []byte {
encoded := p.encode(true)
return encoded
}

func (p *PublicKey) ToDER() string {
return hex.EncodeToString(p.ToDERBytes())
func (p *PublicKey) ToDERHex() string {
return hex.EncodeToString(p.ToDER())
}

func (p *PublicKey) DeriveChild(privateKey *PrivateKey, invoiceNumber string) (*PublicKey, error) {
Expand Down
8 changes: 4 additions & 4 deletions primitives/ec/publickey_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -238,11 +238,11 @@ func TestPubKeys(t *testing.T) {
var pkStr []byte
switch test.format {
case pubkeyUncompressed:
pkStr = pk.SerializeUncompressed()
pkStr = pk.Uncompressed()
case pubkeyCompressed:
pkStr = pk.SerializeCompressed()
pkStr = pk.Compressed()
case pubkeyHybrid:
pkStr = pk.SerializeHybrid()
pkStr = pk.Hybrid()
}
if !bytes.Equal(test.key, pkStr) {
t.Errorf("%s pubkey: serialized keys do not match.",
Expand Down Expand Up @@ -341,7 +341,7 @@ func TestBRC42PublicVectors(t *testing.T) {
}

// Convert derived public key to string/hex and compare
derivedStr := hex.EncodeToString(derived.SerializeCompressed())
derivedStr := hex.EncodeToString(derived.Compressed())
if derivedStr != v.ExpectedPublicKey {
t.Errorf("Derived public key does not match expected: got %v, want %v", derivedStr, v.ExpectedPublicKey)
}
Expand Down
4 changes: 2 additions & 2 deletions script/address.go
Original file line number Diff line number Diff line change
Expand Up @@ -107,9 +107,9 @@ func NewAddressFromPublicKey(pubKey *ec.PublicKey, mainnet bool) (*Address, erro
func NewAddressFromPublicKeyWithCompression(pubKey *ec.PublicKey, mainnet bool, isCompressed bool) (*Address, error) {
var hash []byte
if isCompressed {
hash = crypto.Hash160(pubKey.SerializeCompressed())
hash = pubKey.Hash()
} else {
hash = crypto.Hash160(pubKey.SerializeUncompressed())
hash = crypto.Hash160(pubKey.Uncompressed())
}

// regtest := 111
Expand Down
30 changes: 25 additions & 5 deletions script/script.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"math/bits"
"strings"

ec "github.com/bitcoin-sv/go-sdk/primitives/ec"
"github.com/pkg/errors"
)

Expand Down Expand Up @@ -344,18 +345,37 @@ func MinPushSize(bb []byte) int {
return l + 5
}

// GetParts extracts the decoded chunks from the script.
func (s *Script) GetParts() ([]*ScriptChunk, error) {
// Chunks extracts the decoded chunks from the script.
func (s *Script) Chunks() ([]*ScriptChunk, error) {
return DecodeScript([]byte(*s))
}

// GetPublicKey extracts the public key from a P2PK script.
func (s *Script) GetPublicKey() (string, error) {
// PubKey extracts the public key from a P2PK script.
func (s *Script) PubKey() (*ec.PublicKey, error) {
if !s.IsP2PK() {
return nil, errors.New("script is not of type ScriptTypePubKey")
}

parts, err := s.Chunks()
if err != nil {
return nil, err
}

if len(parts) == 0 || parts[0] == nil {
return nil, errors.New("invalid script parts or missing public key part")
}

pubKey := parts[0].Data
return ec.ParsePubKey(pubKey)
}

// PubKeyHex extracts the public key from a P2PK script.
func (s *Script) PubKeyHex() (string, error) {
if !s.IsP2PK() {
return "", errors.New("script is not of type ScriptTypePubKey")
}

parts, err := s.GetParts()
parts, err := s.Chunks()
if err != nil {
return "", err
}
Expand Down
Loading

0 comments on commit f5aee91

Please sign in to comment.