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


Golang chainhash.HashFuncB函数代码示例

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


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

示例1: String

// String returns the extended key as a human-readable base58-encoded string.
func (k *ExtendedKey) String() (string, error) {
	if len(k.key) == 0 {
		return "", fmt.Errorf("zeroed extended key")
	}

	var childNumBytes [4]byte
	depthByte := byte(k.depth % 256)
	binary.BigEndian.PutUint32(childNumBytes[:], k.childNum)

	// The serialized format is:
	//   version (4) || depth (1) || parent fingerprint (4)) ||
	//   child num (4) || chain code (32) || key data (33) || checksum (4)
	serializedBytes := make([]byte, 0, serializedKeyLen+4)
	serializedBytes = append(serializedBytes, k.version...)
	serializedBytes = append(serializedBytes, depthByte)
	serializedBytes = append(serializedBytes, k.parentFP...)
	serializedBytes = append(serializedBytes, childNumBytes[:]...)
	serializedBytes = append(serializedBytes, k.chainCode...)
	if k.isPrivate {
		serializedBytes = append(serializedBytes, 0x00)
		serializedBytes = paddedAppend(32, serializedBytes, k.key)
	} else {
		serializedBytes = append(serializedBytes, k.pubKeyBytes()...)
	}

	checkSum := chainhash.HashFuncB(chainhash.HashFuncB(serializedBytes))[:4]
	serializedBytes = append(serializedBytes, checkSum...)
	return base58.Encode(serializedBytes), nil
}
开发者ID:IcantBelieveItsNotMoney,项目名称:dcrutil,代码行数:30,代码来源:extendedkey.go

示例2: 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.HashFuncB(chainhash.HashFuncB(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(chainec.Secp256k1.GetN()) >= 0 || keyNum.Sign() == 0 {
			return nil, ErrUnusableSeed
		}
	} else {
		// Ensure the public key parses correctly and is actually on the
		// secp256k1 curve.
		_, err := chainec.Secp256k1.ParsePubKey(keyData)
		if err != nil {
			return nil, err
		}
	}

	return newExtendedKey(version, keyData, chainCode, parentFP, depth,
		childNum, isPrivate), nil
}
开发者ID:IcantBelieveItsNotMoney,项目名称:dcrutil,代码行数:53,代码来源:extendedkey.go

示例3: Example_signMessage

// This example demonstrates signing a message with a secp256k1 private key that
// is first parsed form raw bytes and serializing the generated signature.
func Example_signMessage() {
	// Decode a hex-encoded private key.
	pkBytes, err := hex.DecodeString("22a47fa09a223f2aa079edf85a7c2d4f87" +
		"20ee63e502ee2869afab7de234b80c")
	if err != nil {
		fmt.Println(err)
		return
	}
	privKey, pubKey := secp256k1.PrivKeyFromBytes(secp256k1.S256(), pkBytes)

	// Sign a message using the private key.
	message := "test message"
	messageHash := chainhash.HashFuncB([]byte(message))
	signature, err := privKey.Sign(messageHash)
	if err != nil {
		fmt.Println(err)
		return
	}

	// Serialize and display the signature.
	fmt.Printf("Serialized Signature: %x\n", signature.Serialize())

	// Verify the signature for the message using the public key.
	verified := signature.Verify(messageHash, pubKey)
	fmt.Printf("Signature Verified? %v\n", verified)

	// Output:
	// Serialized Signature: 3045022100fcc0a8768cfbcefcf2cadd7cfb0fb18ed08dd2e2ae84bef1a474a3d351b26f0302200fc1a350b45f46fa00101391302818d748c2b22615511a3ffd5bb638bd777207
	// Signature Verified? true
}
开发者ID:decred,项目名称:dcrd,代码行数:32,代码来源:example_test.go

示例4: BenchmarkHashPRNG

