當前位置: 首頁>>代碼示例>>Golang>>正文


Golang dcrutil.NewBlockFromBytes函數代碼示例

本文整理匯總了Golang中github.com/decred/dcrutil.NewBlockFromBytes函數的典型用法代碼示例。如果您正苦於以下問題:Golang NewBlockFromBytes函數的具體用法?Golang NewBlockFromBytes怎麽用?Golang NewBlockFromBytes使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。


在下文中一共展示了NewBlockFromBytes函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。

示例1: loadBlocks

func loadBlocks(t *testing.T, file string) (blocks []*dcrutil.Block, err error) {
	fi, err := os.Open(file)
	if err != nil {
		t.Errorf("failed to open file %v, err %v", file, err)
		return nil, err
	}
	bcStream := bzip2.NewReader(fi)
	defer fi.Close()

	// Create a buffer of the read file
	bcBuf := new(bytes.Buffer)
	bcBuf.ReadFrom(bcStream)

	// Create decoder from the buffer and a map to store the data
	bcDecoder := gob.NewDecoder(bcBuf)
	blockchain := make(map[int64][]byte)

	// Decode the blockchain into the map
	if err := bcDecoder.Decode(&blockchain); err != nil {
		t.Errorf("error decoding test blockchain")
	}
	blocks = make([]*dcrutil.Block, 0, len(blockchain))
	for height := int64(1); height < int64(len(blockchain)); height++ {
		block, err := dcrutil.NewBlockFromBytes(blockchain[height])
		if err != nil {
			t.Errorf("failed to parse block %v", height)
			return nil, err
		}
		block.SetHeight(height - 1)
		blocks = append(blocks, block)
	}

	return
}
開發者ID:zebbra2014,項目名稱:dcrd,代碼行數:34,代碼來源:operational_test.go

示例2: TestNewBlockFromBytes

// TestNewBlockFromBytes tests creation of a Block from serialized bytes.
func TestNewBlockFromBytes(t *testing.T) {
	// Serialize the test block.
	var block100000Buf bytes.Buffer
	err := Block100000.Serialize(&block100000Buf)
	if err != nil {
		t.Errorf("Serialize: %v", err)
	}
	block100000Bytes := block100000Buf.Bytes()

	// Create a new block from the serialized bytes.
	b, err := dcrutil.NewBlockFromBytes(block100000Bytes)
	if err != nil {
		t.Errorf("NewBlockFromBytes: %v", err)
		return
	}

	// Ensure we get the same data back out.
	serializedBytes, err := b.Bytes()
	if err != nil {
		t.Errorf("Bytes: %v", err)
		return
	}
	if !bytes.Equal(serializedBytes, block100000Bytes) {
		t.Errorf("Bytes: wrong bytes - got %v, want %v",
			spew.Sdump(serializedBytes),
			spew.Sdump(block100000Bytes))
	}

	// Ensure the generated MsgBlock is correct.
	if msgBlock := b.MsgBlock(); !reflect.DeepEqual(msgBlock, &Block100000) {
		t.Errorf("MsgBlock: mismatched MsgBlock - got %v, want %v",
			spew.Sdump(msgBlock), spew.Sdump(&Block100000))
	}
}
開發者ID:alexlyp,項目名稱:dcrutil,代碼行數:35,代碼來源:block_test.go

示例3: processBlock

// processBlock potentially imports the block into the database.  It first
// deserializes the raw block while checking for errors.  Already known blocks
// are skipped and orphan blocks are considered errors.  Finally, it runs the
// block through the chain rules to ensure it follows all rules and matches
// up to the known checkpoint.  Returns whether the block was imported along
// with any potential errors.
func (bi *blockImporter) processBlock(serializedBlock []byte) (bool, error) {
	// Deserialize the block which includes checks for malformed blocks.
	block, err := dcrutil.NewBlockFromBytes(serializedBlock)
	if err != nil {
		return false, err
	}

	// update progress statistics
	bi.lastBlockTime = block.MsgBlock().Header.Timestamp
	bi.receivedLogTx += int64(len(block.MsgBlock().Transactions))

	// Skip blocks that already exist.
	blockSha := block.Sha()
	exists, err := bi.db.ExistsSha(blockSha)
	if err != nil {
		return false, err
	}
	if exists {
		return false, nil
	}

	// Don't bother trying to process orphans.
	prevHash := &block.MsgBlock().Header.PrevBlock
	if !prevHash.IsEqual(&zeroHash) {
		exists, err := bi.db.ExistsSha(prevHash)
		if err != nil {
			return false, err
		}
		if !exists {
			return false, fmt.Errorf("import file contains block "+
				"%v which does not link to the available "+
				"block chain", prevHash)
		}
	}

	// Ensure the blocks follows all of the chain rules and match up to the
	// known checkpoints.
	_, isOrphan, err := bi.chain.ProcessBlock(block, bi.medianTime,
		blockchain.BFFastAdd)
	if err != nil {
		return false, err
	}
	if isOrphan {
		return false, fmt.Errorf("import file contains an orphan "+
			"block: %v", blockSha)
	}

	return true, nil
}
開發者ID:ironbits,項目名稱:dcrd,代碼行數:55,代碼來源:import.go

示例4: fetchBlockBySha

