当前位置: 首页>>代码示例>>Golang>>正文


Golang btcutil.Hash160函数代码示例

本文整理汇总了Golang中github.com/btcsuite/btcutil.Hash160函数的典型用法代码示例。如果您正苦于以下问题:Golang Hash160函数的具体用法?Golang Hash160怎么用?Golang Hash160使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了Hash160函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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


注:本文中的github.com/btcsuite/btcutil.Hash160函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。