func BenchmarkHashPRNG(b *testing.B) {
	seed := chainhash.HashFuncB([]byte{0x01})
	prng := stake.NewHash256PRNG(seed)

	for n := 0; n < b.N; n++ {
		prng.Hash256Rand()
	}
}
开发者ID:ironbits,项目名称:dcrd,代码行数:8,代码来源:lottery_test.go

示例5: TestLotteryNumErrors

func TestLotteryNumErrors(t *testing.T) {
	seed := chainhash.HashFuncB([]byte{0x01})
	prng := NewHash256PRNG(seed)

	// Too big pool.
	_, err := FindTicketIdxs(1000000000000, 5, prng)
	if err == nil {
		t.Errorf("Expected pool size too big error")
	}
}
开发者ID:decred,项目名称:dcrd,代码行数:10,代码来源:lottery_test.go

示例6: getTriedBucket

func (a *AddrManager) getTriedBucket(netAddr *wire.NetAddress) int {
	// bitcoind hashes this as:
	// doublesha256(key + group + truncate_to_64bits(doublesha256(key))
	// % buckets_per_group) % num_buckets
	data1 := []byte{}
	data1 = append(data1, a.key[:]...)
	data1 = append(data1, []byte(NetAddressKey(netAddr))...)
	hash1 := chainhash.HashFuncB(data1)
	hash64 := binary.LittleEndian.Uint64(hash1)
	hash64 %= triedBucketsPerGroup
	var hashbuf [8]byte
	binary.LittleEndian.PutUint64(hashbuf[:], hash64)
	data2 := []byte{}
	data2 = append(data2, a.key[:]...)
	data2 = append(data2, GroupKey(netAddr)...)
	data2 = append(data2, hashbuf[:]...)

	hash2 := chainhash.HashFuncB(data2)
	return int(binary.LittleEndian.Uint64(hash2) % triedBucketCount)
}
开发者ID:ironbits,项目名称:dcrd,代码行数:20,代码来源:addrmanager.go

示例7: getNewBucket

func (a *AddrManager) getNewBucket(netAddr, srcAddr *wire.NetAddress) int {
	// bitcoind:
	// doublesha256(key + sourcegroup + int64(doublesha256(key + group
	// + sourcegroup))%bucket_per_source_group) % num_new_buckets

	data1 := []byte{}
	data1 = append(data1, a.key[:]...)
	data1 = append(data1, []byte(GroupKey(netAddr))...)
	data1 = append(data1, []byte(GroupKey(srcAddr))...)
	hash1 := chainhash.HashFuncB(data1)
	hash64 := binary.LittleEndian.Uint64(hash1)
	hash64 %= newBucketsPerGroup
	var hashbuf [8]byte
	binary.LittleEndian.PutUint64(hashbuf[:], hash64)
	data2 := []byte{}
	data2 = append(data2, a.key[:]...)
	data2 = append(data2, GroupKey(srcAddr)...)
	data2 = append(data2, hashbuf[:]...)

	hash2 := chainhash.HashFuncB(data2)
	return int(binary.LittleEndian.Uint64(hash2) % newBucketCount)
}
开发者ID:ironbits,项目名称:dcrd,代码行数:22,代码来源:addrmanager.go

示例8: BenchmarkHashFuncB

// BenchmarkHashFuncB performs a benchmark on how long it takes to perform a
// hash returning a byte slice.
func BenchmarkHashFuncB(b *testing.B) {
	var buf bytes.Buffer
	if err := genesisCoinbaseTx.Serialize(&buf); err != nil {
		b.Errorf("Serialize: unexpected error: %v", err)
		return
	}
	txBytes := buf.Bytes()

	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		_ = chainhash.HashFuncB(txBytes)
	}
}
开发者ID:decred,项目名称:dcrd,代码行数:15,代码来源:bench_test.go

示例9: TestBasicPRNG