// fetchBlockBySha - return a dcrutil Block
// Must be called with db lock held.
func (db *LevelDb) fetchBlockBySha(sha *chainhash.Hash) (blk *dcrutil.Block, err error) {

	buf, height, err := db.fetchSha(sha)
	if err != nil {
		return
	}

	blk, err = dcrutil.NewBlockFromBytes(buf)
	if err != nil {
		return
	}
	blk.SetHeight(height)

	return
}
開發者ID:ironbits,項目名稱:dcrd,代碼行數:17,代碼來源:block.go

示例5: TestMerkleBlock3

func TestMerkleBlock3(t *testing.T) {
	blockStr := "0100000073cf056852529ffadc50b49589218795adc4d3f24170950d49f201000000000033fd46dda0acfa5c0651c58bee00362b04186c5b4d1045d37751b25779148649000000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000ffff011b00c2eb0b00000000000100007e0100006614b956bee4fc44442bf144050552b3010000000000000000000000000000000000000000000000000000000101000000010000000000000000000000000000000000000000000000000000000000000000ffffffff00ffffffff03fa1a981200000000000017a914f5916158e3e2c4551c1796708db8367207ed13bb8700000000000000000000266a24000100000000000000000000000000000000000000000000000000004dfb774daa8f3a76dea1906f0000000000001976a914b74b7476bdbcf03d18f12cca1766b0ddfd030cdd88ac000000000000000001d8bc28820000000000000000ffffffff0800002f646372642f00"

	blockBytes, err := hex.DecodeString(blockStr)
	if err != nil {
		t.Errorf("TestMerkleBlock3 DecodeString failed: %v", err)
		return
	}
	blk, err := dcrutil.NewBlockFromBytes(blockBytes)
	if err != nil {
		t.Errorf("TestMerkleBlock3 NewBlockFromBytes failed: %v", err)
		return
	}
	f := bloom.NewFilter(10, 0, 0.000001, wire.BloomUpdateAll)

	inputStr := "4986147957b25177d345104d5b6c18042b3600ee8bc551065cfaaca0dd46fd33"
	hash, err := chainhash.NewHashFromStr(inputStr)
	if err != nil {
		t.Errorf("TestMerkleBlock3 NewHashFromStr failed: %v", err)
		return
	}

	f.AddHash(hash)

	mBlock, _ := bloom.NewMerkleBlock(blk, f)
	wantStr := "0100000073cf056852529ffadc50b49589218795adc4d3f24170950d49f201000000000033fd46dda0acfa5c0651c58bee00362b04186c5b4d1045d37751b25779148649000000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000ffff011b00c2eb0b00000000000100007e0100006614b956bee4fc44442bf144050552b3010000000000000000000000000000000000000000000000000000000100000001d0f51e5a4978d736eb3d4a8d615bee74943756b4745d29b27ab2943bc1307cc800000000000100"
	want, err := hex.DecodeString(wantStr)
	if err != nil {
		t.Errorf("TestMerkleBlock3 DecodeString failed: %v", err)
		return
	}

	got := bytes.NewBuffer(nil)
	err = mBlock.BtcEncode(got, wire.ProtocolVersion)
	if err != nil {
		t.Errorf("TestMerkleBlock3 BtcEncode failed: %v", err)
		return
	}

	if !bytes.Equal(want, got.Bytes()) {
		t.Errorf("TestMerkleBlock3 failed merkle block comparison: "+
			"got %v want %v", got.Bytes(), want)
		return
	}
}
開發者ID:decred,項目名稱:dcrutil,代碼行數:45,代碼來源:merkleblock_test.go

示例6: loadBlocks

// loadBlocks loads the blocks contained in the testdata directory and returns
// a slice of them.
func loadBlocks(t *testing.T, dataFile string, network wire.CurrencyNet) ([]*dcrutil.Block, error) {
	// Open the file that contains the blocks for reading.
	fi, err := os.Open(dataFile)
	if err != nil {
		t.Errorf("failed to open file %v, err %v", dataFile, err)
		return nil, err
	}
	defer func() {
		if err := fi.Close(); err != nil {
			t.Errorf("failed to close file %v %v", dataFile,
				err)
		}
	}()

	bcStream := bzip2.NewReader(fi)

	// Create a buffer of the read file.
	bcBuf := new(bytes.Buffer)
	bcBuf.ReadFrom(bcStream)

	// Create decoder from the buffer and a map to store the data.
	bcDecoder := gob.NewDecoder(bcBuf)
	blockChain := make(map[int64][]byte)

	// Decode the blockchain into the map.
	if err := bcDecoder.Decode(&blockChain); err != nil {
		t.Errorf("error decoding test blockchain: %v", err.Error())
	}

	// Fetch blocks 1 to 168 and perform various tests.
	blocks := make([]*dcrutil.Block, 169)
	for i := 0; i <= 168; i++ {
		bl, err := dcrutil.NewBlockFromBytes(blockChain[int64(i)])
		if err != nil {
			t.Errorf("NewBlockFromBytes error: %v", err.Error())
		}
		bl.SetHeight(int64(i))

		blocks[i] = bl
	}

	return blocks, nil
}
開發者ID:decred,項目名稱:dcrd,代碼行數:45,代碼來源:whitebox_test.go

示例7: loadReorgBlocks

