本文整理汇总了Golang中github.com/btcsuite/btcutil.NewBlock函数的典型用法代码示例。如果您正苦于以下问题:Golang NewBlock函数的具体用法?Golang NewBlock怎么用?Golang NewBlock使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了NewBlock函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Golang代码示例。
示例1: 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/btcsuite/btcd/database"
// _ "github.com/btcsuite/btcd/database/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 := database.CreateDB("memdb")
if err != nil {
fmt.Println(err)
return
}
defer db.Close()
// Insert the main network genesis block.
genesis := btcutil.NewBlock(chaincfg.MainNetParams.GenesisBlock)
newHeight, err := db.InsertBlock(genesis)
if err != nil {
fmt.Println(err)
return
}
fmt.Println("New height:", newHeight)
// Output:
// New height: 0
}
开发者ID:genecyber,项目名称:btcd,代码行数:36,代码来源:example_test.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) {
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 wire.MsgBlock
err = msgBlock.Deserialize(bytes.NewReader(serializedBlock))
if err != nil {
return nil, err
}
return btcutil.NewBlock(&msgBlock), nil
}
开发者ID:Wishing-Wall,项目名称:wishingwall,代码行数:29,代码来源:chain.go
示例3: GenerateAndSubmitBlock
// GenerateAndSubmitBlock creates a block whose contents include the passed
// transactions and submits it to the running simnet node. For generating
// blocks with only a coinbase tx, callers can simply pass nil instead of
// transactions to be mined. Additionally, a custom block version can be set by
// the caller. A blockVersion of -1 indicates that the current default block
// version should be used. An uninitialized time.Time should be used for the
// blockTime parameter if one doesn't wish to set a custom time.
//
// This function is safe for concurrent access.
func (h *Harness) GenerateAndSubmitBlock(txns []*btcutil.Tx, blockVersion int32,
blockTime time.Time) (*btcutil.Block, error) {
h.Lock()
defer h.Unlock()
if blockVersion == -1 {
blockVersion = wire.BlockVersion
}
prevBlockHash, prevBlockHeight, err := h.Node.GetBestBlock()
if err != nil {
return nil, err
}
mBlock, err := h.Node.GetBlock(prevBlockHash)
if err != nil {
return nil, err
}
prevBlock := btcutil.NewBlock(mBlock)
prevBlock.SetHeight(prevBlockHeight)
// Create a new block including the specified transactions
newBlock, err := createBlock(prevBlock, txns, blockVersion,
blockTime, h.wallet.coinbaseAddr, h.ActiveNet)
if err != nil {
return nil, err
}
// Submit the block to the simnet node.
if err := h.Node.SubmitBlock(newBlock, nil); err != nil {
return nil, err
}
return newBlock, nil
}
开发者ID:tb00,项目名称:btcd,代码行数:44,代码来源:rpc_harness.go
示例4: BenchmarkIsCoinBase
// BenchmarkIsCoinBase performs a simple benchmark against the IsCoinBase
// function.
func BenchmarkIsCoinBase(b *testing.B) {
tx, _ := btcutil.NewBlock(&Block100000).Tx(1)
b.ResetTimer()
for i := 0; i < b.N; i++ {
blockchain.IsCoinBase(tx)
}
}
开发者ID:vineventura,项目名称:btcd,代码行数:9,代码来源:bench_test.go
示例5: loadBlockDB
// loadBlockDB opens the block database and returns a handle to it.
func loadBlockDB() (database.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:jimmysong,项目名称:btcd,代码行数:31,代码来源:blockmanager.go
示例6: createBlock
// createBlock creates a new block building from the previous block.
func createBlock(prevBlock *btcutil.Block, inclusionTxs []*btcutil.Tx,
blockVersion int32, blockTime time.Time,
miningAddr btcutil.Address, net *chaincfg.Params) (*btcutil.Block, error) {
prevHash := prevBlock.Hash()
blockHeight := prevBlock.Height() + 1
// If a target block time was specified, then use that as the header's
// timestamp. Otherwise, add one second to the previous block unless
// it's the genesis block in which case use the current time.
var ts time.Time
switch {
case !blockTime.IsZero():
ts = blockTime
default:
ts = prevBlock.MsgBlock().Header.Timestamp.Add(time.Second)
}
extraNonce := uint64(0)
coinbaseScript, err := standardCoinbaseScript(blockHeight, extraNonce)
if err != nil {
return nil, err
}
coinbaseTx, err := createCoinbaseTx(coinbaseScript, blockHeight,
miningAddr, net)
if err != nil {
return nil, err
}
// Create a new block ready to be solved.
blockTxns := []*btcutil.Tx{coinbaseTx}
if inclusionTxs != nil {
blockTxns = append(blockTxns, inclusionTxs...)
}
merkles := blockchain.BuildMerkleTreeStore(blockTxns)
var block wire.MsgBlock
block.Header = wire.BlockHeader{
Version: blockVersion,
PrevBlock: *prevHash,
MerkleRoot: *merkles[len(merkles)-1],
Timestamp: ts,
Bits: net.PowLimitBits,
}
for _, tx := range blockTxns {
if err := block.AddTransaction(tx.MsgTx()); err != nil {
return nil, err
}
}
found := solveBlock(&block.Header, net.PowLimit)
if !found {
return nil, errors.New("Unable to solve block")
}
utilBlock := btcutil.NewBlock(&block)
utilBlock.SetHeight(blockHeight)
return utilBlock, nil
}
开发者ID:skycoin,项目名称:skycoin-exchange,代码行数:59,代码来源:blockgen.go
示例7: TestMerkle
// TestMerkle tests the BuildMerkleTreeStore API.
func TestMerkle(t *testing.T) {
block := btcutil.NewBlock(&Block100000)
merkles := blockchain.BuildMerkleTreeStore(block.Transactions())
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:jimmysong,项目名称:btcd,代码行数:11,代码来源:merkle_test.go
示例8: 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 be deleting
// and creating a new database like this, but it is done here so this is
// a complete working example and does not leave temporary files laying
// around.
dbPath := filepath.Join(os.TempDir(), "exampleprocessblock")
_ = os.RemoveAll(dbPath)
db, err := database.Create("ffldb", dbPath, chaincfg.MainNetParams.Net)
if err != nil {
fmt.Printf("Failed to create database: %v\n", err)
return
}
defer os.RemoveAll(dbPath)
defer db.Close()
// Create a new BlockChain instance using the underlying database for
// the main bitcoin network. This example does not demonstrate some
// of the other available configuration options such as specifying a
// notification callback and signature cache.
chain, err := blockchain.New(&blockchain.Config{
DB: db,
ChainParams: &chaincfg.MainNetParams,
})
if err != nil {
fmt.Printf("Failed to create chain instance: %v\n", err)
return
}
// Create a new median time source that is required by the upcoming
// call to ProcessBlock. Ordinarily this would also add time values
// obtained from other peers on the network so the local time is
// adjusted to be in agreement with other peers.
timeSource := blockchain.NewMedianTime()
// Process a block. For this example, we are going to intentionally
// cause an error by trying to process the genesis block which already
// exists.
genesisBlock := btcutil.NewBlock(chaincfg.MainNetParams.GenesisBlock)
isOrphan, err := chain.ProcessBlock(genesisBlock, timeSource, blockchain.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:cdecker,项目名称:btcd,代码行数:54,代码来源:example_test.go
示例9: exampleLoadDB
// exampleLoadDB is used in the example to elide the setup code.
func exampleLoadDB() (database.Db, error) {
db, err := database.CreateDB("memdb")
if err != nil {
return nil, err
}
// Insert the main network genesis block.
genesis := btcutil.NewBlock(chaincfg.MainNetParams.GenesisBlock)
_, err = db.InsertBlock(genesis)
if err != nil {
return nil, err
}
return db, err
}
开发者ID:genecyber,项目名称:btcd,代码行数:16,代码来源:example_test.go
示例10: 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()
// The genesis block should fail to connect since it's already inserted.
genesisBlock := chaincfg.MainNetParams.GenesisBlock
err = chain.CheckConnectBlock(btcutil.NewBlock(genesisBlock))
if err == nil {
t.Errorf("CheckConnectBlock: Did not received expected error")
}
}
开发者ID:cdecker,项目名称:btcd,代码行数:18,代码来源:validate_test.go
示例11: FetchBlockBySha
// FetchBlockBySha returns a btcutil.Block. The implementation may cache the
// underlying data if desired. This is part of the database.Db interface
// implementation.
//
// This implementation does not use any additional cache since the entire
// database is already in memory.
func (db *MemDb) FetchBlockBySha(sha *wire.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:Wishing-Wall,项目名称:wishingwall,代码行数:22,代码来源:memdb.go
示例12: 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 := database.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(chaincfg.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 without an initialized signature
// verification cache, using the underlying database for the main
// bitcoin network and ignore notifications.
chain := blockchain.New(db, &chaincfg.MainNetParams, nil, nil)
// Create a new median time source that is required by the upcoming
// call to ProcessBlock. Ordinarily this would also add time values
// obtained from other peers on the network so the local time is
// adjusted to be in agreement with other peers.
timeSource := blockchain.NewMedianTime()
// 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, timeSource, blockchain.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:vineventura,项目名称:btcd,代码行数:51,代码来源:example_test.go
示例13: 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) (database.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(chaincfg.MainNetParams.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:jimmysong,项目名称:btcd,代码行数:21,代码来源:common_test.go
示例14: TestCheckBlockSanity
// TestCheckBlockSanity tests the CheckBlockSanity function to ensure it works
// as expected.
func TestCheckBlockSanity(t *testing.T) {
powLimit := chaincfg.MainNetParams.PowLimit
block := btcutil.NewBlock(&Block100000)
timeSource := blockchain.NewMedianTime()
err := blockchain.CheckBlockSanity(block, powLimit, timeSource)
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 = blockchain.CheckBlockSanity(block, powLimit, timeSource)
if err == nil {
t.Errorf("CheckBlockSanity: error is nil when it shouldn't be")
}
}
开发者ID:jongillham,项目名称:btcd,代码行数:20,代码来源:validate_test.go
示例15: BenchmarkBlock
// BenchmarkBlockHeader benchmarks how long it takes to load the mainnet genesis
// block.
func BenchmarkBlock(b *testing.B) {
// Start by creating a new database and populating it with the mainnet
// genesis block.
dbPath := filepath.Join(os.TempDir(), "ffldb-benchblk")
_ = os.RemoveAll(dbPath)
db, err := database.Create("ffldb", dbPath, blockDataNet)
if err != nil {
b.Fatal(err)
}
defer os.RemoveAll(dbPath)
defer db.Close()
err = db.Update(func(tx database.Tx) error {
block := btcutil.NewBlock(chaincfg.MainNetParams.GenesisBlock)
if err := tx.StoreBlock(block); err != nil {
return err
}
return nil
})
if err != nil {
b.Fatal(err)
}
b.ReportAllocs()
b.ResetTimer()
err = db.View(func(tx database.Tx) error {
blockHash := chaincfg.MainNetParams.GenesisHash
for i := 0; i < b.N; i++ {
_, err := tx.FetchBlock(blockHash)
if err != nil {
return err
}
}
return nil
})
if err != nil {
b.Fatal(err)
}
// Don't benchmark teardown.
b.StopTimer()
}
开发者ID:rmozzela,项目名称:btcd,代码行数:43,代码来源:bench_test.go
示例16: 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 *wire.MsgBlock, blockHeight int32, extraNonce uint64) error {
coinbaseScript, err := standardCoinbaseScript(blockHeight, extraNonce)
if err != nil {
return err
}
if len(coinbaseScript) > blockchain.MaxCoinbaseScriptLen {
return fmt.Errorf("coinbase transaction script length "+
"of %d is out of range (min: %d, max: %d)",
len(coinbaseScript), blockchain.MinCoinbaseScriptLen,
blockchain.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 := blockchain.BuildMerkleTreeStore(block.Transactions())
msgBlock.Header.MerkleRoot = *merkles[len(merkles)-1]
return nil
}
开发者ID:you21979,项目名称:btcd,代码行数:27,代码来源:mining.go
示例17: 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) (*blockchain.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 database.Db
var teardown func()
if testDbType == "memdb" {
ndb, err := database.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 := database.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(chaincfg.MainNetParams.GenesisBlock)
_, err := db.InsertBlock(genesisBlock)
if err != nil {
teardown()
err := fmt.Errorf("failed to insert genesis block: %v", err)
return nil, nil, err
}
chain := blockchain.New(db, &chaincfg.MainNetParams, nil)
return chain, teardown, nil
}
开发者ID:jimmysong,项目名称:btcd,代码行数:68,代码来源:common_test.go
示例18: 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 := database.CreateDB("memdb")
if err != nil {
t.Errorf("Failed to open test database %v", err)
return
}
_, err = db.InsertBlock(btcutil.NewBlock(chaincfg.MainNetParams.GenesisBlock))
if err != nil {
t.Errorf("InsertBlock: %v", err)
}
if err := db.Close(); err != nil {
t.Errorf("Close: unexpected error %v", err)
}
genesisHash := chaincfg.MainNetParams.GenesisHash
if err := db.DropAfterBlockBySha(genesisHash); err != memdb.ErrDbClosed {
t.Errorf("DropAfterBlockBySha: unexpected error %v", err)
}
if _, err := db.ExistsSha(genesisHash); err != memdb.ErrDbClosed {
t.Errorf("ExistsSha: Unexpected error: %v", err)
}
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)
}
genesisCoinbaseTx := chaincfg.MainNetParams.GenesisBlock.Transactions[0]
coinbaseHash, err := genesisCoinbaseTx.TxSha()
if err != nil {
t.Errorf("TxSha: unexpected error %v", err)
}
if _, err := db.ExistsTxSha(&coinbaseHash); err != memdb.ErrDbClosed {
t.Errorf("ExistsTxSha: unexpected error %v", err)
}
if _, err := db.FetchTxBySha(genesisHash); err != memdb.ErrDbClosed {
t.Errorf("FetchTxBySha: unexpected error %v", err)
}
requestHashes := []*wire.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 := &database.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 := &database.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)
}
if err := db.Sync(); err != memdb.ErrDbClosed {
t.Errorf("Sync: unexpected error %v", err)
}
if err := db.RollbackClose(); err != memdb.ErrDbClosed {
t.Errorf("RollbackClose: unexpected error %v", err)
}
if err := db.Close(); err != memdb.ErrDbClosed {
t.Errorf("Close: unexpected error %v", err)
}
//.........这里部分代码省略.........
开发者ID:jimmysong,项目名称:btcd,代码行数:101,代码来源:memdb_test.go
示例19: Example_blockStorageAndRetrieval
// This example demonstrates creating a new database, using a managed read-write
// transaction to store a block, and using a managed read-only transaction to
// fetch the block.
func Example_blockStorageAndRetrieval() {
// This example assumes the ffldb driver is imported.
//
// import (
// "github.com/btcsuite/btcd/database"
// _ "github.com/btcsuite/btcd/database/ffldb"
// )
// Create a database and schedule it to be closed and removed on exit.
// Typically you wouldn't want to remove the database right away like
// this, nor put it in the temp directory, but it's done here to ensure
// the example cleans up after itself.
dbPath := filepath.Join(os.TempDir(), "exampleblkstorage")
db, err := database.Create("ffldb", dbPath, wire.MainNet)
if err != nil {
fmt.Println(err)
return
}
defer os.RemoveAll(dbPath)
defer db.Close()
// Use the Update function of the database to perform a managed
// read-write transaction and store a genesis block in the database as
// and example.
err = db.Update(func(tx database.Tx) error {
genesisBlock := chaincfg.MainNetParams.GenesisBlock
return tx.StoreBlock(btcutil.NewBlock(genesisBlock))
})
if err != nil {
fmt.Println(err)
return
}
// Use the View function of the database to perform a managed read-only
// transaction and fetch the block stored above.
var loadedBlockBytes []byte
err = db.Update(func(tx database.Tx) error {
genesisHash := chaincfg.MainNetParams.GenesisHash
blockBytes, err := tx.FetchBlock(genesisHash)
if err != nil {
return err
}
// As documented, all data fetched from the database is only
// valid during a database transaction in order to support
// zero-copy backends. Thus, make a copy of the data so it
// can be used outside of the transaction.
loadedBlockBytes = make([]byte, len(blockBytes))
copy(loadedBlockBytes, blockBytes)
return nil
})
if err != nil {
fmt.Println(err)
return
}
// Typically at this point, the block could be deserialized via the
// wire.MsgBlock.Deserialize function or used in its serialized form
// depending on need. However, for this example, just display the
// number of serialized bytes to show it was loaded as expected.
fmt.Printf("Serialized block size: %d bytes\n", len(loadedBlockBytes))
// Output:
// Serialized block size: 285 bytes
}
开发者ID:jongillham,项目名称:btcd,代码行数:68,代码来源:example_test.go
示例20: GenerateNBlocks
// GenerateNBlocks generates the requested number of blocks. 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.
// The function returns a list of the hashes of generated blocks.
func (m *CPUMiner) GenerateNBlocks(n uint32) ([]*wire.ShaHash, error) {
m.Lock()
// Respond with an error if there's virtually 0 chance of CPU-mining a block.
if !m.server.chainParams.GenerateSupported {
m.Unlock()
return nil, errors.New("No support for `generate` on the current " +
"network, " + m.server.chainParams.Net.String() +
", as it's unlikely to be possible to CPU-mine a block.")
}
// Respond with an error if server is already mining.
if m.started || m.discreteMining {
m.Unlock()
return nil, errors.New("Server is already CPU mining. Please call " +
"`setgenerate 0` before calling discrete `generate` commands.")
}
m.started = true
m.discreteMining = true
m.speedMonitorQuit = make(chan struct{})
m.wg.Add(1)
go m.speedMonitor()
m.Unlock()
minrLog.Tracef("Generating %d blocks", n)
i := uint32(0)
blockHashes := make([]*wire.ShaHash, n, n)
// Start a ticker which is used to signal checks for stale work and
// updates to the speed monitor.
ticker := time.NewTicker(time.Second * hashUpdateSecs)
defer ticker.Stop()
for {
// Read updateNumWorkers in case someone tries a `setgenerate` while
// we're generating. We can ignore it as the `generate` RPC call only
// uses 1 worker.
select {
case <-m.updateNumWorkers:
default:
}
// Grab the lock 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()
// 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(m.policy, m.server, payToAddr)
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, nil) {
block := btcutil.NewBlock(template.Block)
m.submitBlock(block)
blockHashes[i] = block.Sha()
i++
if i == n {
minrLog.Tracef("Generated %d blocks", i)
m.Lock()
close(m.speedMonitorQuit)
m.wg.Wait()
m.started = false
m.discreteMining = false
m.Unlock()
return blockHashes, nil
}
}
}
}
开发者ID:wallclockbuilder,项目名称:btcd,代码行数:95,代码来源:cpuminer.go
注:本文中的github.com/btcsuite/btcutil.NewBlock函数示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论