本文整理汇总了Golang中github.com/btcsuite/btcutil.Hash160函数的典型用法代码示例。如果您正苦于以下问题:Golang Hash160函数的具体用法?Golang Hash160怎么用?Golang Hash160使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了Hash160函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Golang代码示例。
示例1: newManagedAddressWithoutPrivKey
// newManagedAddressWithoutPrivKey returns a new managed address based on the
// passed account, public key, and whether or not the public key should be
// compressed.
func newManagedAddressWithoutPrivKey(m *Manager, account uint32, pubKey *btcec.PublicKey, compressed bool) (*managedAddress, error) {
// Create a pay-to-pubkey-hash address from the public key.
var pubKeyHash []byte
if compressed {
pubKeyHash = btcutil.Hash160(pubKey.SerializeCompressed())
} else {
pubKeyHash = btcutil.Hash160(pubKey.SerializeUncompressed())
}
address, err := btcutil.NewAddressPubKeyHash(pubKeyHash, m.chainParams)
if err != nil {
return nil, err
}
return &managedAddress{
manager: m,
address: address,
account: account,
imported: false,
internal: false,
compressed: compressed,
pubKey: pubKey,
privKeyEncrypted: nil,
privKeyCT: nil,
}, nil
}
开发者ID:D-bank,项目名称:btcwallet,代码行数:28,代码来源:address.go
示例2: 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
}
开发者ID:DeniseTerry1,项目名称:lnd,代码行数:56,代码来源:conn.go
示例3: main
func main() {
name := "text/melange"
rand, _ := hex.DecodeString("e4de61166713cf9e")
hash := btcutil.Hash160(append(rand, []byte(name)...))
fmt.Println(hex.EncodeToString(hash))
}
开发者ID:airdispatch,项目名称:zooko-go,代码行数:7,代码来源:generateHash.go
示例4: TestAddrIndexKeySerialization
func TestAddrIndexKeySerialization(t *testing.T) {
var hash160Bytes [ripemd160.Size]byte
fakeHash160 := btcutil.Hash160([]byte("testing"))
copy(fakeHash160, hash160Bytes[:])
fakeIndex := txAddrIndex{
hash160: hash160Bytes,
blkHeight: 1,
txoffset: 5,
txlen: 360,
}
serializedKey := addrIndexToKey(&fakeIndex)
unpackedIndex := unpackTxIndex(serializedKey[22:])
if unpackedIndex.blkHeight != fakeIndex.blkHeight {
t.Errorf("Incorrect block height. Unpack addr index key"+
"serialization failed. Expected %d, received %d",
1, unpackedIndex.blkHeight)
}
if unpackedIndex.txoffset != fakeIndex.txoffset {
t.Errorf("Incorrect tx offset. Unpack addr index key"+
"serialization failed. Expected %d, received %d",
5, unpackedIndex.txoffset)
}
if unpackedIndex.txlen != fakeIndex.txlen {
t.Errorf("Incorrect tx len. Unpack addr index key"+
"serialization failed. Expected %d, received %d",
360, unpackedIndex.txlen)
}
}
开发者ID:jimmysong,项目名称:btcd,代码行数:34,代码来源:internal_test.go
示例5: addUsedAddr
// addUsedAddr creates a deposit script for the given seriesID/branch/index,
// ensures it is imported into the address manager and finaly adds the script
// hash to our used addresses DB. It must be called with the manager unlocked.
func (p *Pool) addUsedAddr(seriesID uint32, branch Branch, index Index) error {
script, err := p.DepositScript(seriesID, branch, index)
if err != nil {
return err
}
// First ensure the address manager has our script. That way there's no way
// to have it in the used addresses DB but not in the address manager.
// TODO: Decide how far back we want the addr manager to rescan and set the
// BlockStamp height according to that.
_, err = p.manager.ImportScript(script, &waddrmgr.BlockStamp{})
if err != nil && err.(waddrmgr.ManagerError).ErrorCode != waddrmgr.ErrDuplicateAddress {
return err
}
encryptedHash, err := p.manager.Encrypt(waddrmgr.CKTPublic, btcutil.Hash160(script))
if err != nil {
return newError(ErrCrypto, "failed to encrypt script hash", err)
}
err = p.namespace.Update(
func(tx walletdb.Tx) error {
return putUsedAddrHash(tx, p.ID, seriesID, branch, index, encryptedHash)
})
if err != nil {
return newError(ErrDatabase, "failed to store used addr script hash", err)
}
return nil
}
开发者ID:justusranvier,项目名称:btcwallet,代码行数:32,代码来源:pool.go
示例6: TestFilterInsertKey
// TestFilterInsertKey ensures inserting public keys and addresses works as
// expected.
func TestFilterInsertKey(t *testing.T) {
secret := "5Kg1gnAjaLfKiwhhPpGS3QfRg2m6awQvaj98JCZBZQ5SuS2F15C"
wif, err := btcutil.DecodeWIF(secret)
if err != nil {
t.Errorf("TestFilterInsertKey DecodeWIF failed: %v", err)
return
}
f := bloom.NewFilter(2, 0, 0.001, wire.BloomUpdateAll)
f.Add(wif.SerializePubKey())
f.Add(btcutil.Hash160(wif.SerializePubKey()))
want, err := hex.DecodeString("038fc16b080000000000000001")
if err != nil {
t.Errorf("TestFilterInsertWithTweak DecodeString failed: %v\n", err)
return
}
got := bytes.NewBuffer(nil)
err = f.MsgFilterLoad().BtcEncode(got, wire.ProtocolVersion)
if err != nil {
t.Errorf("TestFilterInsertWithTweak BtcDecode failed: %v\n", err)
return
}
if !bytes.Equal(got.Bytes(), want) {
t.Errorf("TestFilterInsertWithTweak failure: got %v want %v\n",
got.Bytes(), want)
return
}
}
开发者ID:CrowBits,项目名称:btcutil,代码行数:33,代码来源:filter_test.go
示例7: indexScriptPubKey
// indexScriptPubKey indexes all data pushes greater than 8 bytes within the
// passed SPK. Our "address" index is actually a hash160 index, where in the
// ideal case the data push is either the hash160 of a publicKey (P2PKH) or
// a Script (P2SH).
func indexScriptPubKey(addrIndex database.BlockAddrIndex, scriptPubKey []byte,
locInBlock *wire.TxLoc) error {
dataPushes, err := txscript.PushedData(scriptPubKey)
if err != nil {
adxrLog.Tracef("Couldn't get pushes: %v", err)
return err
}
for _, data := range dataPushes {
// Only index pushes greater than 8 bytes.
if len(data) < 8 {
continue
}
var indexKey [ripemd160.Size]byte
// A perfect little hash160.
if len(data) <= 20 {
copy(indexKey[:], data)
// Otherwise, could be a payToPubKey or an OP_RETURN, so we'll
// make a hash160 out of it.
} else {
copy(indexKey[:], btcutil.Hash160(data))
}
addrIndex[indexKey] = append(addrIndex[indexKey], locInBlock)
}
return nil
}
开发者ID:vineventura,项目名称:btcd,代码行数:32,代码来源:chainindexer.go
示例8: scriptHashPkScript
// scriptHashPkScript generates a pay-to-script-hash public key script paying
// to the hash160 of the passed redeem script.
func scriptHashPkScript(redeemScript []byte) ([]byte, error) {
bldr := txscript.NewScriptBuilder()
bldr.AddOp(txscript.OP_HASH160)
bldr.AddData(btcutil.Hash160(redeemScript))
bldr.AddOp(txscript.OP_EQUAL)
return bldr.Script()
}
开发者ID:PaulCapestany,项目名称:lnd,代码行数:9,代码来源:script_utils.go
示例9: 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
}
开发者ID:DeniseTerry1,项目名称:lnd,代码行数:48,代码来源:conn.go
示例10: commitScriptUnencumbered
// commitScriptUnencumbered constructs the public key script on the commitment
// transaction paying to the "other" party. This output is spendable
// immediately, requiring no contestation period.
func commitScriptUnencumbered(key *btcec.PublicKey) ([]byte, error) {
// This script goes to the "other" party, and it spendable immediately.
builder := txscript.NewScriptBuilder()
builder.AddOp(txscript.OP_DUP)
builder.AddOp(txscript.OP_HASH160)
builder.AddData(btcutil.Hash160(key.SerializeCompressed()))
builder.AddOp(txscript.OP_EQUALVERIFY)
builder.AddOp(txscript.OP_CHECKSIG)
return builder.Script()
}
开发者ID:PaulCapestany,项目名称:lnd,代码行数:14,代码来源:script_utils.go
示例11: 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
}
开发者ID:martindale,项目名称:lnd,代码行数:55,代码来源:peer.go
示例12: RevocationHash
// RevocationHash...
func (c *ChannelUpdate) RevocationHash() ([]byte, error) {
c.lnChannel.stateMtx.RLock()
defer c.lnChannel.stateMtx.RUnlock()
shachain := c.lnChannel.channelState.OurShaChain
nextPreimage, err := shachain.GetHash(c.pendingUpdateNum)
if err != nil {
return nil, err
}
return btcutil.Hash160(nextPreimage[:]), nil
}
开发者ID:conseweb,项目名称:lnd,代码行数:13,代码来源:channel.go
示例13: NewSphinxNode
// NewSphinxNode...
func NewSphinxNode(nodeKey *btcec.PrivateKey, net *chaincfg.Params) *SphinxNode {
var nodeID [securityParameter]byte
copy(nodeID[:], btcutil.Hash160(nodeKey.PubKey().SerializeCompressed()))
// Safe to ignore the error here, nodeID is 20 bytes.
nodeAddr, _ := btcutil.NewAddressPubKeyHash(nodeID[:], net)
return &SphinxNode{
nodeID: nodeID,
nodeAddr: nodeAddr,
lnKey: nodeKey,
// TODO(roasbeef): replace instead with bloom filter?
// * https://moderncrypto.org/mail-archive/messaging/2015/001911.html
seenSecrets: make(map[[sharedSecretSize]byte]struct{}),
}
}
开发者ID:DeniseTerry1,项目名称:lightning-onion,代码行数:17,代码来源:sphinx.go
示例14: generateAddr
// generateAddr computes the associated bitcon address from the provided
// public key. We compute ripemd160(sha256(b)) of the pubkey and then
// shimmy the hashed bytes into btcsuite's AddressPubKeyHash type
func generateAddr(pub *btcec.PublicKey) *btcutil.AddressPubKeyHash {
net := &chaincfg.MainNetParams
// Serialize the public key into bytes and then run ripemd160(sha256(b)) on it
b := btcutil.Hash160(pub.SerializeCompressed())
// Convert the hashed public key into the btcsuite type so that the library
// will handle the base58 encoding when we call addr.String()
addr, err := btcutil.NewAddressPubKeyHash(b, net)
if err != nil {
log.Fatal(err)
}
return addr
}
开发者ID:2014mchidamb,项目名称:ps1,代码行数:19,代码来源:keypair.go
示例15: Commit
// Commit...
func (c *ChannelUpdate) Commit(pastRevokePreimage []byte) error {
c.lnChannel.stateMtx.Lock()
defer c.lnChannel.stateMtx.Unlock()
// First, ensure that the pre-image properly links into the shachain.
theirShaChain := c.lnChannel.channelState.TheirShaChain
var preImage [32]byte
copy(preImage[:], pastRevokePreimage)
if err := theirShaChain.AddNextHash(preImage); err != nil {
return err
}
channelState := c.lnChannel.channelState
// Finally, verify that that this is indeed the pre-image to the
// revocation hash we were given earlier.
if !bytes.Equal(btcutil.Hash160(pastRevokePreimage),
channelState.TheirCurrentRevocation[:]) {
return fmt.Errorf("pre-image hash does not match revocation")
}
// Store this current revocation in the channel state so we can
// verify future channel updates.
channelState.TheirCurrentRevocation = c.pendingRevocation
// The channel update is now complete, roll over to the newest commitment
// transaction.
channelState.OurCommitTx = c.ourPendingCommitTx
channelState.TheirCommitTx = c.theirPendingCommitTx
channelState.NumUpdates = c.pendingUpdateNum
// If this channel update involved deleting an HTLC, remove it from the
// set of pending payments.
if c.deletion {
delete(c.lnChannel.pendingPayments, c.pendingDesc.RHash)
}
// TODO(roasbeef): db writes, checkpoints, and such
// Return the updateTotem, allowing another update to be created now
// that this pending update has been commited, and finalized.
c.lnChannel.updateTotem <- struct{}{}
return nil
}
开发者ID:conseweb,项目名称:lnd,代码行数:46,代码来源:channel.go
示例16: FindPre
func (e *ElkremReceiver) FindPre(
target [20]byte, timeHint uint32) (*[20]byte, error) {
maxUint32 := uint32((1 << 32) - 1)
minTime := uint32(500000000)
hintRange := uint32((1 << 29) - 1)
// a timeHint of 2^32 (4294967296) means we don't have a timeHint.
if timeHint == maxUint32 {
return nil, fmt.Errorf("no timeHint")
}
// valid timeHint range is 500M to 500M + 2^29
if timeHint < minTime || timeHint > minTime+hintRange {
return nil, fmt.Errorf("timeHint %d out of range (500M - ~1G)", timeHint)
}
indexHint := uint64(timeHint - minTime)
maxIndex := e.s[len(e.s)-1].i // highest index we have
if indexHint > maxIndex { // we can't derive needed index
return nil, fmt.Errorf("hint index %d greater than max index %d",
indexHint, maxIndex)
}
// iterate though, adding 2^29 each time.
// there is some redundancy here when you have a large number of guesses
// to go through, so this could be optimized later.
for guess := indexHint; guess < maxIndex; guess += uint64(hintRange) {
sha, err := e.AtIndex(guess) // generate preimage
if err != nil {
return nil, err
}
var truncatedSha [20]byte
copy(truncatedSha[:], sha.Bytes()) // copy into 20 byte array
checkHash := btcutil.Hash160(truncatedSha[:]) // hash and compare
if bytes.Equal(target[:], checkHash) { // matches hash, return
return &truncatedSha, nil
}
}
// got through the loop without finding anything.
return nil, fmt.Errorf("Couldn't find preimage of %x. timeHint %d bad?",
target, timeHint)
}
开发者ID:conseweb,项目名称:lnd,代码行数:43,代码来源:findpre.go
示例17: Dial
// Dial...
func (c *Conn) Dial(address string, remoteId []byte) error {
var err error
if c.conn != nil {
return fmt.Errorf("connection already established")
}
// Before dialing out to the remote host, verify that `remoteId` is either
// a pubkey or a pubkey hash.
if len(remoteId) != 33 && len(remoteId) != 20 {
return fmt.Errorf("must supply either remote pubkey or " +
"pubkey hash")
}
// First, open the TCP connection itself.
c.conn, err = net.Dial("tcp", address)
if err != nil {
return err
}
// Calc remote LNId; need this for creating pbx connections just because
// LNid is in the struct does not mean it's authed!
if len(remoteId) == 20 {
copy(c.remoteLNId[:], remoteId[:16])
} else {
theirAdr := btcutil.Hash160(remoteId)
copy(c.remoteLNId[:], theirAdr[:16])
}
// Make up an ephemeral keypair for this session.
ourEphemeralPriv, err := btcec.NewPrivateKey(btcec.S256())
if err != nil {
return err
}
ourEphemeralPub := ourEphemeralPriv.PubKey()
// Sned 1. Send my ephemeral pubkey. Can add version bits.
if _, err = writeClear(c.conn, ourEphemeralPub.SerializeCompressed()); err != nil {
return err
}
// Read, then deserialize their ephemeral public key.
theirEphPubBytes, err := readClear(c.conn)
if err != nil {
return err
}
theirEphPub, err := btcec.ParsePubKey(theirEphPubBytes, btcec.S256())
if err != nil {
return err
}
// Do non-interactive diffie with ephemeral pubkeys. Sha256 for good
// luck.
sessionKey := fastsha256.Sum256(
btcec.GenerateSharedSecret(ourEphemeralPriv, theirEphPub),
)
// Now that we've derive the session key, we can initialize the
// chacha20poly1305 AEAD instance which will be used for the remainder of
// the session.
c.chachaStream, err = chacha20poly1305.New(sessionKey[:])
if err != nil {
return err
}
// display private key for debug only
fmt.Printf("made session key %x\n", sessionKey)
c.myNonceInt = 1 << 63
c.remoteNonceInt = 0
c.remotePub = theirEphPub
c.authed = false
// Session is now open and confidential but not yet authenticated...
// So auth!
if len(remoteId) == 20 {
// Only know pubkey hash (20 bytes).
err = c.authPKH(remoteId, ourEphemeralPub.SerializeCompressed())
} else {
// Must be 33 byte pubkey.
err = c.authPubKey(remoteId, ourEphemeralPub.SerializeCompressed())
}
if err != nil {
return err
}
return nil
}
开发者ID:martindale,项目名称:lnd,代码行数:89,代码来源:conn.go
示例18: Deserialize
// Deserialize an LNId from byte slice (on disk)
// Note that this does not check any internal consistency, because on local
// storage there's no point. Check separately if needed.
// Also, old and probably needs to be changed / updated
func (l *LNAdr) Deserialize(s []byte) error {
b := bytes.NewBuffer(s)
// Fail if on-disk LNId too short
if b.Len() < 24 { // 24 is min lenght
return fmt.Errorf("can't read LNId - too short")
}
// read indicator of pubkey or pubkeyhash
x, err := b.ReadByte()
if err != nil {
return err
}
if x == 0xb0 { // for pubkey storage
// read 33 bytes of pubkey
l.PubKey, err = btcec.ParsePubKey(b.Next(33), btcec.S256())
if err != nil {
return err
}
l.Base58Adr, err = btcutil.NewAddressPubKeyHash(
btcutil.Hash160(l.PubKey.SerializeCompressed()),
globalconfig.NetParams)
if err != nil {
return err
}
} else if x == 0xa0 { // for pubkeyhash storage
l.Base58Adr, err = btcutil.NewAddressPubKeyHash(
b.Next(20), globalconfig.NetParams)
if err != nil {
return err
}
} else {
return fmt.Errorf("Unknown lnid indicator byte %x", x)
}
var nameLen, hostLen, endorseLen uint8
// read name length
err = binary.Read(b, binary.BigEndian, &nameLen)
if err != nil {
return err
}
// if name non-zero, read name
if nameLen > 0 {
l.name = string(b.Next(int(nameLen)))
}
// read host length
err = binary.Read(b, binary.BigEndian, &hostLen)
if err != nil {
return err
}
// if host non-zero, read host
if hostLen > 0 {
l.host = string(b.Next(int(hostLen)))
}
// read endorsement length
err = binary.Read(b, binary.BigEndian, &endorseLen)
if err != nil {
return err
}
// if endorsement non-zero, read endorsement
if endorseLen > 0 {
l.endorsement = b.Next(int(endorseLen))
}
return nil
}
开发者ID:mkl-,项目名称:lnd,代码行数:73,代码来源:lnadr.go
示例19: Address
// Address converts the extended key to a standard bitcoin pay-to-pubkey-hash
// address for the passed network.
func (k *ExtendedKey) Address(net *chaincfg.Params) (*btcutil.AddressPubKeyHash, error) {
pkHash := btcutil.Hash160(k.pubKeyBytes())
return btcutil.NewAddressPubKeyHash(pkHash, net)
}
开发者ID:skycoin,项目名称:skycoin-exchange,代码行数:6,代码来源:extendedkey.go
示例20: Child
//.........这里部分代码省略.........
//
// 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
}
开发者ID:skycoin,项目名称:skycoin-exchange,代码行数:101,代码来源:extendedkey.go
注:本文中的github.com/btcsuite/btcutil.Hash160函数示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论