• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Golang chainhash.HashFuncH函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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

示例1: TestBlockUndoDataSerializing

// TestBlockUndoDataSerializing ensures serializing and deserializing the
// block undo data works as expected.
func TestBlockUndoDataSerializing(t *testing.T) {
	t.Parallel()

	tests := []struct {
		name       string
		utds       []UndoTicketData
		serialized []byte
	}{
		{
			name: "two ticket datas",
			utds: []UndoTicketData{
				UndoTicketData{
					TicketHash:   chainhash.HashFuncH([]byte{0x00}),
					TicketHeight: 123456,
					Missed:       true,
					Revoked:      false,
					Spent:        false,
					Expired:      true,
				},
				UndoTicketData{
					TicketHash:   chainhash.HashFuncH([]byte{0x01}),
					TicketHeight: 122222,
					Missed:       false,
					Revoked:      true,
					Spent:        true,
					Expired:      false,
				},
			},
			serialized: hexToBytes("0ce8d4ef4dd7cd8d62dfded9d4edb0a774ae6a41929a74da23109e8f11139c8740e20100094a6c419a1e25c85327115c4ace586decddfe2990ed8f3d4d801871158338501d6edd010006"),
		},
	}

	for i, test := range tests {
		// Ensure the state serializes to the expected value.
		gotBytes := serializeBlockUndoData(test.utds)
		if !bytes.Equal(gotBytes, test.serialized) {
			t.Errorf("serializeBlockUndoData #%d (%s): mismatched "+
				"bytes - got %x, want %x", i, test.name,
				gotBytes, test.serialized)
			continue
		}

		// Ensure the serialized bytes are decoded back to the expected
		// state.
		utds, err := deserializeBlockUndoData(test.serialized)
		if err != nil {
			t.Errorf("deserializeBlockUndoData #%d (%s) "+
				"unexpected error: %v", i, test.name, err)
			continue
		}
		if !reflect.DeepEqual(utds, test.utds) {
			t.Errorf("deserializeBlockUndoData #%d (%s) "+
				"mismatched state - got %v, want %v", i,
				test.name, utds, test.utds)
			continue

		}
	}
}
开发者ID:decred,项目名称:dcrd,代码行数:61,代码来源:chainio_test.go


示例2: TestBestChainStateSerialization

// TestBestChainStateSerialization ensures serializing and deserializing the
// best chain state works as expected.
func TestBestChainStateSerialization(t *testing.T) {
	t.Parallel()

	hash1 := chainhash.HashFuncH([]byte{0x00})
	hash2 := chainhash.HashFuncH([]byte{0x01})
	hash3 := chainhash.HashFuncH([]byte{0x02})
	hash4 := chainhash.HashFuncH([]byte{0x03})
	hash5 := chainhash.HashFuncH([]byte{0x04})

	tests := []struct {
		name       string
		state      BestChainState
		serialized []byte
	}{
		{
			name: "generic block",
			state: BestChainState{
				Hash:        *newShaHashFromStr("000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f"),
				Height:      12323,
				Live:        29399,
				Missed:      293929392,
				Revoked:     349839493,
				PerBlock:    5,
				NextWinners: []chainhash.Hash{hash1, hash2, hash3, hash4, hash5},
			},
			serialized: hexToBytes("6fe28c0ab6f1b372c1a6a246ae63f74f931e8365e15a089c68d619000000000023300000d7720000b0018511000000008520da140000000005000ce8d4ef4dd7cd8d62dfded9d4edb0a774ae6a41929a74da23109e8f11139c874a6c419a1e25c85327115c4ace586decddfe2990ed8f3d4d801871158338501d49af37ab5270015fe25276ea5a3bb159d852943df23919522a202205fb7d175cb706d561742ad3671703c247eb927ee8a386369c79644131cdeb2c5c26bf6c5d4c6eb9e38415034f4c93d3304d10bef38bf0ad420eefd0f72f940f11c5857786"),
		},
	}

	for i, test := range tests {
		// Ensure the state serializes to the expected value.
		gotBytes := serializeBestChainState(test.state)
		if !bytes.Equal(gotBytes, test.serialized) {
			t.Errorf("serializeBestChainState #%d (%s): mismatched "+
				"bytes - got %x, want %x", i, test.name,
				gotBytes, test.serialized)
			continue
		}

		// Ensure the serialized bytes are decoded back to the expected
		// state.
		state, err := deserializeBestChainState(test.serialized)
		if err != nil {
			t.Errorf("deserializeBestChainState #%d (%s) "+
				"unexpected error: %v", i, test.name, err)
			continue
		}
		if !reflect.DeepEqual(state, test.state) {
			t.Errorf("deserializeBestChainState #%d (%s) "+
				"mismatched state - got %v, want %v", i,
				test.name, state, test.state)
			continue

		}
	}
}
开发者ID:decred,项目名称:dcrd,代码行数:58,代码来源:chainio_test.go