// loadReorgBlocks reads files containing decred block data (bzipped but
// otherwise in the format bitcoind writes) from disk and returns them as an
// array of dcrutil.Block. This is copied from the blockchain package, which
// itself largely borrowed it from the test code in this package.
func loadReorgBlocks(filename string) ([]*dcrutil.Block, error) {
	filename = filepath.Join("../blockchain/testdata/", filename)
	fi, err := os.Open(filename)
	if err != nil {
		return nil, err
	}
	bcStream := bzip2.NewReader(fi)
	defer fi.Close()

	// Create a buffer of the read file
	bcBuf := new(bytes.Buffer)
	bcBuf.ReadFrom(bcStream)

	// Create decoder from the buffer and a map to store the data
	bcDecoder := gob.NewDecoder(bcBuf)
	blockchain := make(map[int64][]byte)

	// Decode the blockchain into the map
	if err := bcDecoder.Decode(&blockchain); err != nil {
		return nil, err
	}

	var block *dcrutil.Block

	blocks := make([]*dcrutil.Block, 0, len(blockchain))
	for height := int64(0); height < int64(len(blockchain)); height++ {
		block, err = dcrutil.NewBlockFromBytes(blockchain[height])
		if err != nil {
			return blocks, err
		}
		block.SetHeight(height)
		blocks = append(blocks, block)
	}

	return blocks, nil
}
開發者ID:ironbits,項目名稱:dcrd,代碼行數:40,代碼來源:reorg_test.go

示例8: TestBlockErrors

// TestBlockErrors tests the error paths for the Block API.
func TestBlockErrors(t *testing.T) {
	// Ensure out of range errors are as expected.
	wantErr := "transaction index -1 is out of range - max 3"
	testErr := dcrutil.OutOfRangeError(wantErr)
	if testErr.Error() != wantErr {
		t.Errorf("OutOfRangeError: wrong error - got %v, want %v",
			testErr.Error(), wantErr)
	}

	// Serialize the test block.
	var block100000Buf bytes.Buffer
	err := Block100000.Serialize(&block100000Buf)
	if err != nil {
		t.Errorf("Serialize: %v", err)
	}
	block100000Bytes := block100000Buf.Bytes()

	// Create a new block from the serialized bytes.
	b, err := dcrutil.NewBlockFromBytes(block100000Bytes)
	if err != nil {
		t.Errorf("NewBlockFromBytes: %v", err)
		return
	}

	// Truncate the block byte buffer to force errors.
	shortBytes := block100000Bytes[:100]
	_, err = dcrutil.NewBlockFromBytes(shortBytes)
	if err != io.EOF {
		t.Errorf("NewBlockFromBytes: did not get expected error - "+
			"got %v, want %v", err, io.EOF)
	}

	// Ensure TxSha returns expected error on invalid indices.
	_, err = b.TxSha(-1)
	if _, ok := err.(dcrutil.OutOfRangeError); !ok {
		t.Errorf("TxSha: wrong error - got: %v <%T>, "+
			"want: <%T>", err, err, dcrutil.OutOfRangeError(""))
	}
	_, err = b.TxSha(len(Block100000.Transactions) + 1)
	if _, ok := err.(dcrutil.OutOfRangeError); !ok {
		t.Errorf("TxSha: wrong error - got: %v <%T>, "+
			"want: <%T>", err, err, dcrutil.OutOfRangeError(""))
	}

	// Ensure Tx returns expected error on invalid indices.
	_, err = b.Tx(-1)
	if _, ok := err.(dcrutil.OutOfRangeError); !ok {
		t.Errorf("Tx: wrong error - got: %v <%T>, "+
			"want: <%T>", err, err, dcrutil.OutOfRangeError(""))
	}
	_, err = b.Tx(len(Block100000.Transactions) + 1)
	if _, ok := err.(dcrutil.OutOfRangeError); !ok {
		t.Errorf("Tx: wrong error - got: %v <%T>, "+
			"want: <%T>", err, err, dcrutil.OutOfRangeError(""))
	}

	// Ensure TxLoc returns expected error with short byte buffer.
	// This makes use of the test package only function, SetBlockBytes, to
	// inject a short byte buffer.
	b.SetBlockBytes(shortBytes)
	_, _, err = b.TxLoc()
	if err != io.EOF {
		t.Errorf("TxLoc: did not get expected error - "+
			"got %v, want %v", err, io.EOF)
	}
}
開發者ID:alexlyp,項目名稱:dcrutil,代碼行數:67,代碼來源:block_test.go

示例9: TestTicketDB

