// TestSigCacheAddEvictEntry tests the eviction case where a new signature // triplet is added to a full signature cache which should trigger randomized // eviction, followed by adding the new element to the cache. func TestSigCacheAddEvictEntry(t *testing.T) { // Create a sigcache that can hold up to 100 entries. sigCacheSize := uint(100) sigCache := NewSigCache(sigCacheSize) // Fill the sigcache up with some random sig triplets. for i := uint(0); i < sigCacheSize; i++ { msg, sig, key, err := genRandomSig() if err != nil { t.Fatalf("unable to generate random signature test data") } sigCache.Add(*msg, sig, key) sigCopy, _ := btcec.ParseSignature(sig.Serialize(), btcec.S256()) keyCopy, _ := btcec.ParsePubKey(key.SerializeCompressed(), btcec.S256()) if !sigCache.Exists(*msg, sigCopy, keyCopy) { t.Errorf("previously added item not found in signature" + "cache") } } // The sigcache should now have sigCacheSize entries within it. if uint(len(sigCache.validSigs)) != sigCacheSize { t.Fatalf("sigcache should now have %v entries, instead it has %v", sigCacheSize, len(sigCache.validSigs)) } // Add a new entry, this should cause eviction of a randomly chosen // previous entry. msgNew, sigNew, keyNew, err := genRandomSig() if err != nil { t.Fatalf("unable to generate random signature test data") } sigCache.Add(*msgNew, sigNew, keyNew) // The sigcache should still have sigCache entries. if uint(len(sigCache.validSigs)) != sigCacheSize { t.Fatalf("sigcache should now have %v entries, instead it has %v", sigCacheSize, len(sigCache.validSigs)) } // The entry added above should be found within the sigcache. sigNewCopy, _ := btcec.ParseSignature(sigNew.Serialize(), btcec.S256()) keyNewCopy, _ := btcec.ParsePubKey(keyNew.SerializeCompressed(), btcec.S256()) if !sigCache.Exists(*msgNew, sigNewCopy, keyNewCopy) { t.Fatalf("previously added item not found in signature cache") } }
func TestPubKeys(t *testing.T) { for _, test := range pubKeyTests { pk, err := btcec.ParsePubKey(test.key, btcec.S256()) if err != nil { if test.isValid { t.Errorf("%s pubkey failed when shouldn't %v", test.name, err) } continue } if !test.isValid { t.Errorf("%s counted as valid when it should fail", test.name) continue } var pkStr []byte switch test.format { case btcec.TstPubkeyUncompressed: pkStr = (*btcec.PublicKey)(pk).SerializeUncompressed() case btcec.TstPubkeyCompressed: pkStr = (*btcec.PublicKey)(pk).SerializeCompressed() case btcec.TstPubkeyHybrid: pkStr = (*btcec.PublicKey)(pk).SerializeHybrid() } if !bytes.Equal(test.key, pkStr) { t.Errorf("%s pubkey: serialized keys do not match.", test.name) spew.Dump(test.key) spew.Dump(pkStr) } } }
// TestSigCacheAddMaxEntriesZeroOrNegative tests that if a sigCache is created // with a max size <= 0, then no entries are added to the sigcache at all. func TestSigCacheAddMaxEntriesZeroOrNegative(t *testing.T) { // Create a sigcache that can hold up to 0 entries. sigCache := NewSigCache(0) // Generate a random sigCache entry triplet. msg1, sig1, key1, err := genRandomSig() if err != nil { t.Errorf("unable to generate random signature test data") } // Add the triplet to the signature cache. sigCache.Add(*msg1, sig1, key1) // The generated triplet should not be found. sig1Copy, _ := btcec.ParseSignature(sig1.Serialize(), btcec.S256()) key1Copy, _ := btcec.ParsePubKey(key1.SerializeCompressed(), btcec.S256()) if sigCache.Exists(*msg1, sig1Copy, key1Copy) { t.Errorf("previously added signature found in sigcache, but" + "shouldn't have been") } // There shouldn't be any entries in the sigCache. if len(sigCache.validSigs) != 0 { t.Errorf("%v items found in sigcache, no items should have"+ "been added", len(sigCache.validSigs)) } }
// TstAddressPubKey makes an AddressPubKey, setting the unexported fields with // the parameters. func TstAddressPubKey(serializedPubKey []byte, pubKeyFormat PubKeyFormat, netID byte) *AddressPubKey { pubKey, _ := btcec.ParsePubKey(serializedPubKey, btcec.S256()) return &AddressPubKey{ pubKeyFormat: pubKeyFormat, pubKey: (*btcec.PublicKey)(pubKey), pubKeyHashID: netID, } }
// NewKeyFromString returns a new extended key instance from a base58-encoded // extended key. func NewKeyFromString(key string) (*ExtendedKey, error) { // The base58-decoded extended key must consist of a serialized payload // plus an additional 4 bytes for the checksum. decoded := base58.Decode(key) if len(decoded) != serializedKeyLen+4 { return nil, ErrInvalidKeyLen } // The serialized format is: // version (4) || depth (1) || parent fingerprint (4)) || // child num (4) || chain code (32) || key data (33) || checksum (4) // Split the payload and checksum up and ensure the checksum matches. payload := decoded[:len(decoded)-4] checkSum := decoded[len(decoded)-4:] expectedCheckSum := wire.DoubleSha256(payload)[:4] if !bytes.Equal(checkSum, expectedCheckSum) { return nil, ErrBadChecksum } // Deserialize each of the payload fields. version := payload[:4] depth := uint16(payload[4:5][0]) parentFP := payload[5:9] childNum := binary.BigEndian.Uint32(payload[9:13]) chainCode := payload[13:45] keyData := payload[45:78] // The key data is a private key if it starts with 0x00. Serialized // compressed pubkeys either start with 0x02 or 0x03. isPrivate := keyData[0] == 0x00 if isPrivate { // Ensure the private key is valid. It must be within the range // of the order of the secp256k1 curve and not be 0. keyData = keyData[1:] keyNum := new(big.Int).SetBytes(keyData) if keyNum.Cmp(btcec.S256().N) >= 0 || keyNum.Sign() == 0 { return nil, ErrUnusableSeed } } else { // Ensure the public key parses correctly and is actually on the // secp256k1 curve. _, err := btcec.ParsePubKey(keyData, btcec.S256()) if err != nil { return nil, err } } return newExtendedKey(version, keyData, chainCode, parentFP, depth, childNum, isPrivate), nil }
func TestPrivKeys(t *testing.T) { tests := []struct { name string key []byte }{ { name: "check curve", key: []byte{ 0xea, 0xf0, 0x2c, 0xa3, 0x48, 0xc5, 0x24, 0xe6, 0x39, 0x26, 0x55, 0xba, 0x4d, 0x29, 0x60, 0x3c, 0xd1, 0xa7, 0x34, 0x7d, 0x9d, 0x65, 0xcf, 0xe9, 0x3c, 0xe1, 0xeb, 0xff, 0xdc, 0xa2, 0x26, 0x94, }, }, } for _, test := range tests { priv, pub := btcec.PrivKeyFromBytes(btcec.S256(), test.key) _, err := btcec.ParsePubKey( pub.SerializeUncompressed(), btcec.S256()) if err != nil { t.Errorf("%s privkey: %v", test.name, err) continue } hash := []byte{0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9} sig, err := priv.Sign(hash) if err != nil { t.Errorf("%s could not sign: %v", test.name, err) continue } if !sig.Verify(hash, pub) { t.Errorf("%s could not verify: %v", test.name, err) continue } serializedKey := priv.Serialize() if !bytes.Equal(serializedKey, test.key) { t.Errorf("%s unexpected serialized bytes - got: %x, "+ "want: %x", test.name, serializedKey, test.key) } } }
// This example demonstrates encrypting a message for a public key that is first // parsed from raw bytes, then decrypting it using the corresponding private key. func Example_encryptMessage() { // Decode the hex-encoded pubkey of the recipient. pubKeyBytes, err := hex.DecodeString("04115c42e757b2efb7671c578530ec191a1" + "359381e6a71127a9d37c486fd30dae57e76dc58f693bd7e7010358ce6b165e483a29" + "21010db67ac11b1b51b651953d2") // uncompressed pubkey if err != nil { fmt.Println(err) return } pubKey, err := btcec.ParsePubKey(pubKeyBytes, btcec.S256()) if err != nil { fmt.Println(err) return } // Encrypt a message decryptable by the private key corresponding to pubKey message := "test message" ciphertext, err := btcec.Encrypt(pubKey, []byte(message)) if err != nil { fmt.Println(err) return } // Decode the hex-encoded private key. pkBytes, err := hex.DecodeString("a11b0a4e1a132305652ee7a8eb7848f6ad" + "5ea381e3ce20a2c086a2e388230811") if err != nil { fmt.Println(err) return } // note that we already have corresponding pubKey privKey, _ := btcec.PrivKeyFromBytes(btcec.S256(), pkBytes) // Try decrypting and verify if it's the same message. plaintext, err := btcec.Decrypt(privKey, ciphertext) if err != nil { fmt.Println(err) return } fmt.Println(string(plaintext)) // Output: // test message }
// TestSigCacheAddExists tests the ability to add, and later check the // existence of a signature triplet in the signature cache. func TestSigCacheAddExists(t *testing.T) { sigCache := NewSigCache(200) // Generate a random sigCache entry triplet. msg1, sig1, key1, err := genRandomSig() if err != nil { t.Errorf("unable to generate random signature test data") } // Add the triplet to the signature cache. sigCache.Add(*msg1, sig1, key1) // The previously added triplet should now be found within the sigcache. sig1Copy, _ := btcec.ParseSignature(sig1.Serialize(), btcec.S256()) key1Copy, _ := btcec.ParsePubKey(key1.SerializeCompressed(), btcec.S256()) if !sigCache.Exists(*msg1, sig1Copy, key1Copy) { t.Errorf("previously added item not found in signature cache") } }
// This example demonstrates verifying a secp256k1 signature against a public // key that is first parsed from raw bytes. The signature is also parsed from // raw bytes. func Example_verifySignature() { // Decode hex-encoded serialized public key. pubKeyBytes, err := hex.DecodeString("02a673638cb9587cb68ea08dbef685c" + "6f2d2a751a8b3c6f2a7e9a4999e6e4bfaf5") if err != nil { fmt.Println(err) return } pubKey, err := btcec.ParsePubKey(pubKeyBytes, btcec.S256()) if err != nil { fmt.Println(err) return } // Decode hex-encoded serialized signature. sigBytes, err := hex.DecodeString("30450220090ebfb3690a0ff115bb1b38b" + "8b323a667b7653454f1bccb06d4bbdca42c2079022100ec95778b51e707" + "1cb1205f8bde9af6592fc978b0452dafe599481c46d6b2e479") if err != nil { fmt.Println(err) return } signature, err := btcec.ParseSignature(sigBytes, btcec.S256()) if err != nil { fmt.Println(err) return } // Verify the signature for the message using the public key. message := "test message" messageHash := wire.DoubleSha256([]byte(message)) verified := signature.Verify(messageHash, pubKey) fmt.Println("Signature Verified?", verified) // Output: // Signature Verified? true }
// NewAddressPubKey returns a new AddressPubKey which represents a pay-to-pubkey // address. The serializedPubKey parameter must be a valid pubkey and can be // uncompressed, compressed, or hybrid. func NewAddressPubKey(serializedPubKey []byte, net *chaincfg.Params) (*AddressPubKey, error) { pubKey, err := btcec.ParsePubKey(serializedPubKey, btcec.S256()) if err != nil { return nil, err } // Set the format of the pubkey. This probably should be returned // from btcec, but do it here to avoid API churn. We already know the // pubkey is valid since it parsed above, so it's safe to simply examine // the leading byte to get the format. pkFormat := PKFUncompressed switch serializedPubKey[0] { case 0x02, 0x03: pkFormat = PKFCompressed case 0x06, 0x07: pkFormat = PKFHybrid } return &AddressPubKey{ pubKeyFormat: pkFormat, pubKey: pubKey, pubKeyHashID: net.PubKeyHashAddrID, }, nil }
// ECPubKey converts the extended key to a btcec public key and returns it. func (k *ExtendedKey) ECPubKey() (*btcec.PublicKey, error) { return btcec.ParsePubKey(k.pubKeyBytes(), btcec.S256()) }
// Child returns a derived child extended key at the given index. When this // extended key is a private extended key (as determined by the IsPrivate // function), a private extended key will be derived. Otherwise, the derived // extended key will be also be a public extended key. // // When the index is greater to or equal than the HardenedKeyStart constant, the // derived extended key will be a hardened extended key. It is only possible to // derive a hardended extended key from a private extended key. Consequently, // this function will return ErrDeriveHardFromPublic if a hardened child // extended key is requested from a public extended key. // // A hardened extended key is useful since, as previously mentioned, it requires // a parent private extended key to derive. In other words, normal child // extended public keys can be derived from a parent public extended key (no // knowledge of the parent private key) whereas hardened extended keys may not // be. // // NOTE: There is an extremely small chance (< 1 in 2^127) the specific child // index does not derive to a usable child. The ErrInvalidChild error will be // returned if this should occur, and the caller is expected to ignore the // invalid child and simply increment to the next index. func (k *ExtendedKey) Child(i uint32) (*ExtendedKey, error) { // There are four scenarios that could happen here: // 1) Private extended key -> Hardened child private extended key // 2) Private extended key -> Non-hardened child private extended key // 3) Public extended key -> Non-hardened child public extended key // 4) Public extended key -> Hardened child public extended key (INVALID!) // Case #4 is invalid, so error out early. // A hardened child extended key may not be created from a public // extended key. isChildHardened := i >= HardenedKeyStart if !k.isPrivate && isChildHardened { return nil, ErrDeriveHardFromPublic } // The data used to derive the child key depends on whether or not the // child is hardened per [BIP32]. // // For hardened children: // 0x00 || ser256(parentKey) || ser32(i) // // For normal children: // serP(parentPubKey) || ser32(i) keyLen := 33 data := make([]byte, keyLen+4) if isChildHardened { // Case #1. // When the child is a hardened child, the key is known to be a // private key due to the above early return. Pad it with a // leading zero as required by [BIP32] for deriving the child. copy(data[1:], k.key) } else { // Case #2 or #3. // This is either a public or private extended key, but in // either case, the data which is used to derive the child key // starts with the secp256k1 compressed public key bytes. copy(data, k.pubKeyBytes()) } binary.BigEndian.PutUint32(data[keyLen:], i) // Take the HMAC-SHA512 of the current key's chain code and the derived // data: // I = HMAC-SHA512(Key = chainCode, Data = data) hmac512 := hmac.New(sha512.New, k.chainCode) hmac512.Write(data) ilr := hmac512.Sum(nil) // Split "I" into two 32-byte sequences Il and Ir where: // Il = intermediate key used to derive the child // Ir = child chain code il := ilr[:len(ilr)/2] childChainCode := ilr[len(ilr)/2:] // Both derived public or private keys rely on treating the left 32-byte // sequence calculated above (Il) as a 256-bit integer that must be // within the valid range for a secp256k1 private key. There is a small // chance (< 1 in 2^127) this condition will not hold, and in that case, // a child extended key can't be created for this index and the caller // should simply increment to the next index. ilNum := new(big.Int).SetBytes(il) if ilNum.Cmp(btcec.S256().N) >= 0 || ilNum.Sign() == 0 { return nil, ErrInvalidChild } // The algorithm used to derive the child key depends on whether or not // a private or public child is being derived. // // For private children: // childKey = parse256(Il) + parentKey // // For public children: // childKey = serP(point(parse256(Il)) + parentKey) var isPrivate bool var childKey []byte if k.isPrivate { // Case #1 or #2. // Add the parent private key to the intermediate private key to // derive the final child key. // // childKey = parse256(Il) + parenKey keyNum := new(big.Int).SetBytes(k.key) ilNum.Add(ilNum, keyNum) ilNum.Mod(ilNum, btcec.S256().N) childKey = ilNum.Bytes() isPrivate = true } else { // Case #3. // Calculate the corresponding intermediate public key for // intermediate private key. ilx, ily := btcec.S256().ScalarBaseMult(il) if ilx.Sign() == 0 || ily.Sign() == 0 { return nil, ErrInvalidChild } // Convert the serialized compressed parent public key into X // and Y coordinates so it can be added to the intermediate // public key. pubKey, err := btcec.ParsePubKey(k.key, btcec.S256()) if err != nil { return nil, err } // Add the intermediate public key to the parent public key to // derive the final child key. // // childKey = serP(point(parse256(Il)) + parentKey) childX, childY := btcec.S256().Add(ilx, ily, pubKey.X, pubKey.Y) pk := btcec.PublicKey{Curve: btcec.S256(), X: childX, Y: childY} childKey = pk.SerializeCompressed() } // The fingerprint of the parent for the derived child is the first 4 // bytes of the RIPEMD160(SHA256(parentPubKey)). parentFP := coinutil.Hash160(k.pubKeyBytes())[:4] return newExtendedKey(k.version, childKey, childChainCode, parentFP, k.depth+1, i, isPrivate), nil }
func TestChaining(t *testing.T) { tests := []struct { name string cc []byte origPrivateKey []byte nextPrivateKeyUncompressed []byte nextPrivateKeyCompressed []byte nextPublicKeyUncompressed []byte nextPublicKeyCompressed []byte }{ { name: "chaintest 1", cc: []byte("3318959fff419ab8b556facb3c429a86"), origPrivateKey: []byte("5ffc975976eaaa1f7b179f384ebbc053"), nextPrivateKeyUncompressed: []byte{ 0xd3, 0xfe, 0x2e, 0x96, 0x44, 0x12, 0x2d, 0xaa, 0x80, 0x8e, 0x36, 0x17, 0xb5, 0x9f, 0x8c, 0xd2, 0x72, 0x8c, 0xaf, 0xf1, 0xdb, 0xd6, 0x4a, 0x92, 0xd7, 0xc7, 0xee, 0x2b, 0x56, 0x34, 0xe2, 0x87, }, nextPrivateKeyCompressed: []byte{ 0x08, 0x56, 0x7a, 0x1b, 0x89, 0x56, 0x2e, 0xfa, 0xb4, 0x02, 0x59, 0x69, 0x10, 0xc3, 0x60, 0x1f, 0x34, 0xf0, 0x55, 0x02, 0x8a, 0xbf, 0x37, 0xf5, 0x22, 0x80, 0x9f, 0xd2, 0xe5, 0x42, 0x5b, 0x2d, }, nextPublicKeyUncompressed: []byte{ 0x04, 0xdd, 0x70, 0x31, 0xa5, 0xf9, 0x06, 0x70, 0xd3, 0x9a, 0x24, 0x5b, 0xd5, 0x73, 0xdd, 0xb6, 0x15, 0x81, 0x0b, 0x78, 0x19, 0xbc, 0xc8, 0x26, 0xc9, 0x16, 0x86, 0x73, 0xae, 0xe4, 0xc0, 0xed, 0x39, 0x81, 0xb4, 0x86, 0x2d, 0x19, 0x8c, 0x67, 0x9c, 0x93, 0x99, 0xf6, 0xd2, 0x3f, 0xd1, 0x53, 0x9e, 0xed, 0xbd, 0x07, 0xd6, 0x4f, 0xa9, 0x81, 0x61, 0x85, 0x46, 0x84, 0xb1, 0xa0, 0xed, 0xbc, 0xa7, }, nextPublicKeyCompressed: []byte{ 0x02, 0x2c, 0x48, 0x73, 0x37, 0x35, 0x74, 0x7f, 0x05, 0x58, 0xc1, 0x4e, 0x0d, 0x18, 0xc2, 0xbf, 0xcc, 0x83, 0xa2, 0x4d, 0x64, 0xab, 0xba, 0xea, 0xeb, 0x4c, 0xcd, 0x4c, 0x0c, 0x21, 0xc4, 0x30, 0x0f, }, }, } for _, test := range tests { // Create both uncompressed and compressed public keys for original // private key. origPubUncompressed := pubkeyFromPrivkey(test.origPrivateKey, false) origPubCompressed := pubkeyFromPrivkey(test.origPrivateKey, true) // Create next chained private keys, chained from both the uncompressed // and compressed pubkeys. nextPrivUncompressed, err := chainedPrivKey(test.origPrivateKey, origPubUncompressed, test.cc) if err != nil { t.Errorf("%s: Uncompressed chainedPrivKey failed: %v", test.name, err) return } nextPrivCompressed, err := chainedPrivKey(test.origPrivateKey, origPubCompressed, test.cc) if err != nil { t.Errorf("%s: Compressed chainedPrivKey failed: %v", test.name, err) return } // Verify that the new private keys match the expected values // in the test case. if !bytes.Equal(nextPrivUncompressed, test.nextPrivateKeyUncompressed) { t.Errorf("%s: Next private key (from uncompressed pubkey) does not match expected.\nGot: %s\nExpected: %s", test.name, spew.Sdump(nextPrivUncompressed), spew.Sdump(test.nextPrivateKeyUncompressed)) return } if !bytes.Equal(nextPrivCompressed, test.nextPrivateKeyCompressed) { t.Errorf("%s: Next private key (from compressed pubkey) does not match expected.\nGot: %s\nExpected: %s", test.name, spew.Sdump(nextPrivCompressed), spew.Sdump(test.nextPrivateKeyCompressed)) return } // Create the next pubkeys generated from the next private keys. nextPubUncompressedFromPriv := pubkeyFromPrivkey(nextPrivUncompressed, false) nextPubCompressedFromPriv := pubkeyFromPrivkey(nextPrivCompressed, true) // Create the next pubkeys by chaining directly off the original // pubkeys (without using the original's private key). nextPubUncompressedFromPub, err := chainedPubKey(origPubUncompressed, test.cc) if err != nil { t.Errorf("%s: Uncompressed chainedPubKey failed: %v", test.name, err) return } nextPubCompressedFromPub, err := chainedPubKey(origPubCompressed, test.cc) if err != nil { t.Errorf("%s: Compressed chainedPubKey failed: %v", test.name, err) return } // Public keys (used to generate the bitcoin address) MUST match. if !bytes.Equal(nextPubUncompressedFromPriv, nextPubUncompressedFromPub) { t.Errorf("%s: Uncompressed public keys do not match.", test.name) } if !bytes.Equal(nextPubCompressedFromPriv, nextPubCompressedFromPub) { t.Errorf("%s: Compressed public keys do not match.", test.name) } // Verify that all generated public keys match the expected // values in the test case. if !bytes.Equal(nextPubUncompressedFromPub, test.nextPublicKeyUncompressed) { t.Errorf("%s: Next uncompressed public keys do not match expected value.\nGot: %s\nExpected: %s", test.name, spew.Sdump(nextPubUncompressedFromPub), spew.Sdump(test.nextPublicKeyUncompressed)) return } if !bytes.Equal(nextPubCompressedFromPub, test.nextPublicKeyCompressed) { t.Errorf("%s: Next compressed public keys do not match expected value.\nGot: %s\nExpected: %s", test.name, spew.Sdump(nextPubCompressedFromPub), spew.Sdump(test.nextPublicKeyCompressed)) return } // Sign data with the next private keys and verify signature with // the next pubkeys. pubkeyUncompressed, err := btcec.ParsePubKey(nextPubUncompressedFromPub, btcec.S256()) if err != nil { t.Errorf("%s: Unable to parse next uncompressed pubkey: %v", test.name, err) return } pubkeyCompressed, err := btcec.ParsePubKey(nextPubCompressedFromPub, btcec.S256()) if err != nil { t.Errorf("%s: Unable to parse next compressed pubkey: %v", test.name, err) return } privkeyUncompressed := &btcec.PrivateKey{ PublicKey: *pubkeyUncompressed.ToECDSA(), D: new(big.Int).SetBytes(nextPrivUncompressed), } privkeyCompressed := &btcec.PrivateKey{ PublicKey: *pubkeyCompressed.ToECDSA(), D: new(big.Int).SetBytes(nextPrivCompressed), } data := "String to sign." sig, err := privkeyUncompressed.Sign([]byte(data)) if err != nil { t.Errorf("%s: Unable to sign data with next private key (chained from uncompressed pubkey): %v", test.name, err) return } ok := sig.Verify([]byte(data), privkeyUncompressed.PubKey()) if !ok { t.Errorf("%s: btcec signature verification failed for next keypair (chained from uncompressed pubkey).", test.name) return } sig, err = privkeyCompressed.Sign([]byte(data)) if err != nil { t.Errorf("%s: Unable to sign data with next private key (chained from compressed pubkey): %v", test.name, err) return } ok = sig.Verify([]byte(data), privkeyCompressed.PubKey()) if !ok { t.Errorf("%s: btcec signature verification failed for next keypair (chained from compressed pubkey).", test.name) return } } }