示例3: TestTicketHashesSerializing

// TestTicketHashesSerializing ensures serializing and deserializing the
// ticket hashes works as expected.
func TestTicketHashesSerializing(t *testing.T) {
	t.Parallel()
	hash1 := chainhash.HashFuncH([]byte{0x00})
	hash2 := chainhash.HashFuncH([]byte{0x01})

	tests := []struct {
		name       string
		ths        TicketHashes
		serialized []byte
	}{
		{
			name: "two ticket hashes",
			ths: TicketHashes{
				hash1,
				hash2,
			},
			serialized: hexToBytes("0ce8d4ef4dd7cd8d62dfded9d4edb0a774ae6a41929a74da23109e8f11139c874a6c419a1e25c85327115c4ace586decddfe2990ed8f3d4d801871158338501d"),
		},
	}

	for i, test := range tests {
		// Ensure the state serializes to the expected value.
		gotBytes := serializeTicketHashes(test.ths)
		if !bytes.Equal(gotBytes, test.serialized) {
			t.Errorf("serializeBlockUndoData #%d (%s): mismatched "+
				"bytes - got %x, want %x", i, test.name,
				gotBytes, test.serialized)
			continue
		}

		// Ensure the serialized bytes are decoded back to the expected
		// state.
		ths, err := deserializeTicketHashes(test.serialized)
		if err != nil {
			t.Errorf("deserializeBlockUndoData #%d (%s) "+
				"unexpected error: %v", i, test.name, err)
			continue
		}
		if !reflect.DeepEqual(ths, test.ths) {
			t.Errorf("deserializeBlockUndoData #%d (%s) "+
				"mismatched state - got %v, want %v", i,
				test.name, ths, test.ths)
			continue

		}
	}
}
开发者ID:decred,项目名称:dcrd,代码行数:49,代码来源:chainio_test.go


示例4: HashMerkleBranches

// HashMerkleBranches takes two hashes, treated as the left and right tree
// nodes, and returns the hash of their concatenation.  This is a helper
// function used to aid in the generation of a merkle tree.
func HashMerkleBranches(left *chainhash.Hash, right *chainhash.Hash) *chainhash.Hash {
	// Concatenate the left and right nodes.
	var sha [chainhash.HashSize * 2]byte
	copy(sha[:chainhash.HashSize], left[:])
	copy(sha[chainhash.HashSize:], right[:])

	newSha := chainhash.HashFuncH(sha[:])
	return &newSha
}
开发者ID:ironbits,项目名称:dcrd,代码行数:12,代码来源:merkle.go


示例5: Verify

func (b Block) Verify() bool {
	databytes, err := hex.DecodeString(b.header[0:360])
	if err != nil {
		return false
	}
	hash := chainhash.HashFuncH(databytes)
	hashNum := blockchain.ShaHashToBig(&hash)
	return hashNum.Cmp(b.difficulty) <= 0
}
开发者ID:bitbandi,项目名称:decred-proxy,代码行数:9,代码来源:blocks.go


示例6: BlockSha