func TestTicketDB(t *testing.T) {
	// Declare some useful variables
	testBCHeight := int64(168)

	// Set up a DB
	database, err := database.CreateDB("leveldb", "ticketdb_test")
	if err != nil {
		t.Errorf("Db create error: %v", err.Error())
	}

	// Make a new tmdb to fill with dummy live and used tickets
	var tmdb stake.TicketDB
	tmdb.Initialize(simNetParams, database)

	filename := filepath.Join("..", "/../blockchain/testdata", "blocks0to168.bz2")
	fi, err := os.Open(filename)
	bcStream := bzip2.NewReader(fi)
	defer fi.Close()

	// Create a buffer of the read file
	bcBuf := new(bytes.Buffer)
	bcBuf.ReadFrom(bcStream)

	// Create decoder from the buffer and a map to store the data
	bcDecoder := gob.NewDecoder(bcBuf)
	blockchain := make(map[int64][]byte)

	// Decode the blockchain into the map
	if err := bcDecoder.Decode(&blockchain); err != nil {
		t.Errorf("error decoding test blockchain")
	}

	var CopyOfMapsAtBlock50, CopyOfMapsAtBlock168 stake.TicketMaps
	var ticketsToSpendIn167 []chainhash.Hash
	var sortedTickets167 []*stake.TicketData

	for i := int64(0); i <= testBCHeight; i++ {
		block, err := dcrutil.NewBlockFromBytes(blockchain[i])
		if err != nil {
			t.Errorf("block deserialization error on block %v", i)
		}
		block.SetHeight(i)
		database.InsertBlock(block)
		tmdb.InsertBlock(block)

		if i == 50 {
			// Create snapshot of tmdb at block 50
			CopyOfMapsAtBlock50, err = cloneTicketDB(&tmdb)
			if err != nil {
				t.Errorf("db cloning at block 50 failure! %v", err)
			}
		}

		// Test to make sure that ticket selection is working correctly.
		if i == 167 {
			// Sort the entire list of tickets lexicographically by sorting
			// each bucket and then appending it to the list. Then store it
			// to use in the next block.
			totalTickets := 0
			sortedSlice := make([]*stake.TicketData, 0)
			for i := 0; i < stake.BucketsSize; i++ {
				tix, err := tmdb.DumpLiveTickets(uint8(i))
				if err != nil {
					t.Errorf("error dumping live tickets")
				}
				mapLen := len(tix)
				totalTickets += mapLen
				tempTdSlice := stake.NewTicketDataSlice(mapLen)
				itr := 0 // Iterator
				for _, td := range tix {
					tempTdSlice[itr] = td
					itr++
				}
				sort.Sort(tempTdSlice)
				sortedSlice = append(sortedSlice, tempTdSlice...)
			}
			sortedTickets167 = sortedSlice
		}

		if i == 168 {
			parentBlock, err := dcrutil.NewBlockFromBytes(blockchain[i-1])
			if err != nil {
				t.Errorf("block deserialization error on block %v", i-1)
			}
			pbhB, err := parentBlock.MsgBlock().Header.Bytes()
			if err != nil {
				t.Errorf("block header serialization error")
			}
			prng := stake.NewHash256PRNG(pbhB)
			ts, err := stake.FindTicketIdxs(int64(len(sortedTickets167)),
				int(simNetParams.TicketsPerBlock), prng)
			if err != nil {
				t.Errorf("failure on FindTicketIdxs")
			}
			for _, idx := range ts {
				ticketsToSpendIn167 =
					append(ticketsToSpendIn167, sortedTickets167[idx].SStxHash)
			}

			// Make sure that the tickets that were supposed to be spent or
//.........這裏部分代碼省略.........
開發者ID:alexlyp,項目名稱:dcrd,代碼行數:101,代碼來源:ticketdb_test.go

示例10: TestReorganization

// TestReorganization loads a set of test blocks which force a chain
// reorganization to test the block chain handling code.
func TestReorganization(t *testing.T) {
	// Create a new database and chain instance to run tests against.
	chain, teardownFunc, err := chainSetup("reorgunittest",
		simNetParams)
	if err != nil {
		t.Errorf("Failed to setup chain instance: %v", err)
		return
	}
	defer teardownFunc()

	err = chain.GenerateInitialIndex()
	if err != nil {
		t.Errorf("GenerateInitialIndex: %v", err)
	}

	// The genesis block should fail to connect since it's already
	// inserted.
	genesisBlock := simNetParams.GenesisBlock
	err = chain.CheckConnectBlock(dcrutil.NewBlock(genesisBlock))
	if err == nil {
		t.Errorf("CheckConnectBlock: Did not receive expected error")
	}

	// Load up the rest of the blocks up to HEAD.
	filename := filepath.Join("testdata/", "reorgto179.bz2")
	fi, err := os.Open(filename)
	bcStream := bzip2.NewReader(fi)
	defer fi.Close()

	// Create a buffer of the read file
	bcBuf := new(bytes.Buffer)
	bcBuf.ReadFrom(bcStream)

	// Create decoder from the buffer and a map to store the data
	bcDecoder := gob.NewDecoder(bcBuf)
	blockChain := make(map[int64][]byte)

	// Decode the blockchain into the map
	if err := bcDecoder.Decode(&blockChain); err != nil {
		t.Errorf("error decoding test blockchain: %v", err.Error())
	}

	// Load up the short chain
	timeSource := blockchain.NewMedianTime()
	finalIdx1 := 179
	for i := 1; i < finalIdx1+1; i++ {
		bl, err := dcrutil.NewBlockFromBytes(blockChain[int64(i)])
		if err != nil {
			t.Errorf("NewBlockFromBytes error: %v", err.Error())
		}
		bl.SetHeight(int64(i))

		_, _, err = chain.ProcessBlock(bl, timeSource, blockchain.BFNone)
		if err != nil {
			t.Errorf("ProcessBlock error: %v", err.Error())
		}
	}

	// Load the long chain and begin loading blocks from that too,
	// forcing a reorganization
	// Load up the rest of the blocks up to HEAD.
	filename = filepath.Join("testdata/", "reorgto180.bz2")
	fi, err = os.Open(filename)
	bcStream = bzip2.NewReader(fi)
	defer fi.Close()

	// Create a buffer of the read file
	bcBuf = new(bytes.Buffer)
	bcBuf.ReadFrom(bcStream)

	// Create decoder from the buffer and a map to store the data
	bcDecoder = gob.NewDecoder(bcBuf)
	blockChain = make(map[int64][]byte)

	// Decode the blockchain into the map
	if err := bcDecoder.Decode(&blockChain); err != nil {
		t.Errorf("error decoding test blockchain: %v", err.Error())
	}

	forkPoint := 131
	finalIdx2 := 180
	for i := forkPoint; i < finalIdx2+1; i++ {
		bl, err := dcrutil.NewBlockFromBytes(blockChain[int64(i)])
		if err != nil {
			t.Errorf("NewBlockFromBytes error: %v", err.Error())
		}
		bl.SetHeight(int64(i))

		_, _, err = chain.ProcessBlock(bl, timeSource, blockchain.BFNone)
		if err != nil {
			t.Errorf("ProcessBlock error: %v", err.Error())
		}
	}

	// Ensure our blockchain is at the correct best tip
	topBlock, _ := chain.GetTopBlock()
	tipHash := topBlock.Sha()
	expected, _ := chainhash.NewHashFromStr("5ab969d0afd8295b6cd1506f2a310d" +
//.........這裏部分代碼省略.........
開發者ID:ironbits,項目名稱:dcrd,代碼行數:101,代碼來源:reorganization_test.go

示例11: TestFilterInsertP2PubKeyOnly

func TestFilterInsertP2PubKeyOnly(t *testing.T) {
	blockStr := "000000004ad131bae9cb9f74b8bcd928" +
		"a60dfe4dadabeb31b1e79403385f9ac4" +
		"ccc28b7400429e56f7df2872aaaa0c16" +
		"221cb09059bd3ea897de156ff51202ff" +
		"72b2cd8d000000000000000000000000" +
		"00000000000000000000000000000000" +
		"00000000010000000000000000000000" +
		"22000000ffff7f20002d310100000000" +
		"640000007601000063a0815601000000" +
		"00000000000000000000000000000000" +
		"00000000000000000000000000000000" +
		"00000000010100000001000000000000" +
		"00000000000000000000000000000000" +
		"00000000000000000000ffffffff00ff" +
		"ffffff0380b2e60e00000000000017a9" +
		"144fa6cbd0dbe5ec407fe4c8ad374e66" +
		"7771fa0d448700000000000000000000" +
		"226a2000000000000000000000000000" +
		"0000009e0453a6ab10610e17a7a5fadc" +
		"f6c34f002f68590000000000001976a9" +
		"141b79e6496226f89ad4e049667c1344" +
		"c16a75815188ac000000000000000001" +
		"000000000000000000000000ffffffff" +
		"04deadbeef00"
	blockBytes, err := hex.DecodeString(blockStr)
	if err != nil {
		t.Errorf("TestFilterInsertP2PubKeyOnly DecodeString failed: %v", err)
		return
	}
	block, err := dcrutil.NewBlockFromBytes(blockBytes)
	if err != nil {
		t.Errorf("TestFilterInsertP2PubKeyOnly NewBlockFromBytes failed: %v", err)
		return
	}

	f := bloom.NewFilter(10, 0, 0.000001, wire.BloomUpdateP2PubkeyOnly)

	// Generation pubkey
	inputStr := "04eaafc2314def4ca98ac970241bcab022b9c1e1f4ea423a20f134c" +
		"876f2c01ec0f0dd5b2e86e7168cefe0d81113c3807420ce13ad1357231a" +
		"2252247d97a46a91"
	inputBytes, err := hex.DecodeString(inputStr)
	if err != nil {
		t.Errorf("TestFilterInsertP2PubKeyOnly DecodeString failed: %v", err)
		return
	}
	f.Add(inputBytes)

	// Output address of 4th transaction
	inputStr = "b6efd80d99179f4f4ff6f4dd0a007d018c385d21"
	inputBytes, err = hex.DecodeString(inputStr)
	if err != nil {
		t.Errorf("TestFilterInsertP2PubKeyOnly DecodeString failed: %v", err)
		return
	}
	f.Add(inputBytes)

	// Ignore return value -- this is just used to update the filter.
	_, _ = bloom.NewMerkleBlock(block, f)

	// We should match the generation pubkey
	inputStr = "147caa76786596590baa4e98f5d9f48b86c7765e489f7a6ff3360fe5c674360b"
	sha, err := chainhash.NewHashFromStr(inputStr)
	if err != nil {
		t.Errorf("TestMerkleBlockP2PubKeyOnly NewShaHashFromStr failed: %v", err)
		return
	}
	outpoint := wire.NewOutPoint(sha, 0, dcrutil.TxTreeRegular)
	if !f.MatchesOutPoint(outpoint) {
		t.Errorf("TestMerkleBlockP2PubKeyOnly didn't match the generation "+
			"outpoint %s", inputStr)
		return
	}

	// We should not match the 4th transaction, which is not p2pk
	inputStr = "02981fa052f0481dbc5868f4fc2166035a10f27a03cfd2de67326471df5bc041"
	sha, err = chainhash.NewHashFromStr(inputStr)
	if err != nil {
		t.Errorf("TestMerkleBlockP2PubKeyOnly NewShaHashFromStr failed: %v", err)
		return
	}
	outpoint = wire.NewOutPoint(sha, 0, dcrutil.TxTreeRegular)
	if f.MatchesOutPoint(outpoint) {
		t.Errorf("TestMerkleBlockP2PubKeyOnly matched outpoint %s", inputStr)
		return
	}
}
開發者ID:alexlyp,項目名稱:dcrutil,代碼行數:88,代碼來源:filter_test.go

示例12: reorgTestForced

// reorgTestsForced tests a forced reorganization of a single block at HEAD.
func reorgTestForced(t *testing.T) {
	// Create a new database and chain instance to run tests against.
	chain, teardownFunc, err := chainSetup("reorgunittest",
		simNetParams)
	if err != nil {
		t.Errorf("Failed to setup chain instance: %v", err)
		return
	}
	defer teardownFunc()

	// The genesis block should fail to connect since it's already
	// inserted.
	genesisBlock := simNetParams.GenesisBlock
	err = chain.CheckConnectBlock(dcrutil.NewBlock(genesisBlock))
	if err == nil {
		t.Errorf("CheckConnectBlock: Did not receive expected error")
	}

	// Load up the rest of the blocks up to HEAD.
	filename := filepath.Join("testdata/", "reorgto179.bz2")
	fi, err := os.Open(filename)
	bcStream := bzip2.NewReader(fi)
	defer fi.Close()

	// Create a buffer of the read file
	bcBuf := new(bytes.Buffer)
	bcBuf.ReadFrom(bcStream)

	// Create decoder from the buffer and a map to store the data
	bcDecoder := gob.NewDecoder(bcBuf)
	blockChain := make(map[int64][]byte)

	// Decode the blockchain into the map
	if err := bcDecoder.Decode(&blockChain); err != nil {
		t.Errorf("error decoding test blockchain: %v", err.Error())
	}

	// Load up the short chain
	finalIdx1 := 131
	var oldBestHash *chainhash.Hash
	for i := 1; i < finalIdx1+1; i++ {
		bl, err := dcrutil.NewBlockFromBytes(blockChain[int64(i)])
		if err != nil {
			t.Fatalf("NewBlockFromBytes error: %v", err.Error())
		}
		bl.SetHeight(int64(i))
		if i == finalIdx1 {
			oldBestHash = bl.Sha()
		}

		_, _, err = chain.ProcessBlock(bl, blockchain.BFNone)
		if err != nil {
			t.Fatalf("ProcessBlock error at height %v: %v", i, err.Error())
		}
	}

	// Load the long chain and begin loading blocks from that too,
	// forcing a reorganization
	// Load up the rest of the blocks up to HEAD.
	filename = filepath.Join("testdata/", "reorgto180.bz2")
	fi, err = os.Open(filename)
	bcStream = bzip2.NewReader(fi)
	defer fi.Close()

	// Create a buffer of the read file
	bcBuf = new(bytes.Buffer)
	bcBuf.ReadFrom(bcStream)

	// Create decoder from the buffer and a map to store the data
	bcDecoder = gob.NewDecoder(bcBuf)
	blockChain = make(map[int64][]byte)

	// Decode the blockchain into the map
	if err := bcDecoder.Decode(&blockChain); err != nil {
		t.Errorf("error decoding test blockchain: %v", err.Error())
	}

	forkPoint := int64(131)
	forkBl, err := dcrutil.NewBlockFromBytes(blockChain[forkPoint])
	if err != nil {
		t.Fatalf("NewBlockFromBytes error: %v", err.Error())
	}
	forkBl.SetHeight(forkPoint)

	_, _, err = chain.ProcessBlock(forkBl, blockchain.BFNone)
	if err != nil {
		t.Fatalf("ProcessBlock error: %v", err.Error())
	}
	newBestHash := forkBl.Sha()

	err = chain.ForceHeadReorganization(*oldBestHash, *newBestHash)
	if err != nil {
		t.Fatalf("failed forced reorganization: %v", err.Error())
	}

	// Ensure our blockchain is at the correct best tip for our forced
	// reorganization
	topBlock, _ := chain.GetTopBlock()
	tipHash := topBlock.Sha()
//.........這裏部分代碼省略.........
開發者ID:decred,項目名稱:dcrd,代碼行數:101,代碼來源:reorganization_test.go

示例13: TestTicketDBGeneral

func TestTicketDBGeneral(t *testing.T) {
	// Declare some useful variables.
	testBCHeight := int64(168)
	filename := filepath.Join("..", "/../blockchain/testdata", "blocks0to168.bz2")
	fi, err := os.Open(filename)
	bcStream := bzip2.NewReader(fi)
	defer fi.Close()

	// Create a buffer of the read file.
	bcBuf := new(bytes.Buffer)
	bcBuf.ReadFrom(bcStream)

	// Create decoder from the buffer and a map to store the data.
	bcDecoder := gob.NewDecoder(bcBuf)
	testBlockchainBytes := make(map[int64][]byte)

	// Decode the blockchain into the map.
	if err := bcDecoder.Decode(&testBlockchainBytes); err != nil {
		t.Errorf("error decoding test blockchain")
	}
	testBlockchain := make(map[int64]*dcrutil.Block, len(testBlockchainBytes))
	for k, v := range testBlockchainBytes {
		bl, err := dcrutil.NewBlockFromBytes(v)
		if err != nil {
			t.Fatalf("couldn't decode block")
		}

		testBlockchain[k] = bl
	}

	// Create a new database to store the accepted stake node data into.
	dbName := "ffldb_staketest"
	dbPath := filepath.Join(testDbRoot, dbName)
	_ = os.RemoveAll(dbPath)
	testDb, err := database.Create(testDbType, dbPath, 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()

	// Load the genesis block and begin testing exported functions.
	var bestNode *Node
	err = testDb.Update(func(dbTx database.Tx) error {
		var errLocal error
		bestNode, errLocal = InitDatabaseState(dbTx, simNetParams)
		if errLocal != nil {
			return errLocal
		}

		return nil
	})
	if err != nil {
		t.Fatalf(err.Error())
	}

	// Cache all of our nodes so that we can check them when we start
	// disconnecting and going backwards through the blockchain.
	nodesForward := make([]*Node, testBCHeight+1)
	loadedNodesForward := make([]*Node, testBCHeight+1)
	nodesForward[0] = bestNode
	loadedNodesForward[0] = bestNode
	err = testDb.Update(func(dbTx database.Tx) error {
		for i := int64(1); i <= testBCHeight; i++ {
			block := testBlockchain[i]
			ticketsToAdd := make([]chainhash.Hash, 0)
			if i >= simNetParams.StakeEnabledHeight {
				matureHeight := (i - int64(simNetParams.TicketMaturity))
				ticketsToAdd = ticketsInBlock(testBlockchain[matureHeight])
			}
			header := block.MsgBlock().Header
			if int(header.PoolSize) != len(bestNode.LiveTickets()) {
				t.Errorf("bad number of live tickets: want %v, got %v",
					header.PoolSize, len(bestNode.LiveTickets()))
			}
			if header.FinalState != bestNode.FinalState() {
				t.Errorf("bad final state: want %x, got %x",
					header.FinalState, bestNode.FinalState())
			}

			// In memory addition test.
			bestNode, err = bestNode.ConnectNode(header,
				ticketsSpentInBlock(block), revokedTicketsInBlock(block),
				ticketsToAdd)
			if err != nil {
				return fmt.Errorf("couldn't connect node: %v", err.Error())
			}

			// Write the new node to db.
			nodesForward[i] = bestNode
			blockSha := block.Sha()
			err := WriteConnectedBestNode(dbTx, bestNode, *blockSha)
			if err != nil {
				return fmt.Errorf("failure writing the best node: %v",
					err.Error())
			}

//.........這裏部分代碼省略.........
開發者ID:decred,項目名稱:dcrd,代碼行數:101,代碼來源:tickets_test.go

示例14: TestTicketDBLongChain

func TestTicketDBLongChain(t *testing.T) {
	// Declare some useful variables.
	testBCHeight := int64(1001)
	filename := filepath.Join("..", "/../blockchain/testdata", "testexpiry.bz2")
	fi, err := os.Open(filename)
	bcStream := bzip2.NewReader(fi)
	defer fi.Close()

	// Create a buffer of the read file.
	bcBuf := new(bytes.Buffer)
	bcBuf.ReadFrom(bcStream)

	// Create decoder from the buffer and a map to store the data.
	bcDecoder := gob.NewDecoder(bcBuf)
	testBlockchainBytes := make(map[int64][]byte)

	// Decode the blockchain into the map.
	if err := bcDecoder.Decode(&testBlockchainBytes); err != nil {
		t.Errorf("error decoding test blockchain")
	}
	testBlockchain := make(map[int64]*dcrutil.Block, len(testBlockchainBytes))
	for k, v := range testBlockchainBytes {
		bl, err := dcrutil.NewBlockFromBytes(v)
		if err != nil {
			t.Fatalf("couldn't decode block")
		}

		testBlockchain[k] = bl
	}

	// Connect to the best block (1001).
	bestNode := genesisNode(simNetParams)
	nodesForward := make([]*Node, testBCHeight+1)
	nodesForward[0] = bestNode
	for i := int64(1); i <= testBCHeight; i++ {
		block := testBlockchain[i]
		ticketsToAdd := make([]chainhash.Hash, 0)
		if i >= simNetParams.StakeEnabledHeight {
			matureHeight := (i - int64(simNetParams.TicketMaturity))
			ticketsToAdd = ticketsInBlock(testBlockchain[matureHeight])
		}
		header := block.MsgBlock().Header
		if int(header.PoolSize) != len(bestNode.LiveTickets()) {
			t.Errorf("bad number of live tickets: want %v, got %v",
				header.PoolSize, len(bestNode.LiveTickets()))
		}
		if header.FinalState != bestNode.FinalState() {
			t.Errorf("bad final state: want %x, got %x",
				header.FinalState, bestNode.FinalState())
		}

		// In memory addition test.
		bestNode, err = bestNode.ConnectNode(header,
			ticketsSpentInBlock(block), revokedTicketsInBlock(block),
			ticketsToAdd)
		if err != nil {
			t.Fatalf("couldn't connect node: %v", err.Error())
		}

		nodesForward[i] = bestNode
	}

	// Disconnect all the way back to the genesis block.
	for i := testBCHeight; i >= int64(1); i-- {
		parentBlock := testBlockchain[i-1]
		ticketsToAdd := make([]chainhash.Hash, 0)
		if i >= simNetParams.StakeEnabledHeight {
			matureHeight := (i - 1 - int64(simNetParams.TicketMaturity))
			ticketsToAdd = ticketsInBlock(testBlockchain[matureHeight])
		}
		header := parentBlock.MsgBlock().Header
		blockUndoData := nodesForward[i-1].UndoData()

		// In memory disconnection test.
		bestNode, err = bestNode.DisconnectNode(header, blockUndoData,
			ticketsToAdd, nil)
		if err != nil {
			t.Errorf(err.Error())
		}
	}

	// Test some accessory functions.
	accessoryTestNode := nodesForward[450]
	exists := accessoryTestNode.ExistsLiveTicket(accessoryTestNode.nextWinners[0])
	if !exists {
		t.Errorf("expected winner to exist in node live tickets")
	}
	missedExp := make([]chainhash.Hash, 0)
	accessoryTestNode.missedTickets.ForEach(func(k tickettreap.Key,
		v *tickettreap.Value) bool {
		if v.Expired {
			missedExp = append(missedExp, chainhash.Hash(k))
		}

		return true
	})
	revokedExp := make([]chainhash.Hash, 0)
	accessoryTestNode.revokedTickets.ForEach(func(k tickettreap.Key,
		v *tickettreap.Value) bool {
		if v.Expired {
//.........這裏部分代碼省略.........
開發者ID:decred,項目名稱:dcrd,代碼行數:101,代碼來源:tickets_test.go

示例15: TestMerkleBlock3

func TestMerkleBlock3(t *testing.T) {
	blockStr := "000000004ad131bae9cb9f74b8bcd928" +
		"a60dfe4dadabeb31b1e79403385f9ac4" +
		"ccc28b7400429e56f7df2872aaaa0c16" +
		"221cb09059bd3ea897de156ff51202ff" +
		"72b2cd8d000000000000000000000000" +
		"00000000000000000000000000000000" +
		"00000000010000000000000000000000" +
		"22000000ffff7f20002d310100000000" +
		"640000007601000063a0815601000000" +
		"00000000000000000000000000000000" +
		"00000000000000000000000000000000" +
		"00000000010100000001000000000000" +
		"00000000000000000000000000000000" +
		"00000000000000000000ffffffff00ff" +
		"ffffff0380b2e60e00000000000017a9" +
		"144fa6cbd0dbe5ec407fe4c8ad374e66" +
		"7771fa0d448700000000000000000000" +
		"226a2000000000000000000000000000" +
		"0000009e0453a6ab10610e17a7a5fadc" +
		"f6c34f002f68590000000000001976a9" +
		"141b79e6496226f89ad4e049667c1344" +
		"c16a75815188ac000000000000000001" +
		"000000000000000000000000ffffffff" +
		"04deadbeef00"

	blockBytes, err := hex.DecodeString(blockStr)
	if err != nil {
		t.Errorf("TestMerkleBlock3 DecodeString failed: %v", err)
		return
	}
	blk, err := dcrutil.NewBlockFromBytes(blockBytes)
	if err != nil {
		t.Errorf("TestMerkleBlock3 NewBlockFromBytes failed: %v", err)
		return
	}

	f := bloom.NewFilter(10, 0, 0.000001, wire.BloomUpdateAll)

	inputStr := "4797be83be7b4c4f833739c3542c2c1c403ffb01f0b721b5bc5dee3ff655a856"
	sha, err := chainhash.NewHashFromStr(inputStr)
	if err != nil {
		t.Errorf("TestMerkleBlock3 NewShaHashFromStr failed: %v", err)
		return
	}

	f.AddShaHash(sha)

	mBlock, _ := bloom.NewMerkleBlock(blk, f)

	wantStr := "0100000079cda856b143d9db2c1caff01d1aecc8630d30625d10e8b4" +
		"b8b0000000000000b50cc069d6a3e33e3ff84a5c41d9d3febe7c770fdcc" +
		"96b2c3ff60abe184f196367291b4d4c86041b8fa45d630100000001b50c" +
		"c069d6a3e33e3ff84a5c41d9d3febe7c770fdcc96b2c3ff60abe184f196" +
		"30101"
	want, err := hex.DecodeString(wantStr)
	if err != nil {
		t.Errorf("TestMerkleBlock3 DecodeString failed: %v", err)
		return
	}

	got := bytes.NewBuffer(nil)
	err = mBlock.BtcEncode(got, wire.ProtocolVersion)
	if err != nil {
		t.Errorf("TestMerkleBlock3 BtcEncode failed: %v", err)
		return
	}

	if !bytes.Equal(want, got.Bytes()) {
		t.Errorf("TestMerkleBlock3 failed merkle block comparison: "+
			"got %v want %v", got.Bytes, want)
		return
	}
}
開發者ID:alexlyp,項目名稱:dcrutil,代碼行數:74,代碼來源:merkleblock_test.go


注:本文中的github.com/decred/dcrutil.NewBlockFromBytes函數示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。