func TestBasicPRNG(t *testing.T) {
	seed := chainhash.HashFuncB([]byte{0x01})
	prng := stake.NewHash256PRNG(seed)
	for i := 0; i < 100000; i++ {
		prng.Hash256Rand()
	}

	lastHashExp, _ := chainhash.NewHashFromStr("24f1cd72aefbfc85a9d3e21e2eb" +
		"732615688d3634bf94499af5a81e0eb45c4e4")
	lastHash := prng.StateHash()
	if *lastHashExp != lastHash {
		t.Errorf("expected final state of %v, got %v", lastHashExp, lastHash)
	}
}
开发者ID:ironbits,项目名称:dcrd,代码行数:14,代码来源:lottery_test.go

示例10: String

// String creates the Wallet Import Format string encoding of a WIF structure.
// See DecodeWIF for a detailed breakdown of the format and requirements of
// a valid WIF string.
func (w *WIF) String() string {
	// Precalculate size.  Maximum number of bytes before base58 encoding
	// is two bytes for the network, one byte for the ECDSA type, 32 bytes
	// of private key and finally four bytes of checksum.
	encodeLen := 2 + 1 + 32 + 4

	a := make([]byte, 0, encodeLen)
	a = append(a, w.netID[:]...)
	a = append(a, byte(w.ecType))
	a = append(a, w.PrivKey.Serialize()...)

	cksum := chainhash.HashFuncB(a)
	a = append(a, cksum[:4]...)
	return base58.Encode(a)
}
开发者ID:alexlyp,项目名称:dcrutil,代码行数:18,代码来源:wif.go

示例11: TestLotteryNumSelection

func TestLotteryNumSelection(t *testing.T) {
	// Test finding ticket indexes.
	seed := chainhash.HashFuncB([]byte{0x01})
	prng := stake.NewHash256PRNG(seed)
	ticketsInPool := int64(56789)
	tooFewTickets := int64(4)
	justEnoughTickets := int64(5)
	ticketsPerBlock := 5

	_, err := stake.FindTicketIdxs(tooFewTickets, ticketsPerBlock, prng)
	if err == nil {
		t.Errorf("got unexpected no error for FindTicketIdxs too few tickets " +
			"test")
	}

	tickets, err := stake.FindTicketIdxs(ticketsInPool, ticketsPerBlock, prng)
	if err != nil {
		t.Errorf("got unexpected error for FindTicketIdxs 1 test")
	}
	ticketsExp := []int{34850, 8346, 27636, 54482, 25482}
	if !reflect.DeepEqual(ticketsExp, tickets) {
		t.Errorf("Unexpected tickets selected; got %v, want %v", tickets,
			ticketsExp)
	}

	// Ensure that it can find all suitable ticket numbers in a small
	// bucket of tickets.
	tickets, err = stake.FindTicketIdxs(justEnoughTickets, ticketsPerBlock, prng)
	if err != nil {
		t.Errorf("got unexpected error for FindTicketIdxs 2 test")
	}
	ticketsExp = []int{3, 0, 4, 2, 1}
	if !reflect.DeepEqual(ticketsExp, tickets) {
		t.Errorf("Unexpected tickets selected; got %v, want %v", tickets,
			ticketsExp)
	}

	lastHashExp, _ := chainhash.NewHashFromStr("e97ce54aea63a883a82871e752c" +
		"6ec3c5731fffc63dafc3767c06861b0b2fa65")
	lastHash := prng.StateHash()
	if *lastHashExp != lastHash {
		t.Errorf("expected final state of %v, got %v", lastHashExp, lastHash)
	}
}
开发者ID:ironbits,项目名称:dcrd,代码行数:44,代码来源:lottery_test.go

示例12: NewHash256PRNG

// NewHash256PRNG creates a pointer to a newly created hash256PRNG.
func NewHash256PRNG(seed []byte) *Hash256PRNG {
	// idx and lastHash are automatically initialized
	// as 0. We initialize the seed by appending a constant
	// to it and hashing to give 32 bytes. This ensures
	// that regardless of the input, the PRNG is always
	// doing a short number of rounds because it only
	// has to hash < 64 byte messages. The constant is
	// derived from the hexadecimal representation of
	// pi.
	cst := []byte{0x24, 0x3F, 0x6A, 0x88,
		0x85, 0xA3, 0x08, 0xD3}
	hp := new(Hash256PRNG)
	hp.seed = chainhash.HashFuncB(append(seed, cst...))
	initLH, err := chainhash.NewHash(hp.seed)
	if err != nil {
		return nil
	}
	hp.seedState = *initLH
	hp.lastHash = *initLH
	hp.idx = 0
	return hp
}
开发者ID:ironbits,项目名称:dcrd,代码行数:23,代码来源:lottery.go