// BlockSha computes the block identifier hash for the given block header.
func (h *BlockHeader) BlockSha() chainhash.Hash {
	// Encode the header and hash256 everything prior to the number of
	// transactions.  Ignore the error returns since there is no way the
	// encode could fail except being out of memory which would cause a
	// run-time panic.
	var buf bytes.Buffer
	_ = writeBlockHeader(&buf, 0, h)

	return chainhash.HashFuncH(buf.Bytes())
}
开发者ID:decred,项目名称:dcrd,代码行数:11,代码来源:blockheader.go


示例7: StateHash

// StateHash returns a hash referencing the current state the deterministic PRNG.
func (hp *Hash256PRNG) StateHash() chainhash.Hash {
	fHash := hp.lastHash
	fIdx := hp.idx
	fHashIdx := hp.hashIdx

	finalState := make([]byte, len(fHash)+4+1)
	copy(finalState, fHash[:])
	binary.BigEndian.PutUint32(finalState[len(fHash):], uint32(fIdx))
	finalState[len(fHash)+4] = byte(fHashIdx)

	return chainhash.HashFuncH(finalState)
}
开发者ID:decred,项目名称:dcrd,代码行数:13,代码来源:lottery.go


示例8: BenchmarkHashFuncH

// BenchmarkHashFuncH performs a benchmark on how long it takes to perform
// a hash returning a Hash.
func BenchmarkHashFuncH(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.HashFuncH(txBytes)
	}
}
开发者ID:decred,项目名称:dcrd,代码行数:15,代码来源:bench_test.go


示例9: Hash256Rand

// Hash256Rand returns a uint32 random number using the pseudorandom number
// generator and updates the state.
func (hp *Hash256PRNG) Hash256Rand() uint32 {
	r := binary.BigEndian.Uint32(hp.lastHash[hp.hashIdx*4 : hp.hashIdx*4+4])
	hp.hashIdx++

	// 'roll over' the hash index to use and store it.
	if hp.hashIdx > 7 {
		idxB := make([]byte, 4, 4)
		binary.BigEndian.PutUint32(idxB, uint32(hp.idx))
		hp.lastHash = chainhash.HashFuncH(append(hp.seed[:], idxB...))
		hp.idx++
		hp.hashIdx = 0
	}

	// 'roll over' the PRNG by re-hashing the seed when
	// we overflow idx.
	if hp.idx > 0xFFFFFFFF {
		hp.seed = chainhash.HashFuncH(hp.seed[:])
		hp.lastHash = hp.seed
		hp.idx = 0
	}

	return r
}
开发者ID:decred,项目名称:dcrd,代码行数:25,代码来源:lottery.go


示例10: 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.
	hp := new(Hash256PRNG)
	hp.seed = chainhash.HashFuncH(append(seed, seedConst[:]...))
	hp.lastHash = hp.seed
	hp.idx = 0
	return hp
}
开发者ID:decred,项目名称:dcrd,代码行数:16,代码来源:lottery.go


示例11: TestFetchWinnersErrors

func TestFetchWinnersErrors(t *testing.T) {
	treap := new(tickettreap.Immutable)
	for i := 0; i < 0xff; i++ {
		h := chainhash.HashFuncH([]byte{byte(i)})
		v := &tickettreap.Value{
			Height:  uint32(i),
			Missed:  i%2 == 0,
			Revoked: i%2 != 0,
			Spent:   i%2 == 0,
			Expired: i%2 != 0,
		}
		treap = treap.Put(tickettreap.Key(h), v)
	}

	// No indexes.
	_, err := fetchWinners(nil, treap)
	if err == nil {
		t.Errorf("Expected nil slice error")
	}

	// No treap.
	_, err = fetchWinners([]int{1, 2, 3, 4, -1}, nil)
	if err == nil {
		t.Errorf("Expected nil treap error")
	}

	// Bad index too small.
	_, err = fetchWinners([]int{1, 2, 3, 4, -1}, treap)
	if err == nil {
		t.Errorf("Expected index too small error")
	}

	// Bad index too big.
	_, err = fetchWinners([]int{1, 2, 3, 4, 256}, treap)
	if err == nil {
		t.Errorf("Expected index too big error")
	}
}
开发者ID:decred,项目名称:dcrd,代码行数:38,代码来源:lottery_test.go


示例12: TestTicketSorting

