本文整理匯總了Golang中github.com/NebulousLabs/Sia/types.Block.ID方法的典型用法代碼示例。如果您正苦於以下問題:Golang Block.ID方法的具體用法?Golang Block.ID怎麽用?Golang Block.ID使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類github.com/NebulousLabs/Sia/types.Block
的用法示例。
在下文中一共展示了Block.ID方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: SubmitBlock
// SubmitBlock takes a solved block and submits it to the blockchain.
// SubmitBlock should not be called with a lock.
func (m *Miner) SubmitBlock(b types.Block) error {
// Give the block to the consensus set.
err := m.cs.AcceptBlock(b)
// Add the miner to the blocks list if the only problem is that it's stale.
if err == modules.ErrNonExtendingBlock {
m.mu.Lock()
m.blocksFound = append(m.blocksFound, b.ID())
m.mu.Unlock()
}
if err != nil {
m.tpool.PurgeTransactionPool()
m.log.Println("ERROR: an invalid block was submitted:", err)
return err
}
m.mu.Lock()
defer m.mu.Unlock()
// Grab a new address for the miner. Call may fail if the wallet is locked
// or if the wallet addresses have been exhausted.
m.blocksFound = append(m.blocksFound, b.ID())
var uc types.UnlockConditions
uc, err = m.wallet.NextAddress()
if err == nil { // Only update the address if there was no error.
m.address = uc.UnlockHash()
}
return err
}
示例2: validateHeader
// validateHeader does some early, low computation verification on the block.
// Callers should not assume that validation will happen in a particular order.
func (cs *ConsensusSet) validateHeader(tx dbTx, b types.Block) error {
// See if the block is known already.
id := b.ID()
_, exists := cs.dosBlocks[id]
if exists {
return errDoSBlock
}
// Check if the block is already known.
blockMap := tx.Bucket(BlockMap)
if blockMap == nil {
return errNoBlockMap
}
if blockMap.Get(id[:]) != nil {
return modules.ErrBlockKnown
}
// Check for the parent.
parentID := b.ParentID
parentBytes := blockMap.Get(parentID[:])
if parentBytes == nil {
return errOrphan
}
var parent processedBlock
err := cs.marshaler.Unmarshal(parentBytes, &parent)
if err != nil {
return err
}
// Check that the timestamp is not too far in the past to be acceptable.
minTimestamp := cs.blockRuleHelper.minimumValidChildTimestamp(blockMap, &parent)
return cs.blockValidator.ValidateBlock(b, minTimestamp, parent.ChildTarget, parent.Height+1)
}
示例3: newChild
// newChild creates a blockNode from a block and adds it to the parent's set of
// children. The new node is also returned. It necessairly modifies the database
//
// TODO: newChild has a fair amount of room for optimization.
func (cs *ConsensusSet) newChild(pb *processedBlock, b types.Block) *processedBlock {
// Create the child node.
childID := b.ID()
child := &processedBlock{
Block: b,
Parent: b.ParentID,
Height: pb.Height + 1,
Depth: pb.childDepth(),
}
err := cs.db.Update(func(tx *bolt.Tx) error {
blockMap := tx.Bucket(BlockMap)
err := cs.setChildTarget(blockMap, child)
if err != nil {
return err
}
pb.Children = append(pb.Children, childID)
err = blockMap.Put(child.Block.ParentID[:], encoding.Marshal(*pb))
if err != nil {
return err
}
return blockMap.Put(childID[:], encoding.Marshal(*child))
})
if build.DEBUG && err != nil {
panic(err)
}
return child
}
示例4: managedSubmitBlock
// managedSubmitBlock takes a solved block and submits it to the blockchain.
// managedSubmitBlock should not be called with a lock.
func (m *Miner) managedSubmitBlock(b types.Block) error {
// Give the block to the consensus set.
err := m.cs.AcceptBlock(b)
// Add the miner to the blocks list if the only problem is that it's stale.
if err == modules.ErrNonExtendingBlock {
m.mu.Lock()
m.persist.BlocksFound = append(m.persist.BlocksFound, b.ID())
m.mu.Unlock()
m.log.Println("Mined a stale block - block appears valid but does not extend the blockchain")
return err
}
if err == modules.ErrBlockUnsolved {
m.log.Println("Mined an unsolved block - header submission appears to be incorrect")
return err
}
if err != nil {
m.tpool.PurgeTransactionPool()
m.log.Critical("ERROR: an invalid block was submitted:", err)
return err
}
m.mu.Lock()
defer m.mu.Unlock()
// Grab a new address for the miner. Call may fail if the wallet is locked
// or if the wallet addresses have been exhausted.
m.persist.BlocksFound = append(m.persist.BlocksFound, b.ID())
var uc types.UnlockConditions
uc, err = m.wallet.NextAddress()
if err != nil {
return err
}
m.persist.Address = uc.UnlockHash()
return m.saveSync()
}
示例5: addBlockToTree
// addBlockToTree inserts a block into the blockNode tree by adding it to its
// parent's list of children. If the new blockNode is heavier than the current
// node, the blockchain is forked to put the new block and its parents at the
// tip. An error will be returned if block verification fails or if the block
// does not extend the longest fork.
func (cs *State) addBlockToTree(b types.Block) (revertedNodes, appliedNodes []*blockNode, err error) {
parentNode := cs.blockMap[b.ParentID]
newNode := parentNode.newChild(b)
cs.blockMap[b.ID()] = newNode
if newNode.heavierThan(cs.currentBlockNode()) {
return cs.forkBlockchain(newNode)
}
return nil, nil, modules.ErrNonExtendingBlock
}
示例6: SubmitHeader
// SubmitHeader accepts a block header.
func (m *Miner) SubmitHeader(bh types.BlockHeader) error {
if err := m.tg.Add(); err != nil {
return err
}
defer m.tg.Done()
// Because a call to managedSubmitBlock is required at the end of this
// function, the first part needs to be wrapped in an anonymous function
// for lock safety.
var b types.Block
err := func() error {
m.mu.Lock()
defer m.mu.Unlock()
// Lookup the block that corresponds to the provided header.
nonce := bh.Nonce
bh.Nonce = [8]byte{}
bPointer, bExists := m.blockMem[bh]
arbData, arbExists := m.arbDataMem[bh]
if !bExists || !arbExists {
return errLateHeader
}
// Block is going to be passed to external memory, but the memory pointed
// to by the transactions slice is still being modified - needs to be
// copied. Same with the memory being pointed to by the arb data slice.
b = *bPointer
txns := make([]types.Transaction, len(b.Transactions))
copy(txns, b.Transactions)
b.Transactions = txns
b.Transactions[0].ArbitraryData = [][]byte{arbData[:]}
b.Nonce = nonce
// Sanity check - block should have same id as header.
bh.Nonce = nonce
if types.BlockID(crypto.HashObject(bh)) != b.ID() {
m.log.Critical("block reconstruction failed")
}
return nil
}()
if err != nil {
m.log.Println("ERROR during call to SubmitHeader, pre SubmitBlock:", err)
return err
}
err = m.managedSubmitBlock(b)
if err != nil {
m.log.Println("ERROR returned by managedSubmitBlock:", err)
return err
}
return nil
}
示例7: TestCheckTarget
// TestCheckTarget probes the checkTarget function.
func TestCheckTarget(t *testing.T) {
var b types.Block
lowTarget := types.RootDepth
highTarget := types.Target{}
sameTarget := types.Target(b.ID())
if !checkTarget(b, lowTarget) {
t.Error("CheckTarget failed for a low target")
}
if checkTarget(b, highTarget) {
t.Error("CheckTarget passed for a high target")
}
if !checkTarget(b, sameTarget) {
t.Error("CheckTarget failed for a same target")
}
}
示例8: newChild
// newChild creates a blockNode from a block and adds it to the parent's set of
// children. The new node is also returned. It necessairly modifies the database
func (cs *ConsensusSet) newChild(tx *bolt.Tx, pb *processedBlock, b types.Block) *processedBlock {
// Create the child node.
childID := b.ID()
child := &processedBlock{
Block: b,
Height: pb.Height + 1,
Depth: pb.childDepth(),
}
blockMap := tx.Bucket(BlockMap)
cs.setChildTarget(blockMap, child)
err := blockMap.Put(childID[:], encoding.Marshal(*child))
if build.DEBUG && err != nil {
panic(err)
}
return child
}
示例9: TestBuriedBadFork
// TestBuriedBadFork creates a block with an invalid transaction that's not on
// the longest fork. The consensus set will not validate that block. Then valid
// blocks are added on top of it to make it the longest fork. When it becomes
// the longest fork, all the blocks should be fully validated and thrown out
// because a parent is invalid.
func TestBuriedBadFork(t *testing.T) {
if testing.Short() {
t.SkipNow()
}
t.Parallel()
cst, err := createConsensusSetTester("TestBuriedBadFork")
if err != nil {
t.Fatal(err)
}
defer cst.Close()
pb := cst.cs.dbCurrentProcessedBlock()
// Create a bad block that builds on a parent, so that it is part of not
// the longest fork.
badBlock := types.Block{
ParentID: pb.Block.ParentID,
Timestamp: types.CurrentTimestamp(),
MinerPayouts: []types.SiacoinOutput{{Value: types.CalculateCoinbase(pb.Height)}},
Transactions: []types.Transaction{{
SiacoinInputs: []types.SiacoinInput{{}}, // Will trigger an error on full verification but not partial verification.
}},
}
parent, err := cst.cs.dbGetBlockMap(pb.Block.ParentID)
if err != nil {
t.Fatal(err)
}
badBlock, _ = cst.miner.SolveBlock(badBlock, parent.ChildTarget)
err = cst.cs.AcceptBlock(badBlock)
if err != modules.ErrNonExtendingBlock {
t.Fatal(err)
}
// Build another bock on top of the bad block that is fully valid, this
// will cause a fork and full validation of the bad block, both the bad
// block and this block should be thrown away.
block := types.Block{
ParentID: badBlock.ID(),
Timestamp: types.CurrentTimestamp(),
MinerPayouts: []types.SiacoinOutput{{Value: types.CalculateCoinbase(pb.Height + 1)}},
}
block, _ = cst.miner.SolveBlock(block, parent.ChildTarget) // okay because the target will not change
err = cst.cs.AcceptBlock(block)
if err == nil {
t.Fatal("a bad block failed to cause an error")
}
}
示例10: SubmitBlock
// submitBlock takes a solved block and submits it to the blockchain.
// submitBlock should not be called with a lock.
func (m *Miner) SubmitBlock(b types.Block) error {
// Give the block to the consensus set.
err := m.cs.AcceptBlock(b)
if err != nil {
m.tpool.PurgeTransactionPool()
m.log.Println("ERROR: an invalid block was submitted:", err)
return err
}
// Grab a new address for the miner.
lockID := m.mu.Lock()
m.blocksFound = append(m.blocksFound, b.ID())
var addr types.UnlockHash
addr, _, err = m.wallet.CoinAddress(false) // false indicates that the address should not be visible to the user.
if err == nil { // Special case: only update the address if there was no error.
m.address = addr
}
m.mu.Unlock(lockID)
return err
}
示例11: acceptBlock
// acceptBlock is the internal consensus function for adding blocks. There is
// no block relaying. The speed of 'acceptBlock' is effected by the value of
// 'cs.verificationRigor'. If rigor is set to 'fullVerification', all of the
// transactions will be checked and verified. This is a requirement when
// receiving blocks from untrusted sources. When set to 'partialVerification',
// verification of transactions is skipped. This is acceptable when receiving
// blocks from a trust source, such as blocks that were previously verified and
// saved to disk. The value of 'cs.verificationRigor' should be set before
// 'acceptBlock' is called.
func (cs *State) acceptBlock(b types.Block) error {
// See if the block is known already.
_, exists := cs.dosBlocks[b.ID()]
if exists {
return ErrDoSBlock
}
_, exists = cs.blockMap[b.ID()]
if exists {
return ErrBlockKnown
}
// Check that the header is valid. The header is checked first because it
// is not computationally expensive to verify, but it is computationally
// expensive to create.
err := cs.validHeader(b)
if err != nil {
return err
}
// Try adding the block to the block tree. This call will perform
// verification on the block before adding the block to the block tree. An
// error is returned if verification fails or if the block does not extend
// the longest fork.
revertedNodes, appliedNodes, err := cs.addBlockToTree(b)
if err != nil {
return err
}
if len(appliedNodes) > 0 {
cs.updateSubscribers(revertedNodes, appliedNodes)
}
// Sanity check - if applied nodes is len 0, revertedNodes should also be
// len 0.
if build.DEBUG {
if len(appliedNodes) == 0 && len(revertedNodes) != 0 {
panic("appliedNodes and revertedNodes are mismatched!")
}
}
return nil
}
示例12: SubmitBlock
// submitBlock takes a solved block and submits it to the blockchain.
// submitBlock should not be called with a lock.
func (m *Miner) SubmitBlock(b types.Block) error {
// Give the block to the consensus set.
err := m.cs.AcceptBlock(b)
if err != nil {
m.tpool.PurgeTransactionPool()
m.log.Println("ERROR: an invalid block was submitted:", err)
return err
}
lockID := m.mu.Lock()
defer m.mu.Unlock(lockID)
// Grab a new address for the miner. Call may fail if the wallet is locked
// or if the wallet addresses have been exhausted.
m.blocksFound = append(m.blocksFound, b.ID())
var uc types.UnlockConditions
uc, err = m.wallet.NextAddress()
if err == nil { // Special case: only update the address if there was no error.
m.address = uc.UnlockHash()
}
return err
}
示例13: newChild
// newChild creates a blockNode from a block and adds it to the parent's set of
// children. The new node is also returned. It necessairly modifies the database
//
// TODO: newChild has a fair amount of room for optimization.
func (cs *ConsensusSet) newChild(tx *bolt.Tx, pb *processedBlock, b types.Block) (*processedBlock, error) {
// Create the child node.
childID := b.ID()
child := &processedBlock{
Block: b,
Parent: b.ParentID,
Height: pb.Height + 1,
Depth: pb.childDepth(),
}
blockMap := tx.Bucket(BlockMap)
err := cs.setChildTarget(blockMap, child)
if err != nil {
return nil, err
}
err = blockMap.Put(childID[:], encoding.Marshal(*child))
if err != nil {
return nil, err
}
return child, nil
}
示例14: buildExplorerBlock
// buildExplorerBlock takes a block and its height and uses it to construct an
// explorer block.
func (srv *Server) buildExplorerBlock(height types.BlockHeight, block types.Block) ExplorerBlock {
var mpoids []types.SiacoinOutputID
for i := range block.MinerPayouts {
mpoids = append(mpoids, block.MinerPayoutID(uint64(i)))
}
var etxns []ExplorerTransaction
for _, txn := range block.Transactions {
etxns = append(etxns, srv.buildExplorerTransaction(height, block.ID(), txn))
}
facts, exists := srv.explorer.BlockFacts(height)
if build.DEBUG && !exists {
panic("incorrect request to buildExplorerBlock - block does not exist")
}
return ExplorerBlock{
MinerPayoutIDs: mpoids,
Transactions: etxns,
RawBlock: block,
BlockFacts: facts,
}
}
示例15: SubmitHeader
// SubmitHeader accepts a block header.
func (m *Miner) SubmitHeader(bh types.BlockHeader) error {
m.mu.Lock()
// Lookup the block that corresponds to the provided header.
var b types.Block
nonce := bh.Nonce
bh.Nonce = [8]byte{}
bPointer, bExists := m.blockMem[bh]
arbData, arbExists := m.arbDataMem[bh]
if !bExists || !arbExists {
m.log.Println("ERROR:", errLateHeader)
m.mu.Unlock()
return errLateHeader
}
// Block is going to be passed to external memory, but the memory pointed
// to by the transactions slice is still being modified - needs to be
// copied. Same with the memory being pointed to by the arb data slice.
b = *bPointer
txns := make([]types.Transaction, len(b.Transactions))
copy(txns, b.Transactions)
b.Transactions = txns
b.Transactions[0].ArbitraryData = [][]byte{arbData[:]}
b.Nonce = nonce
// Sanity check - block should have same id as header.
if build.DEBUG {
bh.Nonce = nonce
if types.BlockID(crypto.HashObject(bh)) != b.ID() {
panic("block reconstruction failed")
}
}
m.mu.Unlock()
return m.SubmitBlock(b)
}