示例13: Example_verifySignature

// 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 := secp256k1.ParsePubKey(pubKeyBytes, secp256k1.S256())
	if err != nil {
		fmt.Println(err)
		return
	}

	// Decode hex-encoded serialized signature.
	sigBytes, err := hex.DecodeString("3045022100fcc0a8768cfbcefcf2cadd7cfb0" +
		"fb18ed08dd2e2ae84bef1a474a3d351b26f0302200fc1a350b45f46fa0010139130" +
		"2818d748c2b22615511a3ffd5bb638bd777207")

	if err != nil {
		fmt.Println(err)
		return
	}
	signature, err := secp256k1.ParseSignature(sigBytes, secp256k1.S256())
	if err != nil {
		fmt.Println(err)
		return
	}

	// Verify the signature for the message using the public key.
	message := "test message"
	messageHash := chainhash.HashFuncB([]byte(message))
	verified := signature.Verify(messageHash, pubKey)
	fmt.Println("Signature Verified?", verified)

	// Output:
	// Signature Verified? true
}
开发者ID:decred,项目名称:dcrd,代码行数:41,代码来源:example_test.go

示例14: DecodeWIF

// DecodeWIF creates a new WIF structure by decoding the string encoding of
// the import format.
//
// The WIF string must be a base58-encoded string of the following byte
// sequence:
//
//  * 2 bytes to identify the network, must be 0x80 for mainnet or 0xef for testnet
//  * 1 byte for ECDSA type
//  * 32 bytes of a binary-encoded, big-endian, zero-padded private key
//  * 4 bytes of checksum, must equal the first four bytes of the double SHA256
//    of every byte before the checksum in this sequence
//
// If the base58-decoded byte sequence does not match this, DecodeWIF will
// return a non-nil error.  ErrMalformedPrivateKey is returned when the WIF
// is of an impossible length.  ErrChecksumMismatch is returned if the
// expected WIF checksum does not match the calculated checksum.
func DecodeWIF(wif string) (*WIF, error) {
	decoded := base58.Decode(wif)
	decodedLen := len(decoded)

	if decodedLen != 39 {
		return nil, ErrMalformedPrivateKey
	}

	// Checksum is first four bytes of hash of the identifier byte
	// and privKey.  Verify this matches the final 4 bytes of the decoded
	// private key.
	cksum := chainhash.HashFuncB(decoded[:decodedLen-4])
	if !bytes.Equal(cksum[:4], decoded[decodedLen-4:]) {
		return nil, ErrChecksumMismatch
	}

	netID := [2]byte{decoded[0], decoded[1]}
	var privKey chainec.PrivateKey

	ecType := 0
	switch int(decoded[2]) {
	case chainec.ECTypeSecp256k1:
		privKeyBytes := decoded[3 : 3+chainec.Secp256k1.PrivKeyBytesLen()]
		privKey, _ = chainec.Secp256k1.PrivKeyFromScalar(privKeyBytes)
		ecType = chainec.ECTypeSecp256k1
	case chainec.ECTypeEdwards:
		privKeyBytes := decoded[3 : 3+32]
		privKey, _ = chainec.Edwards.PrivKeyFromScalar(privKeyBytes)
		ecType = chainec.ECTypeEdwards
	case chainec.ECTypeSecSchnorr:
		privKeyBytes := decoded[3 : 3+chainec.SecSchnorr.PrivKeyBytesLen()]
		privKey, _ = chainec.SecSchnorr.PrivKeyFromScalar(privKeyBytes)
		ecType = chainec.ECTypeSecSchnorr
	}

	return &WIF{ecType, privKey, netID}, nil
}
开发者ID:alexlyp,项目名称:dcrutil,代码行数:53,代码来源:wif.go