func TestTicketSorting(t *testing.T) {
	ticketsPerBlock := 5
	ticketPoolSize := uint16(8192)
	totalTickets := uint32(ticketPoolSize) * uint32(5)
	bucketsSize := 256

	randomGen := rand.New(rand.NewSource(12345))
	ticketMap := make([]SStxMemMap, int(bucketsSize), int(bucketsSize))

	for i := 0; i < bucketsSize; i++ {
		ticketMap[i] = make(SStxMemMap)
	}

	toMake := int(ticketPoolSize) * ticketsPerBlock
	for i := 0; i < toMake; i++ {
		td := new(TicketData)

		rint64 := randomGen.Int63n(1 << 62)
		randBytes := make([]byte, 8, 8)
		binary.LittleEndian.PutUint64(randBytes, uint64(rint64))
		h := chainhash.HashFuncH(randBytes)
		td.SStxHash = h

		prefix := byte(h[0])

		ticketMap[prefix][h] = td
	}

	// Pre-sort with buckets (faster).
	sortedSlice := make([]*TicketData, 0, totalTickets)
	for i := 0; i < bucketsSize; i++ {
		tempTdSlice := NewTicketDataSlice(len(ticketMap[i]))
		itr := 0 // Iterator
		for _, td := range ticketMap[i] {
			tempTdSlice[itr] = td
			itr++
		}
		sort.Sort(tempTdSlice)
		sortedSlice = append(sortedSlice, tempTdSlice...)
	}
	sortedSlice1 := sortedSlice

	// However, it should be the same as a sort without the buckets.
	toSortSlice := make([]*TicketData, 0, totalTickets)
	for i := 0; i < bucketsSize; i++ {
		tempTdSlice := make([]*TicketData, len(ticketMap[i]),
			len(ticketMap[i]))
		itr := 0 // Iterator
		for _, td := range ticketMap[i] {
			tempTdSlice[itr] = td
			itr++
		}
		toSortSlice = append(toSortSlice, tempTdSlice...)
	}
	sortedSlice = NewTicketDataSlice(int(totalTickets))
	copy(sortedSlice, toSortSlice)
	sort.Sort(TicketDataSlice(sortedSlice))
	sortedSlice2 := sortedSlice

	if !reflect.DeepEqual(sortedSlice1, sortedSlice2) {
		t.Errorf("bucket sort failed to sort to the same slice as global sort")
	}
}
开发者ID:ironbits,项目名称:dcrd,代码行数:63,代码来源:lottery_test.go


示例13: TestLiveDatabase

