Example #1
0
// 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.  The net parameter must be
// btcwire.MainNet or btcwire.TestNet3.
func NewAddressPubKey(serializedPubKey []byte, net btcwire.BitcoinNet) (*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:
		fallthrough
	case 0x03:
		pkFormat = PKFCompressed

	case 0x06:
		fallthrough
	case 0x07:
		pkFormat = PKFHybrid
	}

	ecPubKey := (*btcec.PublicKey)(pubKey)
	addr := &AddressPubKey{pubKeyFormat: pkFormat, pubKey: ecPubKey, net: net}
	return addr, nil
}
Example #2
0
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)
		}
	}
}
Example #3
0
func addPoints(a []byte, b []byte) []byte {
	ap, err := btcec.ParsePubKey(a, btcec.S256())
	if err != nil {
		panic(err)
	}
	bp, err := btcec.ParsePubKey(b, btcec.S256())
	if err != nil {
		panic(err)
	}
	sumX, sumY := btcec.S256().Add(ap.X, ap.Y, bp.X, bp.Y)
	sum := (*btcec.PublicKey)(&ecdsa.PublicKey{
		Curve: btcec.S256(),
		X:     sumX,
		Y:     sumY,
	})
	return sum.SerializeCompressed()
}
Example #4
0
// TstAddressPubKey makes an AddressPubKey, setting the unexported fields with
// the parameters.
func TstAddressPubKey(serializedPubKey []byte, pubKeyFormat PubKeyFormat,
	net btcwire.BitcoinNet) *AddressPubKey {

	pubKey, _ := btcec.ParsePubKey(serializedPubKey, btcec.S256())
	return &AddressPubKey{
		pubKeyFormat: pubKeyFormat,
		pubKey:       (*btcec.PublicKey)(pubKey),
		net:          net,
	}
}
Example #5
0
// 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,
	}
}
Example #6
0
// Verifies a hash using DER encoded signature
func Verify(pubKey, signature, hash []byte) (bool, error) {
	sig, err := btcec.ParseDERSignature(signature, btcec.S256())
	if err != nil {
		return false, err
	}
	pk, err := btcec.ParsePubKey(pubKey, btcec.S256())
	if err != nil {
		return false, nil
	}
	return sig.Verify(hash, pk), nil
}
Example #7
0
func TestPrivKeys(t *testing.T) {
	for _, test := range privKeyTests {
		_, 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
		}
	}
}
Example #8
0
// 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 := btcutil.Base58Decode(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 := btcwire.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
}
Example #9
0
func TestPrivKeys(t *testing.T) {
	for _, test := range privKeyTests {
		x, y := btcec.S256().ScalarBaseMult(test.key)
		pub := (*btcec.PublicKey)(&ecdsa.PublicKey{
			Curve: btcec.S256(),
			X:     x,
			Y:     y,
		})
		_, err := btcec.ParsePubKey(pub.SerializeUncompressed(), btcec.S256())
		if err != nil {
			t.Errorf("%s privkey: %v", test.name, err)
			continue
		}
	}
}
Example #10
0
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)
		}
	}
}
Example #11
0
// 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 := btcwire.DoubleSha256([]byte(message))
	verified := signature.Verify(messageHash, pubKey)
	fmt.Println("Signature Verified?", verified)

	// Output:
	// Signature Verified? true
}
Example #12
0
// 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 *btcnet.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
}
Example #13
0
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 := &ecdsa.PrivateKey{
			PublicKey: *pubkeyUncompressed.ToECDSA(),
			D:         new(big.Int).SetBytes(nextPrivUncompressed),
		}
		privkeyCompressed := &ecdsa.PrivateKey{
			PublicKey: *pubkeyCompressed.ToECDSA(),
			D:         new(big.Int).SetBytes(nextPrivCompressed),
		}
		data := "String to sign."
		r, s, err := ecdsa.Sign(rand.Reader, privkeyUncompressed, []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 := ecdsa.Verify(&privkeyUncompressed.PublicKey, []byte(data), r, s)
		if !ok {
			t.Errorf("%s: ecdsa verification failed for next keypair (chained from uncompressed pubkey).",
				test.name)
			return
		}
		r, s, err = ecdsa.Sign(rand.Reader, privkeyCompressed, []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 = ecdsa.Verify(&privkeyCompressed.PublicKey, []byte(data), r, s)
		if !ok {
			t.Errorf("%s: ecdsa verification failed for next keypair (chained from compressed pubkey).",
				test.name)
			return
		}
	}
}
Example #14
0
func processPubKeyHash(db btcdb.Db, rd *rData) error {
	sigScript := rd.txIn.SignatureScript
	pkScript := rd.txPrevOut.PkScript
	script, err := btcscript.NewScript(sigScript, pkScript, rd.txInIndex, rd.tx.MsgTx(), 0)
	if err != nil {
		return fmt.Errorf("failed btcscript.NewScript - h %v: %v\n", rd.in.H, err)
	}

	for script.Next() != btcscript.OP_CHECKSIG {
		_, err := script.Step()
		if err != nil {
			return fmt.Errorf("Failed Step - in %v: %v\n", rd.in, err)
		}
	}

	data := script.GetStack()

	rd.sigStr = data[0]
	rd.pkStr = data[1]

	aPubKey, err := btcutil.NewAddressPubKey(rd.pkStr, &btcnet.MainNetParams)
	if err != nil {
		return fmt.Errorf("Pubkey parse error: %v", err)
	}
	rd.address = aPubKey.EncodeAddress()
	rd.compressed = aPubKey.Format() == btcutil.PKFCompressed

	// From github.com/conformal/btcscript/opcode.go

	// Signature actually needs needs to be longer than this, but we need
	// at least  1 byte for the below. btcec will check full length upon
	// parsing the signature.
	if len(rd.sigStr) < 1 {
		return fmt.Errorf("OP_CHECKSIG ERROR")
	}

	// Trim off hashtype from the signature string.
	hashType := rd.sigStr[len(rd.sigStr)-1]
	sigStr := rd.sigStr[:len(rd.sigStr)-1]

	// Get script from the last OP_CODESEPARATOR and without any subsequent
	// OP_CODESEPARATORs
	subScript := script.SubScript()

	// Unlikely to hit any cases here, but remove the signature from
	// the script if present.
	subScript = btcscript.RemoveOpcodeByData(subScript, sigStr)

	hash := btcscript.CalcScriptHash(subScript, hashType, rd.tx.MsgTx(), rd.txInIndex)

	pubKey, err := btcec.ParsePubKey(rd.pkStr, btcec.S256())
	if err != nil {
		return fmt.Errorf("OP_CHECKSIG ERROR")
	}

	signature, err := btcec.ParseSignature(sigStr, btcec.S256())
	if err != nil {
		return fmt.Errorf("OP_CHECKSIG ERROR")
	}

	// log.Printf("op_checksig\n"+
	//  "pubKey:\n%v"+
	//  "pubKey.X: %v\n"+
	//  "pubKey.Y: %v\n"+
	//  "signature.R: %v\n"+
	//  "signature.S: %v\n"+
	//  "checkScriptHash:\n%v",
	//  hex.Dump(pkStr), pubKey.X, pubKey.Y,
	//  signature.R, signature.S, hex.Dump(hash))

	if ok := ecdsa.Verify(pubKey.ToECDSA(), hash, signature.R, signature.S); !ok {
		return fmt.Errorf("OP_CHECKSIG FAIL")
	}

	rd.signature = signature
	rd.pubKey = pubKey
	rd.hash = hash

	return nil
}
Example #15
0
// Returns public key in golang format
func (k PubKey) GoPubKey() (*ecdsa.PublicKey, error) {
	pk, err := btcec.ParsePubKey(k, btcec.S256())
	return (*ecdsa.PublicKey)(pk), err
}
Example #16
0
// 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())
}
Example #17
0
// 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 := btcutil.Hash160(k.pubKeyBytes())[:4]
	return newExtendedKey(k.version, childKey, childChainCode, parentFP,
		k.depth+1, i, isPrivate), nil
}
Example #18
0
func ParsePublicKey(b []byte) (*btcec.PublicKey, error) {
	key, err := btcec.ParsePubKey(b, btcec.S256())
	return (*btcec.PublicKey)(key), err
}
Example #19
0
func TestWalletPubkeyChaining(t *testing.T) {
	// Set a reasonable keypool size that isn't too big nor too small for testing.
	const keypoolSize = 5

	w, err := NewWallet("banana wallet", "A wallet for testing.",
		[]byte("banana"), btcwire.MainNet, &BlockStamp{}, keypoolSize)
	if err != nil {
		t.Error("Error creating new wallet: " + err.Error())
		return
	}
	if !w.IsLocked() {
		t.Error("New wallet is not locked.")
	}

	// Wallet should have a total of 6 addresses, one for the root, plus 5 in
	// the keypool with their private keys set.  Ask for as many new addresses
	// as needed to deplete the pool.
	for i := 0; i < keypoolSize; i++ {
		_, err := w.NextChainedAddress(&BlockStamp{}, keypoolSize)
		if err != nil {
			t.Errorf("Error getting next address from keypool: %v", err)
			return
		}
	}

	// Get next chained address after depleting the keypool.  This will extend
	// the chain based on the last pubkey, not privkey.
	addrWithoutPrivkey, err := w.NextChainedAddress(&BlockStamp{}, keypoolSize)
	if err != nil {
		t.Errorf("Failed to extend address chain from pubkey: %v", err)
		return
	}

	// Lookup address info.  This should succeed even without the private
	// key available.
	info, err := w.AddressInfo(addrWithoutPrivkey)
	if err != nil {
		t.Errorf("Failed to get info about address without private key: %v", err)
		return
	}
	// sanity checks
	if !info.Compressed {
		t.Errorf("Pubkey should be compressed.")
		return
	}
	if info.Imported {
		t.Errorf("Should not be marked as imported.")
		return
	}

	// Try to lookup it's private key.  This should fail.
	_, err = w.AddressKey(addrWithoutPrivkey)
	if err == nil {
		t.Errorf("Incorrectly returned nil error for looking up private key for address without one saved.")
		return
	}

	// Deserialize w and serialize into a new wallet.  The rest of the checks
	// in this test test against both a fresh, as well as an "opened and closed"
	// wallet with the missing private key.
	serializedWallet := new(bytes.Buffer)
	_, err = w.WriteTo(serializedWallet)
	if err != nil {
		t.Errorf("Error writing wallet with missing private key: %v", err)
		return
	}
	w2 := new(Wallet)
	_, err = w2.ReadFrom(serializedWallet)
	if err != nil {
		t.Errorf("Error reading wallet with missing private key: %v", err)
		return
	}

	// Unlock wallet.  This should trigger creating the private key for
	// the address.
	if err = w.Unlock([]byte("banana")); err != nil {
		t.Errorf("Can't unlock original wallet: %v", err)
		return
	}
	if err = w2.Unlock([]byte("banana")); err != nil {
		t.Errorf("Can't unlock re-read wallet: %v", err)
		return
	}

	// Same address, better variable name.
	addrWithPrivKey := addrWithoutPrivkey

	// Try a private key lookup again.  The private key should now be available.
	key1, err := w.AddressKey(addrWithPrivKey)
	if err != nil {
		t.Errorf("Private key for original wallet was not created! %v", err)
		return
	}
	key2, err := w2.AddressKey(addrWithPrivKey)
	if err != nil {
		t.Errorf("Private key for re-read wallet was not created! %v", err)
		return
	}

	// Keys returned by both wallets must match.
	if !reflect.DeepEqual(key1, key2) {
		t.Errorf("Private keys for address originally created without one mismtach between original and re-read wallet.")
		return
	}

	// Sign some data with the private key, then verify signature with the pubkey.
	hash := []byte("hash to sign")
	r, s, err := ecdsa.Sign(rand.Reader, key1, hash)
	if err != nil {
		t.Errorf("Unable to sign hash with the created private key: %v", err)
		return
	}
	pubKeyStr, _ := hex.DecodeString(info.Pubkey)
	pubKey, err := btcec.ParsePubKey(pubKeyStr, btcec.S256())
	ok := ecdsa.Verify(pubKey, hash, r, s)
	if !ok {
		t.Errorf("ECDSA verification failed; address's pubkey mismatches the privkey.")
		return
	}

	// Test that normal keypool extension and address creation continues to
	// work.  With the wallet still unlocked, create a new address.  This
	// will cause the keypool to refill and return the first address from the
	// keypool.
	nextAddr, err := w.NextChainedAddress(&BlockStamp{}, keypoolSize)
	if err != nil {
		t.Errorf("Unable to create next address or refill keypool after finding the privkey: %v", err)
		return
	}

	nextInfo, err := w.AddressInfo(nextAddr)
	if err != nil {
		t.Errorf("Couldn't get info about the next address in the chain: %v", err)
		return
	}
	nextKey, err := w.AddressKey(nextAddr)
	if err != nil {
		t.Errorf("Couldn't get private key for the next address in the chain: %v", err)
		return
	}

	// Do an ECDSA signature check here as well, this time for the next
	// address after the one made without the private key.
	r, s, err = ecdsa.Sign(rand.Reader, nextKey, hash)
	if err != nil {
		t.Errorf("Unable to sign hash with the created private key: %v", err)
		return
	}
	pubKeyStr, _ = hex.DecodeString(nextInfo.Pubkey)
	pubKey, err = btcec.ParsePubKey(pubKeyStr, btcec.S256())
	ok = ecdsa.Verify(pubKey, hash, r, s)
	if !ok {
		t.Errorf("ECDSA verification failed; next address's keypair does not match.")
		return
	}

	// Check that the serialized wallet correctly unmarked the 'needs private
	// keys later' flag.
	buf := new(bytes.Buffer)
	w2.WriteTo(buf)
	w2.ReadFrom(buf)
	err = w2.Unlock([]byte("banana"))
	if err != nil {
		t.Errorf("Unlock after serialize/deserialize failed: %v", err)
		return
	}
}