示例15: calcSignatureHash


//.........这里部分代码省略.........
	// Decred mitigates this by actually returning an error instead.
	if hashType&sigHashMask == SigHashSingle && idx >= len(tx.TxOut) {
		return nil, ErrSighashSingleIdx
	}

	// Remove all instances of OP_CODESEPARATOR from the script.
	script = removeOpcode(script, OP_CODESEPARATOR)

	// Make a deep copy of the transaction, zeroing out the script for all
	// inputs that are not currently being processed.
	txCopy := tx.Copy()
	for i := range txCopy.TxIn {
		if i == idx {
			// UnparseScript cannot fail here because removeOpcode
			// above only returns a valid script.
			sigScript, _ := unparseScript(script)
			txCopy.TxIn[idx].SignatureScript = sigScript
		} else {
			txCopy.TxIn[i].SignatureScript = nil
		}
	}

	switch hashType & sigHashMask {
	case SigHashNone:
		txCopy.TxOut = txCopy.TxOut[0:0] // Empty slice.
		for i := range txCopy.TxIn {
			if i != idx {
				txCopy.TxIn[i].Sequence = 0
			}
		}

	case SigHashSingle:
		// Resize output array to up to and including requested index.
		txCopy.TxOut = txCopy.TxOut[:idx+1]

		// All but current output get zeroed out.
		for i := 0; i < idx; i++ {
			txCopy.TxOut[i].Value = -1
			txCopy.TxOut[i].PkScript = nil
		}

		// Sequence on all other inputs is 0, too.
		for i := range txCopy.TxIn {
			if i != idx {
				txCopy.TxIn[i].Sequence = 0
			}
		}

	default:
		// Consensus treats undefined hashtypes like normal SigHashAll
		// for purposes of hash generation.
		fallthrough
	case SigHashOld:
		fallthrough
	case SigHashAllValue:
		fallthrough
	case SigHashAll:
		// Nothing special here.
	}
	if hashType&SigHashAnyOneCanPay != 0 {
		txCopy.TxIn = txCopy.TxIn[idx : idx+1]
		idx = 0
	}

	// The final hash (message to sign) is the hash of:
	// 1) hash of the prefix ||
	// 2) hash of the witness for signing ||
	// 3) the hash type (encoded as a 4-byte little-endian value)
	var wbuf bytes.Buffer
	binary.Write(&wbuf, binary.LittleEndian, uint32(hashType))

	// Optimization for SIGHASH_ALL. In this case, the prefix hash is
	// the same as the transaction hash because only the inputs have
	// been modified, so don't bother to do the wasteful O(N^2) extra
	// hash here.
	// The caching only works if the "anyone can pay flag" is also
	// disabled.
	var prefixHash chainhash.Hash
	if cachedPrefix != nil &&
		(hashType&sigHashMask == SigHashAll) &&
		(hashType&SigHashAnyOneCanPay == 0) &&
		chaincfg.SigHashOptimization {
		prefixHash = *cachedPrefix
	} else {
		prefixHash = txCopy.TxSha()
	}

	// If the ValueIn is to be included in what we're signing, sign
	// the witness hash that includes it. Otherwise, just sign the
	// prefix and signature scripts.
	var witnessHash chainhash.Hash
	if hashType&sigHashMask != SigHashAllValue {
		witnessHash = txCopy.TxShaWitnessSigning()
	} else {
		witnessHash = txCopy.TxShaWitnessValueSigning()
	}
	wbuf.Write(prefixHash.Bytes())
	wbuf.Write(witnessHash.Bytes())
	return chainhash.HashFuncB(wbuf.Bytes()), nil
}
开发者ID:decred,项目名称:dcrd,代码行数:101,代码来源:script.go


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