// TestLiveDatabase tests various functions that require a live database.
func TestLiveDatabase(t *testing.T) {
	// Create a new database to store the accepted stake node data into.
	dbName := "ffldb_ticketdb_test"
	dbPath := filepath.Join(testDbRoot, dbName)
	_ = os.RemoveAll(dbPath)
	testDb, err := database.Create(testDbType, dbPath, chaincfg.SimNetParams.Net)
	if err != nil {
		t.Fatalf("error creating db: %v", err)
	}

	// Setup a teardown.
	defer os.RemoveAll(dbPath)
	defer os.RemoveAll(testDbRoot)
	defer testDb.Close()

	// Initialize the database, then try to read the version.
	err = testDb.Update(func(dbTx database.Tx) error {
		return DbCreate(dbTx)
	})
	if err != nil {
		t.Fatalf("%v", err.Error())
	}

	var dbi *DatabaseInfo
	err = testDb.View(func(dbTx database.Tx) error {
		dbi, err = DbFetchDatabaseInfo(dbTx)
		if err != nil {
			return err
		}

		return nil
	})
	if err != nil {
		t.Fatalf("%v", err.Error())
	}
	if dbi.Version != currentDatabaseVersion {
		t.Fatalf("bad version after reading from DB; want %v, got %v",
			currentDatabaseVersion, dbi.Version)
	}

	// Test storing arbitrary ticket treaps.
	ticketMap := make(map[tickettreap.Key]*tickettreap.Value)
	tickets := make([]chainhash.Hash, 5)
	for i := 0; i < 4; i++ {
		h := chainhash.HashFuncH(bytes.Repeat([]byte{0x01}, i))
		ticketMap[tickettreap.Key(h)] = &tickettreap.Value{
			Height:  12345 + uint32(i),
			Missed:  i%2 == 0,
			Revoked: i%2 != 0,
			Spent:   i%2 == 0,
			Expired: i%2 != 0,
		}
		tickets[i] = h
	}

	err = testDb.Update(func(dbTx database.Tx) error {
		for k, v := range ticketMap {
			h := chainhash.Hash(k)
			err = DbPutTicket(dbTx, dbnamespace.LiveTicketsBucketName, &h,
				v.Height, v.Missed, v.Revoked, v.Spent, v.Expired)
			if err != nil {
				return err
			}
		}

		return nil
	})
	if err != nil {
		t.Fatalf("%v", err.Error())
	}

	var treap *tickettreap.Immutable
	ticketMap2 := make(map[tickettreap.Key]*tickettreap.Value)
	err = testDb.View(func(dbTx database.Tx) error {
		treap, err = DbLoadAllTickets(dbTx, dbnamespace.LiveTicketsBucketName)
		if err != nil {
			return err
		}

		return nil
	})
	if err != nil {
		t.Fatalf("%v", err.Error())
	}
	treap.ForEach(func(k tickettreap.Key, v *tickettreap.Value) bool {
		ticketMap2[k] = v

		return true
	})

	if !reflect.DeepEqual(ticketMap, ticketMap2) {
		t.Fatalf("not same ticket maps")
	}
}
开发者ID:decred,项目名称:dcrd,代码行数:95,代码来源:chainio_test.go


示例14: estimateNextStakeDifficulty

