本文整理汇总了Golang中github.com/conformal/btcutil.NewBlock函数的典型用法代码示例。如果您正苦于以下问题:Golang NewBlock函数的具体用法?Golang NewBlock怎么用?Golang NewBlock使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了NewBlock函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Golang代码示例。
示例1: Receive
// Receive waits for the response promised by the future and returns the raw
// block requested from the server given its hash.
func (r FutureGetBlockResult) Receive() (*btcutil.Block, error) {
res, err := receiveFuture(r)
if err != nil {
return nil, err
}
// Unmarshal result as a string.
var blockHex string
err = json.Unmarshal(res, &blockHex)
if err != nil {
return nil, err
}
// Decode the serialized block hex to raw bytes.
serializedBlock, err := hex.DecodeString(blockHex)
if err != nil {
return nil, err
}
// Deserialize the block and return it.
var msgBlock btcwire.MsgBlock
msgBlock.Deserialize(bytes.NewReader(serializedBlock))
if err != nil {
return nil, err
}
return btcutil.NewBlock(&msgBlock), nil
}
开发者ID:awt,项目名称:btcrpcclient,代码行数:29,代码来源:chain.go
示例2: Receive
// Receive waits for the response promised by the future and returns the raw
// block requested from the server given its hash.
func (r FutureGetBlockResult) Receive() (*btcutil.Block, error) {
reply, err := receiveFuture(r)
if err != nil {
return nil, err
}
// Ensure the returned data is the expected type.
blockHex, ok := reply.(string)
if !ok {
return nil, fmt.Errorf("unexpected response type for "+
"getblock (verbose=0): %T\n", reply)
}
// Decode the serialized block hex to raw bytes.
serializedBlock, err := hex.DecodeString(blockHex)
if err != nil {
return nil, err
}
// Deserialize the block and return it.
var msgBlock btcwire.MsgBlock
msgBlock.Deserialize(bytes.NewReader(serializedBlock))
if err != nil {
return nil, err
}
return btcutil.NewBlock(&msgBlock), nil
}
开发者ID:GeertJohan,项目名称:btcrpcclient,代码行数:29,代码来源:chain.go
示例3: loadBlockDB
// loadBlockDB opens the block database and returns a handle to it.
func loadBlockDB() (btcdb.Db, error) {
db, err := setupBlockDB()
if err != nil {
return nil, err
}
// Get the latest block height from the database.
_, height, err := db.NewestSha()
if err != nil {
db.Close()
return nil, err
}
// Insert the appropriate genesis block for the bitcoin network being
// connected to if needed.
if height == -1 {
genesis := btcutil.NewBlock(activeNetParams.GenesisBlock)
_, err := db.InsertBlock(genesis)
if err != nil {
db.Close()
return nil, err
}
btcdLog.Infof("Inserted genesis block %v",
activeNetParams.GenesisHash)
height = 0
}
btcdLog.Infof("Block database loaded with block height %d", height)
return db, nil
}
开发者ID:RagnarDanneskjold,项目名称:btcd,代码行数:31,代码来源:blockmanager.go
示例4: ExampleCreateDB
// This example demonstrates creating a new database and inserting the genesis
// block into it.
func ExampleCreateDB() {
// Notice in these example imports that the memdb driver is loaded.
// Ordinarily this would be whatever driver(s) your application
// requires.
// import (
// "github.com/conformal/btcdb"
// _ "github.com/conformal/btcdb/memdb"
// )
// Create a database and schedule it to be closed on exit. This example
// uses a memory-only database to avoid needing to write anything to
// the disk. Typically, you would specify a persistent database driver
// such as "leveldb" and give it a database name as the second
// parameter.
db, err := btcdb.CreateDB("memdb")
if err != nil {
fmt.Println(err)
return
}
defer db.Close()
// Insert the main network genesis block.
genesis := btcutil.NewBlock(btcnet.MainNetParams.GenesisBlock)
newHeight, err := db.InsertBlock(genesis)
if err != nil {
fmt.Println(err)
return
}
fmt.Println("New height:", newHeight)
// Output:
// New height: 0
}
开发者ID:kac-,项目名称:btcdb,代码行数:36,代码来源:example_test.go
示例5: generateBlocks
// generateBlocks is a worker that is controlled by the miningWorkerController.
// It is self contained in that it creates block templates and attempts to solve
// them while detecting when it is performing stale work and reacting
// accordingly by generating a new block template. When a block is solved, it
// is submitted.
//
// It must be run as a goroutine.
func (m *CPUMiner) generateBlocks(quit chan struct{}) {
minrLog.Tracef("Starting generate blocks worker")
// Start a ticker which is used to signal checks for stale work and
// updates to the speed monitor.
ticker := time.NewTicker(time.Second * hashUpdateSecs)
out:
for {
// Quit when the miner is stopped.
select {
case <-quit:
break out
default:
// Non-blocking select to fall through
}
// No point in searching for a solution before the chain is
// synced. Also, grab the same lock as used for block
// submission, since the current block will be changing and
// this would otherwise end up building a new block template on
// a block that is in the process of becoming stale.
m.submitBlockLock.Lock()
_, curHeight := m.server.blockManager.chainState.Best()
if curHeight != 0 && !m.server.blockManager.IsCurrent() {
m.submitBlockLock.Unlock()
time.Sleep(time.Second)
continue
}
// Choose a payment address at random.
rand.Seed(time.Now().UnixNano())
payToAddr := cfg.miningAddrs[rand.Intn(len(cfg.miningAddrs))]
// Create a new block template using the available transactions
// in the memory pool as a source of transactions to potentially
// include in the block.
template, err := NewBlockTemplate(payToAddr, m.server.txMemPool)
m.submitBlockLock.Unlock()
if err != nil {
errStr := fmt.Sprintf("Failed to create new block "+
"template: %v", err)
minrLog.Errorf(errStr)
continue
}
// Attempt to solve the block. The function will exit early
// with false when conditions that trigger a stale block, so
// a new block template can be generated. When the return is
// true a solution was found, so submit the solved block.
if m.solveBlock(template.block, curHeight+1, ticker, quit) {
block := btcutil.NewBlock(template.block)
m.submitBlock(block)
}
}
ticker.Stop()
m.workerWg.Done()
minrLog.Tracef("Generate blocks worker done")
}
开发者ID:nixoid,项目名称:btcd,代码行数:66,代码来源:cpuminer.go
示例6: TestCheckBlockSanity
func TestCheckBlockSanity(t *testing.T) {
powLimit := btcchain.ChainParams(btcwire.MainNet).PowLimit
block := btcutil.NewBlock(&Block100000)
err := btcchain.CheckBlockSanity(block, powLimit)
if err != nil {
t.Errorf("CheckBlockSanity: %v", err)
}
}
开发者ID:hsk81,项目名称:btcchain,代码行数:8,代码来源:validate_test.go
示例7: loadBlockDB
// loadBlockDB opens the block database and returns a handle to it.
func loadBlockDB() (btcdb.Db, error) {
// The database name is based on the database type.
dbName := blockDbNamePrefix + "_" + cfg.DbType
if cfg.DbType == "sqlite" {
dbName = dbName + ".db"
}
dbPath := filepath.Join(cfg.DataDir, dbName)
// The regression test is special in that it needs a clean database for
// each run, so remove it now if it already exists.
removeRegressionDB(dbPath)
log.Infof("[BMGR] Loading block database from '%s'", dbPath)
db, err := btcdb.OpenDB(cfg.DbType, dbPath)
if err != nil {
// Return the error if it's not because the database doesn't
// exist.
if err != btcdb.DbDoesNotExist {
return nil, err
}
// Create the db if it does not exist.
err = os.MkdirAll(cfg.DataDir, 0700)
if err != nil {
return nil, err
}
db, err = btcdb.CreateDB(cfg.DbType, dbPath)
if err != nil {
return nil, err
}
}
// Get the latest block height from the database.
_, height, err := db.NewestSha()
if err != nil {
db.Close()
return nil, err
}
// Insert the appropriate genesis block for the bitcoin network being
// connected to if needed.
if height == -1 {
genesis := btcutil.NewBlock(activeNetParams.genesisBlock)
_, err := db.InsertBlock(genesis)
if err != nil {
db.Close()
return nil, err
}
log.Infof("[BMGR] Inserted genesis block %v",
activeNetParams.genesisHash)
height = 0
}
log.Infof("[BMGR] Block database loaded with block height %d", height)
return db, nil
}
开发者ID:kazcw,项目名称:btcd,代码行数:57,代码来源:blockmanager.go
示例8: TestMerkle
// TestMerkle tests the BuildMerkleTreeStore API.
func TestMerkle(t *testing.T) {
block := btcutil.NewBlock(&Block100000)
merkles := btcchain.BuildMerkleTreeStore(block)
calculatedMerkleRoot := merkles[len(merkles)-1]
wantMerkle := &Block100000.Header.MerkleRoot
if !wantMerkle.IsEqual(calculatedMerkleRoot) {
t.Errorf("BuildMerkleTreeStore: merkle root mismatch - "+
"got %v, want %v", calculatedMerkleRoot, wantMerkle)
}
}
开发者ID:hsk81,项目名称:btcchain,代码行数:11,代码来源:merkle_test.go
示例9: exampleLoadDB
// exampleLoadDB is used in the example to elide the setup code.
func exampleLoadDB() (btcdb.Db, error) {
db, err := btcdb.CreateDB("memdb")
if err != nil {
return nil, err
}
// Insert the main network genesis block.
genesis := btcutil.NewBlock(btcnet.MainNetParams.GenesisBlock)
_, err = db.InsertBlock(genesis)
if err != nil {
return nil, err
}
return db, err
}
开发者ID:kac-,项目名称:btcdb,代码行数:16,代码来源:example_test.go
示例10: FetchBlockBySha
// FetchBlockBySha returns a btcutil.Block. The implementation may cache the
// underlying data if desired. This is part of the btcdb.Db interface
// implementation.
//
// This implementation does not use any additional cache since the entire
// database is already in memory.
func (db *MemDb) FetchBlockBySha(sha *btcwire.ShaHash) (*btcutil.Block, error) {
db.Lock()
defer db.Unlock()
if db.closed {
return nil, ErrDbClosed
}
if blockHeight, exists := db.blocksBySha[*sha]; exists {
block := btcutil.NewBlock(db.blocks[int(blockHeight)])
block.SetHeight(blockHeight)
return block, nil
}
return nil, fmt.Errorf("block %v is not in database", sha)
}
开发者ID:stoiclabs,项目名称:blockchainr,代码行数:22,代码来源:memdb.go
示例11: TestCheckBlockSanity
func TestCheckBlockSanity(t *testing.T) {
powLimit := btcnet.MainNetParams.PowLimit
block := btcutil.NewBlock(&Block100000)
err := btcchain.CheckBlockSanity(block, powLimit)
if err != nil {
t.Errorf("CheckBlockSanity: %v", err)
}
// Ensure a block that has a timestamp with a precision higher than one
// second fails.
timestamp := block.MsgBlock().Header.Timestamp
block.MsgBlock().Header.Timestamp = timestamp.Add(time.Nanosecond)
err = btcchain.CheckBlockSanity(block, powLimit)
if err == nil {
t.Errorf("CheckBlockSanity: error is nil when it shouldn't be")
}
}
开发者ID:stoiclabs,项目名称:blockchainr,代码行数:17,代码来源:validate_test.go
示例12: setupDB
// setupDB is used to create a new db instance with the genesis block already
// inserted. In addition to the new db instance, it returns a teardown function
// the caller should invoke when done testing to clean up.
func setupDB(dbType, dbName string) (btcdb.Db, func(), error) {
db, teardown, err := createDB(dbType, dbName, true)
if err != nil {
return nil, nil, err
}
// Insert the main network genesis block. This is part of the initial
// database setup.
genesisBlock := btcutil.NewBlock(&btcwire.GenesisBlock)
_, err = db.InsertBlock(genesisBlock)
if err != nil {
teardown()
err := fmt.Errorf("failed to insert genesis block: %v", err)
return nil, nil, err
}
return db, teardown, nil
}
开发者ID:hsk81,项目名称:btcdb,代码行数:21,代码来源:common_test.go
示例13: UpdateExtraNonce
// UpdateExtraNonce updates the extra nonce in the coinbase script of the passed
// block by regenerating the coinbase script with the passed value and block
// height. It also recalculates and updates the new merkle root that results
// from changing the coinbase script.
func UpdateExtraNonce(msgBlock *btcwire.MsgBlock, blockHeight int64, extraNonce uint64) error {
coinbaseScript := standardCoinbaseScript(blockHeight, extraNonce)
if len(coinbaseScript) > btcchain.MaxCoinbaseScriptLen {
return fmt.Errorf("coinbase transaction script length "+
"of %d is out of range (min: %d, max: %d)",
len(coinbaseScript), btcchain.MinCoinbaseScriptLen,
btcchain.MaxCoinbaseScriptLen)
}
msgBlock.Transactions[0].TxIn[0].SignatureScript = coinbaseScript
// TODO(davec): A btcutil.Block should use saved in the state to avoid
// recalculating all of the other transaction hashes.
// block.Transactions[0].InvalidateCache()
// Recalculate the merkle root with the updated extra nonce.
block := btcutil.NewBlock(msgBlock)
merkles := btcchain.BuildMerkleTreeStore(block.Transactions())
msgBlock.Header.MerkleRoot = *merkles[len(merkles)-1]
return nil
}
开发者ID:stoiclabs,项目名称:blockchainr,代码行数:24,代码来源:mining.go
示例14: ExampleBlockChain_ProcessBlock
// This example demonstrates how to create a new chain instance and use
// ProcessBlock to attempt to attempt add a block to the chain. As the package
// overview documentation describes, this includes all of the Bitcoin consensus
// rules. This example intentionally attempts to insert a duplicate genesis
// block to illustrate how an invalid block is handled.
func ExampleBlockChain_ProcessBlock() {
// Create a new database to store the accepted blocks into. Typically
// this would be opening an existing database and would not use memdb
// which is a memory-only database backend, but we create a new db
// here so this is a complete working example.
db, err := btcdb.CreateDB("memdb")
if err != nil {
fmt.Printf("Failed to create database: %v\n", err)
return
}
defer db.Close()
// Insert the main network genesis block. This is part of the initial
// database setup. Like above, this typically would not be needed when
// opening an existing database.
genesisBlock := btcutil.NewBlock(btcnet.MainNetParams.GenesisBlock)
_, err = db.InsertBlock(genesisBlock)
if err != nil {
fmt.Printf("Failed to insert genesis block: %v\n", err)
return
}
// Create a new BlockChain instance using the underlying database for
// the main bitcoin network and ignore notifications.
chain := btcchain.New(db, &btcnet.MainNetParams, nil)
// Process a block. For this example, we are going to intentionally
// cause an error by trying to process the genesis block which already
// exists.
isOrphan, err := chain.ProcessBlock(genesisBlock, btcchain.BFNone)
if err != nil {
fmt.Printf("Failed to process block: %v\n", err)
return
}
fmt.Printf("Block accepted. Is it an orphan?: %v", isOrphan)
// Output:
// Failed to process block: already have block 000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f
}
开发者ID:stoiclabs,项目名称:blockchainr,代码行数:44,代码来源:example_test.go
示例15: TestCheckConnectBlock
// TestCheckConnectBlock tests the CheckConnectBlock function to ensure it
// fails
func TestCheckConnectBlock(t *testing.T) {
// Create a new database and chain instance to run tests against.
chain, teardownFunc, err := chainSetup("checkconnectblock")
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 := btcnet.MainNetParams.GenesisBlock
err = chain.CheckConnectBlock(btcutil.NewBlock(genesisBlock))
if err == nil {
t.Errorf("CheckConnectBlock: Did not received expected error")
}
}
开发者ID:stoiclabs,项目名称:blockchainr,代码行数:24,代码来源:validate_test.go
示例16: TestClosed
// TestClosed ensure calling the interface functions on a closed database
// returns appropriate errors for the interface functions that return errors
// and does not panic or otherwise misbehave for functions which do not return
// errors.
func TestClosed(t *testing.T) {
db, err := btcdb.CreateDB("memdb")
if err != nil {
t.Errorf("Failed to open test database %v", err)
return
}
_, err = db.InsertBlock(btcutil.NewBlock(&btcwire.GenesisBlock))
if err != nil {
t.Errorf("InsertBlock: %v", err)
}
db.Close()
genesisHash := &btcwire.GenesisHash
if err := db.DropAfterBlockBySha(genesisHash); err != memdb.ErrDbClosed {
t.Errorf("DropAfterBlockBySha: unexpected error %v", err)
}
if exists := db.ExistsSha(genesisHash); exists != false {
t.Errorf("ExistsSha: genesis hash exists after close")
}
if _, err := db.FetchBlockBySha(genesisHash); err != memdb.ErrDbClosed {
t.Errorf("FetchBlockBySha: unexpected error %v", err)
}
if _, err := db.FetchBlockShaByHeight(0); err != memdb.ErrDbClosed {
t.Errorf("FetchBlockShaByHeight: unexpected error %v", err)
}
if _, err := db.FetchHeightRange(0, 1); err != memdb.ErrDbClosed {
t.Errorf("FetchHeightRange: unexpected error %v", err)
}
genesisMerkleRoot := &btcwire.GenesisMerkleRoot
if exists := db.ExistsTxSha(genesisMerkleRoot); exists != false {
t.Errorf("ExistsTxSha: hash %v exists when it shouldn't",
genesisMerkleRoot)
}
if _, err := db.FetchTxBySha(genesisHash); err != memdb.ErrDbClosed {
t.Errorf("FetchTxBySha: unexpected error %v", err)
}
requestHashes := []*btcwire.ShaHash{genesisHash}
reply := db.FetchTxByShaList(requestHashes)
if len(reply) != len(requestHashes) {
t.Errorf("FetchUnSpentTxByShaList unexpected number of replies "+
"got: %d, want: %d", len(reply), len(requestHashes))
}
for i, txLR := range reply {
wantReply := &btcdb.TxListReply{
Sha: requestHashes[i],
Err: memdb.ErrDbClosed,
}
if !reflect.DeepEqual(wantReply, txLR) {
t.Errorf("FetchTxByShaList unexpected reply\ngot: %v\n"+
"want: %v", txLR, wantReply)
}
}
reply = db.FetchUnSpentTxByShaList(requestHashes)
if len(reply) != len(requestHashes) {
t.Errorf("FetchUnSpentTxByShaList unexpected number of replies "+
"got: %d, want: %d", len(reply), len(requestHashes))
}
for i, txLR := range reply {
wantReply := &btcdb.TxListReply{
Sha: requestHashes[i],
Err: memdb.ErrDbClosed,
}
if !reflect.DeepEqual(wantReply, txLR) {
t.Errorf("FetchUnSpentTxByShaList unexpected reply\n"+
"got: %v\nwant: %v", txLR, wantReply)
}
}
if _, _, err := db.NewestSha(); err != memdb.ErrDbClosed {
t.Errorf("NewestSha: unexpected error %v", err)
}
// The following calls don't return errors from the interface to be able
// to detect a closed database, so just call them to ensure there are no
// panics.
db.Sync()
db.RollbackClose()
}
开发者ID:hsk81,项目名称:btcdb,代码行数:90,代码来源:memdb_test.go
示例17: NewBlockTemplate
// NewBlockTemplate returns a new block template that is ready to be solved
// using the transactions from the passed transaction memory pool and a coinbase
// that either pays to the passed address if it is not nil, or a coinbase that
// is redeemable by anyone if the passed address is nil. The nil address
// functionality is useful since there are cases such as the getblocktemplate
// RPC where external mining software is responsible for creating their own
// coinbase which will replace the one generated for the block template. Thus
// the need to have configured address can be avoided.
//
// The transactions selected and included are prioritized according to several
// factors. First, each transaction has a priority calculated based on its
// value, age of inputs, and size. Transactions which consist of larger
// amounts, older inputs, and small sizes have the highest priority. Second, a
// fee per kilobyte is calculated for each transaction. Transactions with a
// higher fee per kilobyte are preferred. Finally, the block generation related
// configuration options are all taken into account.
//
// Transactions which only spend outputs from other transactions already in the
// block chain are immediately added to a priority queue which either
// prioritizes based on the priority (then fee per kilobyte) or the fee per
// kilobyte (then priority) depending on whether or not the BlockPrioritySize
// configuration option allots space for high-priority transactions.
// Transactions which spend outputs from other transactions in the memory pool
// are added to a dependency map so they can be added to the priority queue once
// the transactions they depend on have been included.
//
// Once the high-priority area (if configured) has been filled with transactions,
// or the priority falls below what is considered high-priority, the priority
// queue is updated to prioritize by fees per kilobyte (then priority).
//
// When the fees per kilobyte drop below the TxMinFreeFee configuration option,
// the transaction will be skipped unless there is a BlockMinSize set, in which
// case the block will be filled with the low-fee/free transactions until the
// block size reaches that minimum size.
//
// Any transactions which would cause the block to exceed the BlockMaxSize
// configuration option, exceed the maximum allowed signature operations per
// block, or otherwise cause the block to be invalid are skipped.
//
// Given the above, a block generated by this function is of the following form:
//
// ----------------------------------- -- --
// | Coinbase Transaction | | |
// |-----------------------------------| | |
// | | | | ----- cfg.BlockPrioritySize
// | High-priority Transactions | | |
// | | | |
// |-----------------------------------| | --
// | | |
// | | |
// | | |--- cfg.BlockMaxSize
// | Transactions prioritized by fee | |
// | until <= cfg.TxMinFreeFee | |
// | | |
// | | |
// | | |
// |-----------------------------------| |
// | Low-fee/Non high-priority (free) | |
// | transactions (while block size | |
// | <= cfg.BlockMinSize) | |
// ----------------------------------- --
func NewBlockTemplate(mempool *txMemPool, payToAddress btcutil.Address) (*BlockTemplate, error) {
blockManager := mempool.server.blockManager
chainState := &blockManager.chainState
chain := blockManager.blockChain
// Extend the most recently known best block.
chainState.Lock()
prevHash := chainState.newestHash
nextBlockHeight := chainState.newestHeight + 1
chainState.Unlock()
// Create a standard coinbase transaction paying to the provided
// address. NOTE: The coinbase value will be updated to include the
// fees from the selected transactions later after they have actually
// been selected. It is created here to detect any errors early
// before potentially doing a lot of work below. The extra nonce helps
// ensure the transaction is not a duplicate transaction (paying the
// same value to the same public key address would otherwise be an
// identical transaction for block version 1).
extraNonce := uint64(0)
coinbaseScript := standardCoinbaseScript(nextBlockHeight, extraNonce)
coinbaseTx, err := createCoinbaseTx(coinbaseScript, nextBlockHeight,
payToAddress)
if err != nil {
return nil, err
}
numCoinbaseSigOps := int64(btcchain.CountSigOps(coinbaseTx))
// Get the current memory pool transactions and create a priority queue
// to hold the transactions which are ready for inclusion into a block
// along with some priority related and fee metadata. Reserve the same
// number of items that are in the memory pool for the priority queue.
// Also, choose the initial sort order for the priority queue based on
// whether or not there is an area allocated for high-priority
// transactions.
mempoolTxns := mempool.TxDescs()
sortedByFee := cfg.BlockPrioritySize == 0
priorityQueue := newTxPriorityQueue(len(mempoolTxns), sortedByFee)
//.........这里部分代码省略.........
开发者ID:stoiclabs,项目名称:blockchainr,代码行数:101,代码来源:mining.go
示例18: TestBlock
// TestBlock tests the API for Block.
func TestBlock(t *testing.T) {
b := btcutil.NewBlock(&Block100000)
// Ensure we get the same data back out.
if msgBlock := b.MsgBlock(); !reflect.DeepEqual(msgBlock, &Block100000) {
t.Errorf("MsgBlock: mismatched MsgBlock - got %v, want %v",
spew.Sdump(msgBlock), spew.Sdump(&Block100000))
}
// Ensure block height set and get work properly.
wantHeight := int64(100000)
b.SetHeight(wantHeight)
if gotHeight := b.Height(); gotHeight != wantHeight {
t.Errorf("Height: mismatched height - got %v, want %v",
gotHeight, wantHeight)
}
// Hash for block 100,000.
wantShaStr := "3ba27aa200b1cecaad478d2b00432346c3f1f3986da1afd33e506"
wantSha, err := btcwire.NewShaHashFromStr(wantShaStr)
if err != nil {
t.Errorf("NewShaHashFromStr: %v", err)
}
// Request the sha multiple times to test generation and caching.
for i := 0; i < 2; i++ {
sha, err := b.Sha()
if err != nil {
t.Errorf("Sha: %v", err)
continue
}
if !sha.IsEqual(wantSha) {
t.Errorf("Sha #%d mismatched sha - got %v, want %v", i,
sha, wantSha)
}
}
// Shas for the transactions in Block100000.
wantTxShas := []string{
"8c14f0db3df150123e6f3dbbf30f8b955a8249b62ac1d1ff16284aefa3d06d87",
"fff2525b8931402dd09222c50775608f75787bd2b87e56995a7bdd30f79702c4",
"6359f0868171b1d194cbee1af2f16ea598ae8fad666d9b012c8ed2b79a236ec4",
"e9a66845e05d5abc0ad04ec80f774a7e585c6e8db975962d069a522137b80c1d",
}
// Request sha for all transactions one at a time via TxSha.
for i, txSha := range wantTxShas {
wantSha, err := btcwire.NewShaHashFromStr(txSha)
if err != nil {
t.Errorf("NewShaHashFromStr: %v", err)
}
// Request the sha multiple times to test generation and caching.
for j := 0; j < 2; j++ {
sha, err := b.TxSha(i)
if err != nil {
t.Errorf("TxSha: %v", err)
continue
}
if !sha.IsEqual(wantSha) {
t.Errorf("TxSha #%d mismatched sha - got %v, "+
"want %v", j, sha, wantSha)
continue
}
}
}
// Create a new block to nuke all cached data.
b = btcutil.NewBlock(&Block100000)
// Request sha for all transactions one at a time via Tx.
for i, txSha := range wantTxShas {
wantSha, err := btcwire.NewShaHashFromStr(txSha)
if err != nil {
t.Errorf("NewShaHashFromStr: %v", err)
}
// Request the sha multiple times to test generation and caching.
for j := 0; j < 2; j++ {
tx, err := b.Tx(i)
if err != nil {
t.Errorf("Tx #%d: %v", i, err)
continue
}
sha := tx.Sha()
if !sha.IsEqual(wantSha) {
t.Errorf("Sha #%d mismatched sha - got %v, "+
"want %v", j, sha, wantSha)
continue
}
}
}
// Create a new block to nuke all cached data.
b = btcutil.NewBlock(&Block100000)
// Request slice of all transaction shas multiple times to test
//.........这里部分代码省略.........
开发者ID:hsk81,项目名称:btcutil,代码行数:101,代码来源:block_test.go
示例19: chainSetup
// chainSetup is used to create a new db and chain instance with the genesis
// block already inserted. In addition to the new chain instnce, it returns
// a teardown function the caller should invoke when done testing to clean up.
func chainSetup(dbName string) (*btcchain.BlockChain, func(), error) {
if !isSupportedDbType(testDbType) {
return nil, nil, fmt.Errorf("unsupported db type %v", testDbType)
}
// Handle memory database specially since it doesn't need the disk
// specific handling.
var db btcdb.Db
var teardown func()
if testDbType == "memdb" {
ndb, err := btcdb.CreateDB(testDbType)
if err != nil {
return nil, nil, fmt.Errorf("error creating db: %v", err)
}
db = ndb
// Setup a teardown function for cleaning up. This function is
// returned to the caller to be invoked when it is done testing.
teardown = func() {
db.Close()
}
} else {
// Create the root directory for test databases.
if !fileExists(testDbRoot) {
if err := os.MkdirAll(testDbRoot, 0700); err != nil {
err := fmt.Errorf("unable to create test db "+
"root: %v", err)
return nil, nil, err
}
}
// Create a new database to store the accepted blocks into.
dbPath := filepath.Join(testDbRoot, dbName)
_ = os.RemoveAll(dbPath)
ndb, err := btcdb.CreateDB(testDbType, dbPath)
if err != nil {
return nil, nil, fmt.Errorf("error creating db: %v", err)
}
db = ndb
// Setup a teardown function for cleaning up. This function is
// returned to the caller to be invoked when it is done testing.
teardown = func() {
dbVersionPath := filepath.Join(testDbRoot, dbName+".ver")
db.Sync()
db.Close()
os.RemoveAll(dbPath)
os.Remove(dbVersionPath)
os.RemoveAll(testDbRoot)
}
}
// Insert the main network genesis block. This is part of the initial
// database setup.
genesisBlock := btcutil.NewBlock(&btcwire.GenesisBlock)
_, err := db.InsertBlock(genesisBlock)
if err != nil {
teardown()
err := fmt.Errorf("failed to insert genesis block: %v", err)
return nil, nil, err
}
chain := btcchain.New(db, btcwire.MainNet, nil)
return chain, teardown, nil
}
开发者ID:hsk81,项目名称:btcchain,代码行数:68,代码来源:common_test.go
示例20: TestHaveBlock
// TestHaveBlock tests the HaveBlock API to ensure proper functionality.
func TestHaveBlock(t *testing.T) {
// Load up blocks such that there is a side chain.
// (genesis block) -> 1 -> 2 -> 3 -> 4
// \-> 3a
testFiles := []string{
"blk_0_to_4.dat.bz2",
"blk_3A.dat.bz2",
}
var blocks []*btcutil.Block
for _, file := range testFiles {
blockTmp, err := loadBlocks(file)
if err != nil {
t.Errorf("Error loading file: %v\n", err)
return
}
for _, block := range blockTmp {
blocks = append(blocks, block)
}
}
// Create a new database and chain instance to run tests against.
chain, teardownFunc, err := chainSetup("haveblock")
if err != nil {
t.Errorf("Failed to setup chain instance: %v", err)
return
}
defer teardownFunc()
// Since we're not dealing with the real block chain, disable
// checkpoints and set the coinbase maturity to 1.
chain.DisableCheckpoints(true)
btcchain.TstSetCoinbaseMaturity(1)
for i := 1; i < len(blocks); i++ {
isOrphan, err := chain.ProcessBlock(blocks[i], btcchain.BFNone)
if err != nil {
t.Errorf("ProcessBlock fail on block %v: %v\n", i, err)
return
}
if isOrphan {
t.Errorf("ProcessBlock incorrectly returned block %v "+
"is an orphan\n", i)
return
}
}
// Insert an orphan block.
isOrphan, err := chain.ProcessBlock(btcutil.NewBlock(&Block100000), btcchain.BFNone)
if err != nil {
t.Errorf("Unable to process block: %v", err)
return
}
if !isOrphan {
t.Errorf("ProcessBlock indicated block is an not orphan when " +
"it should be\n")
return
}
tests := []struct {
hash string
want bool
}{
// Genesis block should be present (in the main chain).
{hash: btcnet.MainNetParams.GenesisHash.String(), want: true},
// Block 3a should be present (on a side chain).
{hash: "00000000474284d20067a4d33f6a02284e6ef70764a3a26d6a5b9df52ef663dd", want: true},
// Block 100000 should be present (as an orphan).
{hash: "000000000003ba27aa200b1cecaad478d2b00432346c3f1f3986da1afd33e506", want: true},
// Random hashes should not be availble.
{hash: "123", want: false},
}
for i, test := range tests {
hash, err := btcwire.NewShaHashFromStr(test.hash)
if err != nil {
t.Errorf("NewShaHashFromStr: %v", err)
continue
}
result, err := chain.HaveBlock(hash)
if err != nil {
t.Errorf("HaveBlock #%d unexpected error: %v", i, err)
return
}
if result != test.want {
t.Errorf("HaveBlock #%d got %v want %v", i, result,
test.want)
continue
}
}
}
开发者ID:stoiclabs,项目名称:blockchainr,代码行数:96,代码来源:chain_test.go
注:本文中的github.com/conformal/btcutil.NewBlock函数示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论