本文整理汇总了Golang中github.com/btcsuite/btcd/btcec.ParsePubKey函数的典型用法代码示例。如果您正苦于以下问题:Golang ParsePubKey函数的具体用法?Golang ParsePubKey怎么用?Golang ParsePubKey使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了ParsePubKey函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: isPubKey
// isPubKey returns whether or not the passed public key script is a standard
// pay-to-pubkey script that pays to a valid compressed or uncompressed public
// key along with the serialized pubkey it is paying to if it is.
//
// NOTE: This function ensures the public key is actually valid since the
// compression algorithm requires valid pubkeys. It does not support hybrid
// pubkeys. This means that even if the script has the correct form for a
// pay-to-pubkey script, this function will only return true when it is paying
// to a valid compressed or uncompressed pubkey.
func isPubKey(script []byte) (bool, []byte) {
// Pay-to-compressed-pubkey script.
if len(script) == 35 && script[0] == txscript.OP_DATA_33 &&
script[34] == txscript.OP_CHECKSIG && (script[1] == 0x02 ||
script[1] == 0x03) {
// Ensure the public key is valid.
serializedPubKey := script[1:34]
_, err := btcec.ParsePubKey(serializedPubKey, btcec.S256())
if err == nil {
return true, serializedPubKey
}
}
// Pay-to-uncompressed-pubkey script.
if len(script) == 67 && script[0] == txscript.OP_DATA_65 &&
script[66] == txscript.OP_CHECKSIG && script[1] == 0x04 {
// Ensure the public key is valid.
serializedPubKey := script[1:66]
_, err := btcec.ParsePubKey(serializedPubKey, btcec.S256())
if err == nil {
return true, serializedPubKey
}
}
return false, nil
}
示例2: GetIdentity
// GetIdentity returns the public identity corresponding to the given address
// if it exists.
func (c *Client) GetIdentity(address string) (*identity.Public, error) {
addr, err := bmutil.DecodeAddress(address)
if err != nil {
return nil, fmt.Errorf("Address decode failed: %v", addr)
}
res, err := c.bmd.GetIdentity(context.Background(), &pb.GetIdentityRequest{
Address: address,
})
if grpc.Code(err) == codes.NotFound {
return nil, ErrIdentityNotFound
} else if err != nil {
return nil, err
}
signKey, err := btcec.ParsePubKey(res.SigningKey, btcec.S256())
if err != nil {
return nil, err
}
encKey, err := btcec.ParsePubKey(res.EncryptionKey, btcec.S256())
if err != nil {
return nil, err
}
return identity.NewPublic(signKey, encKey,
&pow.Data{
res.NonceTrials,
res.ExtraBytes,
}, addr.Version, addr.Stream), nil
}
示例3: TestPublicKeyIsEqual
func TestPublicKeyIsEqual(t *testing.T) {
pubKey1, err := btcec.ParsePubKey(
[]byte{0x03, 0x26, 0x89, 0xc7, 0xc2, 0xda, 0xb1, 0x33,
0x09, 0xfb, 0x14, 0x3e, 0x0e, 0x8f, 0xe3, 0x96, 0x34,
0x25, 0x21, 0x88, 0x7e, 0x97, 0x66, 0x90, 0xb6, 0xb4,
0x7f, 0x5b, 0x2a, 0x4b, 0x7d, 0x44, 0x8e,
},
btcec.S256(),
)
if err != nil {
t.Fatalf("failed to parse raw bytes for pubKey1: %v", err)
}
pubKey2, err := btcec.ParsePubKey(
[]byte{0x02, 0xce, 0x0b, 0x14, 0xfb, 0x84, 0x2b, 0x1b,
0xa5, 0x49, 0xfd, 0xd6, 0x75, 0xc9, 0x80, 0x75, 0xf1,
0x2e, 0x9c, 0x51, 0x0f, 0x8e, 0xf5, 0x2b, 0xd0, 0x21,
0xa9, 0xa1, 0xf4, 0x80, 0x9d, 0x3b, 0x4d,
},
btcec.S256(),
)
if err != nil {
t.Fatalf("failed to parse raw bytes for pubKey2: %v", err)
}
if !pubKey1.IsEqual(pubKey1) {
t.Fatalf("value of IsEqual is incorrect, %v is "+
"equal to %v", pubKey1, pubKey1)
}
if pubKey1.IsEqual(pubKey2) {
t.Fatalf("value of IsEqual is incorrect, %v is not "+
"equal to %v", pubKey1, pubKey2)
}
}
示例4: TestSigCacheAddEvictEntry
// 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
// previously 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")
}
}
示例5: TestPubKeys
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)
}
}
}
示例6: TestSigCacheAddMaxEntriesZeroOrNegative
// 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))
}
}
示例7: Uncompress
// Uncompress computes the public key for a given compressed public key.
func (cpk *CompressedPublicKey) Uncompress() (*PublicKey, error) {
// Should only execute the decompression branch of ParsePublicKey
pk_s, err := btcec.ParsePubKey(cpk[:], S256)
if err != nil {
return nil, err
}
return newPublicKeyCoords(pk_s.X, pk_s.Y), nil
}
示例8: TstAddressPubKey
// 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,
}
}
示例9: authPKH
// authPKH...
func (c *LNDConn) authPKH(
myId *btcec.PrivateKey, theirPKH, localEphPubBytes []byte) error {
if c.Authed {
return fmt.Errorf("%s already authed", c.RemotePub)
}
if len(theirPKH) != 20 {
return fmt.Errorf("remote PKH must be 20 bytes, got %d",
len(theirPKH))
}
// Send 53 bytes: our pubkey, and the remote's pubkey hash.
var greetingMsg [53]byte
copy(greetingMsg[:33], myId.PubKey().SerializeCompressed())
copy(greetingMsg[:33], theirPKH)
if _, err := c.Conn.Write(greetingMsg[:]); err != nil {
return err
}
// Wait for their response.
// TODO(tadge): add timeout here
// * NOTE(roasbeef): read timeout should be set on the underlying
// net.Conn.
resp := make([]byte, 53)
if _, err := c.Conn.Read(resp); err != nil {
return err
}
// Parse their long-term public key, and generate the DH proof.
theirPub, err := btcec.ParsePubKey(resp[:33], btcec.S256())
if err != nil {
return err
}
idDH := fastsha256.Sum256(btcec.GenerateSharedSecret(myId, theirPub))
fmt.Printf("made idDH %x\n", idDH)
theirDHproof := btcutil.Hash160(append(localEphPubBytes, idDH[:]...))
// Verify that their DH proof matches the one we just generated.
if bytes.Equal(resp[33:], theirDHproof) == false {
return fmt.Errorf("Invalid DH proof %x", theirDHproof)
}
// If their DH proof checks out, then send our own.
myDHproof := btcutil.Hash160(append(c.RemotePub.SerializeCompressed(), idDH[:]...))
if _, err = c.Conn.Write(myDHproof); err != nil {
return err
}
// Proof sent, auth complete.
c.RemotePub = theirPub
theirAdr := btcutil.Hash160(theirPub.SerializeCompressed())
copy(c.RemoteLNId[:], theirAdr[:16])
c.Authed = true
return nil
}
示例10: newLnAddr
// newLnAddr...
func newLnAddr(encodedAddr string) (*lnAddr, error) {
// The format of an lnaddr is "<pubkey or pkh>@host"
idHost := strings.Split(encodedAddr, "@")
if len(idHost) != 2 {
return nil, fmt.Errorf("invalid format for lnaddr string: %v", encodedAddr)
}
// Attempt to resolve the IP address, this handles parsing IPv6 zones,
// and such.
fmt.Println("host: ", idHost[1])
ipAddr, err := net.ResolveTCPAddr("tcp", idHost[1])
if err != nil {
return nil, err
}
addr := &lnAddr{netAddr: ipAddr}
idLen := len(idHost[0])
switch {
// Is the ID a hex-encoded compressed public key?
case idLen > 65 && idLen < 69:
pubkeyBytes, err := hex.DecodeString(idHost[0])
if err != nil {
return nil, err
}
addr.pubKey, err = btcec.ParsePubKey(pubkeyBytes, btcec.S256())
if err != nil {
return nil, err
}
// got pubey, populate address from pubkey
pkh := btcutil.Hash160(addr.pubKey.SerializeCompressed())
addr.bitcoinAddr, err = btcutil.NewAddressPubKeyHash(pkh,
&chaincfg.TestNet3Params)
if err != nil {
return nil, err
}
// Is the ID a string encoded bitcoin address?
case idLen > 33 && idLen < 37:
addr.bitcoinAddr, err = btcutil.DecodeAddress(idHost[0],
&chaincfg.TestNet3Params)
if err != nil {
return nil, err
}
default:
return nil, fmt.Errorf("invalid address %s", idHost[0])
}
// Finally, populate the lnid from the address.
copy(addr.lnId[:], addr.bitcoinAddr.ScriptAddress())
return addr, nil
}
示例11: verifyECDSA
// Verifies a hash using DER encoded signature
func verifyECDSA(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
}
示例12: NewKeyFromString
// 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 := chainhash.DoubleHashB(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
}
示例13: VerifyBytes
func (pubKey PubKeySecp256k1) VerifyBytes(msg []byte, sig_ Signature) bool {
pub__, err := secp256k1.ParsePubKey(append([]byte{0x04}, pubKey[:]...), secp256k1.S256())
if err != nil {
return false
}
sig, ok := sig_.(SignatureSecp256k1)
if !ok {
return false
}
sig__, err := secp256k1.ParseDERSignature(sig[:], secp256k1.S256())
if err != nil {
return false
}
return sig__.Verify(Sha256(msg), pub__)
}
示例14: createCipherConn
// createCipherConn....
func (l *Listener) createCipherConn(lnConn *LNDConn) (*btcec.PrivateKey, error) {
var err error
var theirEphPubBytes []byte
// First, read and deserialize their ephemeral public key.
theirEphPubBytes, err = readClear(lnConn.Conn)
if err != nil {
return nil, err
}
if len(theirEphPubBytes) != 33 {
return nil, fmt.Errorf("Got invalid %d byte eph pubkey %x\n",
len(theirEphPubBytes), theirEphPubBytes)
}
theirEphPub, err := btcec.ParsePubKey(theirEphPubBytes, btcec.S256())
if err != nil {
return nil, err
}
// Once we've parsed and verified their key, generate, and send own
// ephemeral key pair for use within this session.
myEph, err := btcec.NewPrivateKey(btcec.S256())
if err != nil {
return nil, err
}
if _, err := writeClear(lnConn.Conn, myEph.PubKey().SerializeCompressed()); err != nil {
return nil, err
}
// Now that we have both keys, do non-interactive diffie with ephemeral
// pubkeys, sha256 for good luck.
sessionKey := fastsha256.Sum256(
btcec.GenerateSharedSecret(myEph, theirEphPub),
)
lnConn.chachaStream, err = chacha20poly1305.New(sessionKey[:])
// display private key for debug only
fmt.Printf("made session key %x\n", sessionKey)
lnConn.remoteNonceInt = 1 << 63
lnConn.myNonceInt = 0
lnConn.RemotePub = theirEphPub
lnConn.Authed = false
return myEph, nil
}
示例15: authPubKey
// authPubKey...
func (c *LNDConn) authPubKey(
myId *btcec.PrivateKey, remotePubBytes, localEphPubBytes []byte) error {
if c.Authed {
return fmt.Errorf("%s already authed", c.RemotePub)
}
// Since we already know their public key, we can immediately generate
// the DH proof without an additional round-trip.
theirPub, err := btcec.ParsePubKey(remotePubBytes, btcec.S256())
if err != nil {
return err
}
theirPKH := btcutil.Hash160(remotePubBytes)
idDH := fastsha256.Sum256(btcec.GenerateSharedSecret(myId, theirPub))
myDHproof := btcutil.Hash160(append(c.RemotePub.SerializeCompressed(), idDH[:]...))
// Send over the 73 byte authentication message: my pubkey, their
// pubkey hash, DH proof.
var authMsg [73]byte
copy(authMsg[:33], myId.PubKey().SerializeCompressed())
copy(authMsg[33:], theirPKH)
copy(authMsg[53:], myDHproof)
if _, err = c.Conn.Write(authMsg[:]); err != nil {
return nil
}
// Await, their response. They should send only the 20-byte DH proof.
resp := make([]byte, 20)
_, err = c.Conn.Read(resp)
if err != nil {
return err
}
// Verify that their proof matches our locally computed version.
theirDHproof := btcutil.Hash160(append(localEphPubBytes, idDH[:]...))
if bytes.Equal(resp, theirDHproof) == false {
return fmt.Errorf("invalid DH proof %x", theirDHproof)
}
// Proof checks out, auth complete.
c.RemotePub = theirPub
theirAdr := btcutil.Hash160(theirPub.SerializeCompressed())
copy(c.RemoteLNId[:], theirAdr[:16])
c.Authed = true
return nil
}