// estimateNextStakeDifficulty returns a user-specified estimate for the next
// stake difficulty, with the passed ticketsInWindow indicating the number of
// fresh stake to pretend exists within this window. Optionally the user can
// also override this variable with useMaxTickets, which simply plugs in the
// maximum number of tickets the user can try.
func (b *BlockChain) estimateNextStakeDifficulty(curNode *blockNode,
	ticketsInWindow int64, useMaxTickets bool) (int64, error) {
	alpha := b.chainParams.StakeDiffAlpha
	stakeDiffStartHeight := int64(b.chainParams.CoinbaseMaturity) +
		1
	maxRetarget := int64(b.chainParams.RetargetAdjustmentFactor)
	TicketPoolWeight := int64(b.chainParams.TicketPoolSizeWeight)

	// Number of nodes to traverse while calculating difficulty.
	nodesToTraverse := (b.chainParams.StakeDiffWindowSize *
		b.chainParams.StakeDiffWindows)

	// Genesis block. Block at height 1 has these parameters.
	if curNode == nil ||
		curNode.height < stakeDiffStartHeight {
		return b.chainParams.MinimumStakeDiff, nil
	}

	// Create a fake blockchain on top of the current best node with
	// the number of freshly purchased tickets as indicated by the
	// user.
	oldDiff := curNode.header.SBits
	topNode := curNode
	if (curNode.height+1)%b.chainParams.StakeDiffWindowSize != 0 {
		nextAdjHeight := ((curNode.height /
			b.chainParams.StakeDiffWindowSize) + 1) *
			b.chainParams.StakeDiffWindowSize
		maxTickets := (nextAdjHeight - curNode.height) *
			int64(b.chainParams.MaxFreshStakePerBlock)

		// If the user has indicated that the automatically
		// calculated maximum amount of tickets should be
		// used, plug that in here.
		if useMaxTickets {
			ticketsInWindow = maxTickets
		}

		// Double check to make sure there isn't too much.
		if ticketsInWindow > maxTickets {
			return 0, fmt.Errorf("too much fresh stake to be used "+
				"in evaluation requested; max %v, got %v", maxTickets,
				ticketsInWindow)
		}

		// Insert all the tickets into bogus nodes that will be
		// used to calculate the next difficulty below.
		ticketsToInsert := ticketsInWindow
		for i := curNode.height + 1; i < nextAdjHeight; i++ {
			emptyHeader := new(wire.BlockHeader)
			emptyHeader.Height = uint32(i)

			// User a constant pool size for estimate, since
			// this has much less fluctuation than freshStake.
			// TODO Use a better pool size estimate?
			emptyHeader.PoolSize = curNode.header.PoolSize

			// Insert the fake fresh stake into each block,
			// decrementing the amount we need to use each
			// time until we hit 0.
			freshStake := b.chainParams.MaxFreshStakePerBlock
			if int64(freshStake) > ticketsToInsert {
				freshStake = uint8(ticketsToInsert)
				ticketsToInsert -= ticketsToInsert
			} else {
				ticketsToInsert -= int64(b.chainParams.MaxFreshStakePerBlock)
			}
			emptyHeader.FreshStake = freshStake

			// Connect the header.
			emptyHeader.PrevBlock = topNode.hash

			// Make up a node hash.
			hB, err := emptyHeader.Bytes()
			if err != nil {
				return 0, err
			}
			emptyHeaderHash := chainhash.HashFuncH(hB)

			thisNode := new(blockNode)
			thisNode.header = *emptyHeader
			thisNode.hash = emptyHeaderHash
			thisNode.height = i
			thisNode.parent = topNode
			topNode = thisNode
		}
	}

	// The target size of the ticketPool in live tickets. Recast these as int64
	// to avoid possible overflows for large sizes of either variable in
	// params.
	targetForTicketPool := int64(b.chainParams.TicketsPerBlock) *
		int64(b.chainParams.TicketPoolSize)

	// Initialize bigInt slice for the percentage changes for each window period
	// above or below the target.
//.........这里部分代码省略.........
开发者ID:decred,项目名称:dcrd,代码行数:101,代码来源:difficulty.go


示例15: TestCalcSignatureHash

// TestCalcSignatureHash does some rudimentary testing of msg hash calculation.
func TestCalcSignatureHash(t *testing.T) {
	tx := new(wire.MsgTx)
	for i := 0; i < 3; i++ {
		txIn := new(wire.TxIn)
		txIn.Sequence = 0xFFFFFFFF
		txIn.PreviousOutPoint.Hash = chainhash.HashFuncH([]byte{byte(i)})
		txIn.PreviousOutPoint.Index = uint32(i)
		txIn.PreviousOutPoint.Tree = int8(0)
		tx.AddTxIn(txIn)
	}
	for i := 0; i < 2; i++ {
		txOut := new(wire.TxOut)
		txOut.PkScript = []byte{0x01, 0x01, 0x02, 0x03}
		txOut.Value = 0x0000FF00FF00FF00
		tx.AddTxOut(txOut)
	}

	want, _ := hex.DecodeString("d09285b6f60c71329323bc2e76c48" +
		"a462cde4e1032aa8f59c55823f1722c7f4a")
	pops, _ := txscript.TstParseScript([]byte{0x01, 0x01, 0x02, 0x03})

	// Test prefix caching.
	msg1, err := txscript.CalcSignatureHash(pops, txscript.SigHashAll, tx, 0, nil)
	if err != nil {
		t.Fatalf("unexpected error %v", err.Error())
	}

	prefixHash := tx.TxSha()
	msg2, err := txscript.CalcSignatureHash(pops, txscript.SigHashAll, tx, 0,
		&prefixHash)
	if err != nil {
		t.Fatalf("unexpected error %v", err.Error())
	}

	if !bytes.Equal(msg1, want) {
		t.Errorf("for sighash all sig noncached wrong msg %x given, want %x",
			msg1,
			want)
	}
	if !bytes.Equal(msg2, want) {
		t.Errorf("for sighash all sig cached wrong msg %x given, want %x",
			msg1,
			want)
	}
	if !bytes.Equal(msg1, msg2) {
		t.Errorf("for sighash all sig non-equivalent msgs %x and %x were "+
			"returned when using a cached prefix",
			msg1,
			msg2)
	}

	// Move the index and make sure that we get a whole new hash, despite
	// using the same TxOuts.
	msg3, err := txscript.CalcSignatureHash(pops, txscript.SigHashAll, tx, 1,
		&prefixHash)
	if err != nil {
		t.Fatalf("unexpected error %v", err.Error())
	}

	if bytes.Equal(msg1, msg3) {
		t.Errorf("for sighash all sig equivalent msgs %x and %x were "+
			"returned when using a cached prefix but different indices",
			msg1,
			msg3)
	}
}
开发者ID:zebbra2014,项目名称:dcrd,代码行数:67,代码来源:script_test.go


示例16: TestTicketDBGeneral


//.........这里部分代码省略.........
	_, err = connectNode(nil, b162.MsgBlock().Header,
		n162Test.SpentByBlock(), revokedTicketsInBlock(b162),
		n162Test.NewTickets())
	if err == nil {
		t.Errorf("expect error for no node")
	}

	// Best node missing ticket in live ticket bucket to spend.
	n161Copy := copyNode(nodesForward[161])
	n161Copy.liveTickets.Delete(tickettreap.Key(n162Test.SpentByBlock()[0]))
	_, err = n161Copy.ConnectNode(b162.MsgBlock().Header,
		n162Test.SpentByBlock(), revokedTicketsInBlock(b162),
		n162Test.NewTickets())
	if err == nil || err.(RuleError).GetCode() != ErrMissingTicket {
		t.Errorf("unexpected wrong or no error for "+
			"Best node missing ticket in live ticket bucket to spend: %v", err)
	}

	// Duplicate best winners.
	n161Copy = copyNode(nodesForward[161])
	n162Copy := copyNode(nodesForward[162])
	n161Copy.nextWinners[0] = n161Copy.nextWinners[1]
	spentInBlock := n162Copy.SpentByBlock()
	spentInBlock[0] = spentInBlock[1]
	_, err = n161Copy.ConnectNode(b162.MsgBlock().Header,
		spentInBlock, revokedTicketsInBlock(b162),
		n162Test.NewTickets())
	if err == nil || err.(RuleError).GetCode() != ErrMissingTicket {
		t.Errorf("unexpected wrong or no error for "+
			"Best node missing ticket in live ticket bucket to spend: %v", err)
	}

	// Test for corrupted spentInBlock.
	someHash := chainhash.HashFuncH([]byte{0x00})
	spentInBlock = n162Test.SpentByBlock()
	spentInBlock[4] = someHash
	_, err = nodesForward[161].ConnectNode(b162.MsgBlock().Header,
		spentInBlock, revokedTicketsInBlock(b162), n162Test.NewTickets())
	if err == nil || err.(RuleError).GetCode() != ErrUnknownTicketSpent {
		t.Errorf("unexpected wrong or no error for "+
			"Test for corrupted spentInBlock: %v", err)
	}

	// Corrupt winners.
	n161Copy = copyNode(nodesForward[161])
	n161Copy.nextWinners[4] = someHash
	_, err = n161Copy.ConnectNode(b162.MsgBlock().Header,
		spentInBlock, revokedTicketsInBlock(b162), n162Test.NewTickets())
	if err == nil || err.(RuleError).GetCode() != ErrMissingTicket {
		t.Errorf("unexpected wrong or no error for "+
			"Corrupt winners: %v", err)
	}

	// Unknown missed ticket.
	n162Copy = copyNode(nodesForward[162])
	spentInBlock = n162Copy.SpentByBlock()
	_, err = nodesForward[161].ConnectNode(b162.MsgBlock().Header,
		spentInBlock, append(revokedTicketsInBlock(b162), someHash),
		n162Copy.NewTickets())
	if err == nil || err.(RuleError).GetCode() != ErrMissingTicket {
		t.Errorf("unexpected wrong or no error for "+
			"Unknown missed ticket: %v", err)
	}

	// Insert a duplicate new ticket.
	spentInBlock = n162Test.SpentByBlock()
开发者ID:decred,项目名称:dcrd,代码行数:67,代码来源:tickets_test.go



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Golang chainhash.NewHash函数代码示例发布时间:2022-05-23
下一篇:
Golang chainhash.HashFuncB函数代码示例发布时间:2022-05-23
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap