Update for recent btcutil Block.Sha API change.

This commit is contained in:
Dave Collins 2015-04-17 00:44:15 -05:00
parent 65b044eea2
commit 750d657666
15 changed files with 30 additions and 99 deletions

View File

@ -83,8 +83,7 @@ func (b *BlockChain) maybeAcceptBlock(block *btcutil.Block, flags BehaviorFlags)
} }
// Ensure chain matches up to predetermined checkpoints. // Ensure chain matches up to predetermined checkpoints.
// It's safe to ignore the error on Sha since it's already cached. blockHash := block.Sha()
blockHash, _ := block.Sha()
if !b.verifyCheckpoint(blockHeight, blockHash) { if !b.verifyCheckpoint(blockHeight, blockHash) {
str := fmt.Sprintf("block at height %d does not match "+ str := fmt.Sprintf("block at height %d does not match "+
"checkpoint hash", blockHeight) "checkpoint hash", blockHeight)

View File

@ -239,9 +239,8 @@ func (b *BlockChain) removeOrphanBlock(orphan *orphanBlock) {
b.orphanLock.Lock() b.orphanLock.Lock()
defer b.orphanLock.Unlock() defer b.orphanLock.Unlock()
// Remove the orphan block from the orphan pool. It's safe to ignore // Remove the orphan block from the orphan pool.
// the error on Sha since it's cached. orphanHash := orphan.block.Sha()
orphanHash, _ := orphan.block.Sha()
delete(b.orphans, *orphanHash) delete(b.orphans, *orphanHash)
// Remove the reference from the previous orphan index too. An indexing // Remove the reference from the previous orphan index too. An indexing
@ -251,7 +250,7 @@ func (b *BlockChain) removeOrphanBlock(orphan *orphanBlock) {
prevHash := &orphan.block.MsgBlock().Header.PrevBlock prevHash := &orphan.block.MsgBlock().Header.PrevBlock
orphans := b.prevOrphans[*prevHash] orphans := b.prevOrphans[*prevHash]
for i := 0; i < len(orphans); i++ { for i := 0; i < len(orphans); i++ {
hash, _ := orphans[i].block.Sha() hash := orphans[i].block.Sha()
if hash.IsEqual(orphanHash) { if hash.IsEqual(orphanHash) {
copy(orphans[i:], orphans[i+1:]) copy(orphans[i:], orphans[i+1:])
orphans[len(orphans)-1] = nil orphans[len(orphans)-1] = nil
@ -296,10 +295,6 @@ func (b *BlockChain) addOrphanBlock(block *btcutil.Block) {
b.oldestOrphan = nil b.oldestOrphan = nil
} }
// Get the block sha. It is safe to ignore the error here since any
// errors would've been caught prior to calling this function.
blockSha, _ := block.Sha()
// Protect concurrent access. This is intentionally done here instead // Protect concurrent access. This is intentionally done here instead
// of near the top since removeOrphanBlock does its own locking and // of near the top since removeOrphanBlock does its own locking and
// the range iterator is not invalidated by removing map entries. // the range iterator is not invalidated by removing map entries.
@ -313,7 +308,7 @@ func (b *BlockChain) addOrphanBlock(block *btcutil.Block) {
block: block, block: block,
expiration: expiration, expiration: expiration,
} }
b.orphans[*blockSha] = oBlock b.orphans[*block.Sha()] = oBlock
// Add to previous hash lookup index for faster dependency lookups. // Add to previous hash lookup index for faster dependency lookups.
prevHash := &block.MsgBlock().Header.PrevBlock prevHash := &block.MsgBlock().Header.PrevBlock
@ -951,8 +946,8 @@ func (b *BlockChain) connectBestChain(node *blockNode, block *btcutil.Block, fla
return nil return nil
} }
if fastAdd { if fastAdd {
bsha, _ := block.Sha() log.Warnf("fastAdd set in the side chain case? %v\n",
log.Warnf("fastAdd set in the side chain case? %v\n", bsha) block.Sha())
} }
// We're extending (or creating) a side chain which may or may not // We're extending (or creating) a side chain which may or may not

View File

@ -221,13 +221,8 @@ func (b *BlockChain) IsCheckpointCandidate(block *btcutil.Block) (bool, error) {
return false, fmt.Errorf("checkpoints are disabled") return false, fmt.Errorf("checkpoints are disabled")
} }
blockHash, err := block.Sha()
if err != nil {
return false, err
}
// A checkpoint must be in the main chain. // A checkpoint must be in the main chain.
exists, err := b.db.ExistsSha(blockHash) exists, err := b.db.ExistsSha(block.Sha())
if err != nil { if err != nil {
return false, err return false, err
} }

View File

@ -85,9 +85,7 @@ func (b *BlockChain) processOrphans(hash *wire.ShaHash, flags BehaviorFlags) err
} }
// Remove the orphan from the orphan pool. // Remove the orphan from the orphan pool.
// It's safe to ignore the error on Sha since the hash orphanHash := orphan.block.Sha()
// is already cached.
orphanHash, _ := orphan.block.Sha()
b.removeOrphanBlock(orphan) b.removeOrphanBlock(orphan)
i-- i--
@ -118,10 +116,7 @@ func (b *BlockChain) ProcessBlock(block *btcutil.Block, timeSource MedianTimeSou
fastAdd := flags&BFFastAdd == BFFastAdd fastAdd := flags&BFFastAdd == BFFastAdd
dryRun := flags&BFDryRun == BFDryRun dryRun := flags&BFDryRun == BFDryRun
blockHash, err := block.Sha() blockHash := block.Sha()
if err != nil {
return false, err
}
log.Tracef("Processing block %v", blockHash) log.Tracef("Processing block %v", blockHash)
// The block must not already exist in the main chain or side chains. // The block must not already exist in the main chain or side chains.

View File

@ -328,11 +328,7 @@ func checkProofOfWork(block *btcutil.Block, powLimit *big.Int, flags BehaviorFla
// to avoid proof of work checks is set. // to avoid proof of work checks is set.
if flags&BFNoPoWCheck != BFNoPoWCheck { if flags&BFNoPoWCheck != BFNoPoWCheck {
// The block hash must be less than the claimed target. // The block hash must be less than the claimed target.
blockHash, err := block.Sha() hashNum := ShaHashToBig(block.Sha())
if err != nil {
return err
}
hashNum := ShaHashToBig(blockHash)
if hashNum.Cmp(target) > 0 { if hashNum.Cmp(target) > 0 {
str := fmt.Sprintf("block hash of %064x is higher than "+ str := fmt.Sprintf("block hash of %064x is higher than "+
"expected max of %064x", hashNum, target) "expected max of %064x", hashNum, target)
@ -1002,8 +998,8 @@ func (b *BlockChain) checkConnectBlock(node *blockNode, block *btcutil.Block) er
// This function is NOT safe for concurrent access. // This function is NOT safe for concurrent access.
func (b *BlockChain) CheckConnectBlock(block *btcutil.Block) error { func (b *BlockChain) CheckConnectBlock(block *btcutil.Block) error {
prevNode := b.bestChain prevNode := b.bestChain
blockSha, _ := block.Sha() newNode := newBlockNode(&block.MsgBlock().Header, block.Sha(),
newNode := newBlockNode(&block.MsgBlock().Header, blockSha, block.Height()) block.Height())
if prevNode != nil { if prevNode != nil {
newNode.parent = prevNode newNode.parent = prevNode
newNode.workSum.Add(prevNode.workSum, newNode.workSum) newNode.workSum.Add(prevNode.workSum, newNode.workSum)

View File

@ -531,7 +531,7 @@ func (b *blockManager) current() bool {
// handleBlockMsg handles block messages from all peers. // handleBlockMsg handles block messages from all peers.
func (b *blockManager) handleBlockMsg(bmsg *blockMsg) { func (b *blockManager) handleBlockMsg(bmsg *blockMsg) {
// If we didn't ask for this block then the peer is misbehaving. // If we didn't ask for this block then the peer is misbehaving.
blockSha, _ := bmsg.block.Sha() blockSha := bmsg.block.Sha()
if _, ok := bmsg.peer.requestedBlocks[*blockSha]; !ok { if _, ok := bmsg.peer.requestedBlocks[*blockSha]; !ok {
// The regression test intentionally sends some blocks twice // The regression test intentionally sends some blocks twice
// to test duplicate block insertion fails. Don't disconnect // to test duplicate block insertion fails. Don't disconnect
@ -1193,12 +1193,8 @@ func (b *blockManager) handleNotifyMsg(notification *blockchain.Notification) {
break break
} }
// It's ok to ignore the error here since the notification is
// coming from the chain code which has already cached the hash.
hash, _ := block.Sha()
// Generate the inventory vector and relay it. // Generate the inventory vector and relay it.
iv := wire.NewInvVect(wire.InvTypeBlock, hash) iv := wire.NewInvVect(wire.InvTypeBlock, block.Sha())
b.server.RelayInventory(iv, nil) b.server.RelayInventory(iv, nil)
// A block has been connected to the main block chain. // A block has been connected to the main block chain.

View File

@ -368,7 +368,7 @@ out:
for { for {
select { select {
case nextWrite := <-minHeightWrite: case nextWrite := <-minHeightWrite:
sha, _ := nextWrite.blk.Sha() // Can never fail. sha := nextWrite.blk.Sha()
height := nextWrite.blk.Height() height := nextWrite.blk.Height()
err := a.server.db.UpdateAddrIndexForBlock(sha, height, err := a.server.db.UpdateAddrIndexForBlock(sha, height,
nextWrite.addrIndex) nextWrite.addrIndex)

View File

@ -99,16 +99,12 @@ func (bi *blockImporter) processBlock(serializedBlock []byte) (bool, error) {
return false, err return false, err
} }
blockSha, err := block.Sha()
if err != nil {
return false, err
}
// update progress statistics // update progress statistics
bi.lastBlockTime = block.MsgBlock().Header.Timestamp bi.lastBlockTime = block.MsgBlock().Header.Timestamp
bi.receivedLogTx += int64(len(block.MsgBlock().Transactions)) bi.receivedLogTx += int64(len(block.MsgBlock().Transactions))
// Skip blocks that already exist. // Skip blocks that already exist.
blockSha := block.Sha()
exists, err := bi.db.ExistsSha(blockSha) exists, err := bi.db.ExistsSha(blockSha)
if err != nil { if err != nil {
return false, err return false, err

View File

@ -95,13 +95,9 @@ func findCandidates(db database.Db, latestHash *wire.ShaHash) ([]*chaincfg.Check
// All checks passed, so this node seems like a reasonable // All checks passed, so this node seems like a reasonable
// checkpoint candidate. // checkpoint candidate.
if isCandidate { if isCandidate {
candidateHash, err := block.Sha()
if err != nil {
return nil, err
}
checkpoint := chaincfg.Checkpoint{ checkpoint := chaincfg.Checkpoint{
Height: block.Height(), Height: block.Height(),
Hash: candidateHash, Hash: block.Sha(),
} }
candidates = append(candidates, &checkpoint) candidates = append(candidates, &checkpoint)
} }

View File

@ -148,10 +148,9 @@ func (m *CPUMiner) submitBlock(block *btcutil.Block) bool {
} }
// The block was accepted. // The block was accepted.
blockSha, _ := block.Sha()
coinbaseTx := block.MsgBlock().Transactions[0].TxOut[0] coinbaseTx := block.MsgBlock().Transactions[0].TxOut[0]
minrLog.Infof("Block submitted via CPU miner accepted (hash %s, "+ minrLog.Infof("Block submitted via CPU miner accepted (hash %s, "+
"amount %v)", blockSha, btcutil.Amount(coinbaseTx.Value)) "amount %v)", block.Sha(), btcutil.Amount(coinbaseTx.Value))
return true return true
} }

View File

@ -372,11 +372,7 @@ func (db *LevelDb) InsertBlock(block *btcutil.Block) (height int64, rerr error)
} }
}() }()
blocksha, err := block.Sha() blocksha := block.Sha()
if err != nil {
log.Warnf("Failed to compute block sha %v", blocksha)
return 0, err
}
mblock := block.MsgBlock() mblock := block.MsgBlock()
rawMsg, err := block.Bytes() rawMsg, err := block.Bytes()
if err != nil { if err != nil {

View File

@ -537,11 +537,6 @@ func (db *MemDb) InsertBlock(block *btcutil.Block) (int64, error) {
return 0, ErrDbClosed return 0, ErrDbClosed
} }
blockHash, err := block.Sha()
if err != nil {
return 0, err
}
// Reject the insert if the previously reference block does not exist // Reject the insert if the previously reference block does not exist
// except in the case there are no blocks inserted yet where the first // except in the case there are no blocks inserted yet where the first
// inserted block is assumed to be a genesis block. // inserted block is assumed to be a genesis block.
@ -640,7 +635,7 @@ func (db *MemDb) InsertBlock(block *btcutil.Block) (int64, error) {
} }
db.blocks = append(db.blocks, msgBlock) db.blocks = append(db.blocks, msgBlock)
db.blocksBySha[*blockHash] = newHeight db.blocksBySha[*block.Sha()] = newHeight
// Insert information about eacj transaction and spend all of the // Insert information about eacj transaction and spend all of the
// outputs referenced by the inputs to the transactions. // outputs referenced by the inputs to the transactions.

View File

@ -822,12 +822,7 @@ func (p *peer) handleBlockMsg(msg *wire.MsgBlock, buf []byte) {
block := btcutil.NewBlockFromBlockAndBytes(msg, buf) block := btcutil.NewBlockFromBlockAndBytes(msg, buf)
// Add the block to the known inventory for the peer. // Add the block to the known inventory for the peer.
hash, err := block.Sha() iv := wire.NewInvVect(wire.InvTypeBlock, block.Sha())
if err != nil {
peerLog.Errorf("Unable to get block hash: %v", err)
return
}
iv := wire.NewInvVect(wire.InvTypeBlock, hash)
p.AddKnownInventory(iv) p.AddKnownInventory(iv)
// Queue the block up to be handled by the block // Queue the block up to be handled by the block

View File

@ -2608,8 +2608,7 @@ func handleGetWorkSubmission(s *rpcServer, hexData string) (interface{}, error)
} }
// The block was accepted. // The block was accepted.
blockSha, _ := block.Sha() rpcsLog.Infof("Block submitted via getwork accepted: %s", block.Sha())
rpcsLog.Infof("Block submitted via getwork accepted: %s", blockSha)
return true, nil return true, nil
} }
@ -2837,7 +2836,7 @@ func handleSearchRawTransactions(s *rpcServer, cmd interface{}, closeChan <-chan
var blkHash *wire.ShaHash var blkHash *wire.ShaHash
if blk != nil { if blk != nil {
blkHash, _ = blk.Sha() blkHash = blk.Sha()
} }
rawTxn, err := createTxRawResult(s.server.chainParams, rawTxn, err := createTxRawResult(s.server.chainParams,
@ -2970,10 +2969,7 @@ func handleSubmitBlock(s *rpcServer, cmd interface{}, closeChan <-chan struct{})
return fmt.Sprintf("rejected: %s", err.Error()), nil return fmt.Sprintf("rejected: %s", err.Error()), nil
} }
blockSha, err := block.Sha() rpcsLog.Infof("Accepted block %s via submitblock", block.Sha())
if err == nil {
rpcsLog.Infof("Accepted block %s via submitblock", blockSha)
}
return nil, nil return nil, nil
} }

View File

@ -406,14 +406,9 @@ func (m *wsNotificationManager) UnregisterBlockUpdates(wsc *wsClient) {
func (*wsNotificationManager) notifyBlockConnected(clients map[chan struct{}]*wsClient, func (*wsNotificationManager) notifyBlockConnected(clients map[chan struct{}]*wsClient,
block *btcutil.Block) { block *btcutil.Block) {
hash, err := block.Sha()
if err != nil {
rpcsLog.Error("Bad block; connected block notification dropped")
return
}
// Notify interested websocket clients about the connected block. // Notify interested websocket clients about the connected block.
ntfn := btcjson.NewBlockConnectedNtfn(hash.String(), int32(block.Height())) ntfn := btcjson.NewBlockConnectedNtfn(block.Sha().String(),
int32(block.Height()))
marshalledJSON, err := btcjson.MarshalCmd(nil, ntfn) marshalledJSON, err := btcjson.MarshalCmd(nil, ntfn)
if err != nil { if err != nil {
rpcsLog.Error("Failed to marshal block connected notification: "+ rpcsLog.Error("Failed to marshal block connected notification: "+
@ -435,15 +430,8 @@ func (*wsNotificationManager) notifyBlockDisconnected(clients map[chan struct{}]
return return
} }
hash, err := block.Sha()
if err != nil {
rpcsLog.Error("Bad block; disconnected block notification " +
"dropped")
return
}
// Notify interested websocket clients about the disconnected block. // Notify interested websocket clients about the disconnected block.
ntfn := btcjson.NewBlockDisconnectedNtfn(hash.String(), ntfn := btcjson.NewBlockDisconnectedNtfn(block.Sha().String(),
int32(block.Height())) int32(block.Height()))
marshalledJSON, err := btcjson.MarshalCmd(nil, ntfn) marshalledJSON, err := btcjson.MarshalCmd(nil, ntfn)
if err != nil { if err != nil {
@ -600,10 +588,9 @@ func blockDetails(block *btcutil.Block, txIndex int) *btcjson.BlockDetails {
if block == nil { if block == nil {
return nil return nil
} }
blockSha, _ := block.Sha() // never errors
return &btcjson.BlockDetails{ return &btcjson.BlockDetails{
Height: int32(block.Height()), Height: int32(block.Height()),
Hash: blockSha.String(), Hash: block.Sha().String(),
Index: txIndex, Index: txIndex,
Time: block.MsgBlock().Header.Timestamp.Unix(), Time: block.MsgBlock().Header.Timestamp.Unix(),
} }
@ -1983,12 +1970,7 @@ fetchRange:
default: default:
rescanBlock(wsc, &lookups, blk) rescanBlock(wsc, &lookups, blk)
lastBlock = blk lastBlock = blk
lastBlockHash, err = blk.Sha() lastBlockHash = blk.Sha()
if err != nil {
context := "Failed to create block hash"
return nil, internalRPCError(err.Error(),
context)
}
} }
// Periodically notify the client of the progress // Periodically notify the client of the progress