diff --git a/blockchain/accept.go b/blockchain/accept.go index cdd7b110c..16e66153b 100644 --- a/blockchain/accept.go +++ b/blockchain/accept.go @@ -83,8 +83,7 @@ func (b *BlockChain) maybeAcceptBlock(block *btcutil.Block, flags BehaviorFlags) } // 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) { str := fmt.Sprintf("block at height %d does not match "+ "checkpoint hash", blockHeight) diff --git a/blockchain/chain.go b/blockchain/chain.go index 6d1111c42..bfc93472e 100644 --- a/blockchain/chain.go +++ b/blockchain/chain.go @@ -239,9 +239,8 @@ func (b *BlockChain) removeOrphanBlock(orphan *orphanBlock) { b.orphanLock.Lock() defer b.orphanLock.Unlock() - // Remove the orphan block from the orphan pool. It's safe to ignore - // the error on Sha since it's cached. - orphanHash, _ := orphan.block.Sha() + // Remove the orphan block from the orphan pool. + orphanHash := orphan.block.Sha() delete(b.orphans, *orphanHash) // 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 orphans := b.prevOrphans[*prevHash] for i := 0; i < len(orphans); i++ { - hash, _ := orphans[i].block.Sha() + hash := orphans[i].block.Sha() if hash.IsEqual(orphanHash) { copy(orphans[i:], orphans[i+1:]) orphans[len(orphans)-1] = nil @@ -296,10 +295,6 @@ func (b *BlockChain) addOrphanBlock(block *btcutil.Block) { 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 // of near the top since removeOrphanBlock does its own locking and // the range iterator is not invalidated by removing map entries. @@ -313,7 +308,7 @@ func (b *BlockChain) addOrphanBlock(block *btcutil.Block) { block: block, expiration: expiration, } - b.orphans[*blockSha] = oBlock + b.orphans[*block.Sha()] = oBlock // Add to previous hash lookup index for faster dependency lookups. prevHash := &block.MsgBlock().Header.PrevBlock @@ -951,8 +946,8 @@ func (b *BlockChain) connectBestChain(node *blockNode, block *btcutil.Block, fla return nil } if fastAdd { - bsha, _ := block.Sha() - log.Warnf("fastAdd set in the side chain case? %v\n", bsha) + log.Warnf("fastAdd set in the side chain case? %v\n", + block.Sha()) } // We're extending (or creating) a side chain which may or may not diff --git a/blockchain/checkpoints.go b/blockchain/checkpoints.go index 2794dc75f..fbea66db5 100644 --- a/blockchain/checkpoints.go +++ b/blockchain/checkpoints.go @@ -221,13 +221,8 @@ func (b *BlockChain) IsCheckpointCandidate(block *btcutil.Block) (bool, error) { 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. - exists, err := b.db.ExistsSha(blockHash) + exists, err := b.db.ExistsSha(block.Sha()) if err != nil { return false, err } diff --git a/blockchain/process.go b/blockchain/process.go index 5b9448429..54fcdbd2e 100644 --- a/blockchain/process.go +++ b/blockchain/process.go @@ -85,9 +85,7 @@ func (b *BlockChain) processOrphans(hash *wire.ShaHash, flags BehaviorFlags) err } // Remove the orphan from the orphan pool. - // It's safe to ignore the error on Sha since the hash - // is already cached. - orphanHash, _ := orphan.block.Sha() + orphanHash := orphan.block.Sha() b.removeOrphanBlock(orphan) i-- @@ -118,10 +116,7 @@ func (b *BlockChain) ProcessBlock(block *btcutil.Block, timeSource MedianTimeSou fastAdd := flags&BFFastAdd == BFFastAdd dryRun := flags&BFDryRun == BFDryRun - blockHash, err := block.Sha() - if err != nil { - return false, err - } + blockHash := block.Sha() log.Tracef("Processing block %v", blockHash) // The block must not already exist in the main chain or side chains. diff --git a/blockchain/validate.go b/blockchain/validate.go index aa4f07963..3572d4aef 100644 --- a/blockchain/validate.go +++ b/blockchain/validate.go @@ -328,11 +328,7 @@ func checkProofOfWork(block *btcutil.Block, powLimit *big.Int, flags BehaviorFla // to avoid proof of work checks is set. if flags&BFNoPoWCheck != BFNoPoWCheck { // The block hash must be less than the claimed target. - blockHash, err := block.Sha() - if err != nil { - return err - } - hashNum := ShaHashToBig(blockHash) + hashNum := ShaHashToBig(block.Sha()) if hashNum.Cmp(target) > 0 { str := fmt.Sprintf("block hash of %064x is higher than "+ "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. func (b *BlockChain) CheckConnectBlock(block *btcutil.Block) error { prevNode := b.bestChain - blockSha, _ := block.Sha() - newNode := newBlockNode(&block.MsgBlock().Header, blockSha, block.Height()) + newNode := newBlockNode(&block.MsgBlock().Header, block.Sha(), + block.Height()) if prevNode != nil { newNode.parent = prevNode newNode.workSum.Add(prevNode.workSum, newNode.workSum) diff --git a/blockmanager.go b/blockmanager.go index 1f5250b7f..b8952145c 100644 --- a/blockmanager.go +++ b/blockmanager.go @@ -531,7 +531,7 @@ func (b *blockManager) current() bool { // handleBlockMsg handles block messages from all peers. func (b *blockManager) handleBlockMsg(bmsg *blockMsg) { // 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 { // The regression test intentionally sends some blocks twice // to test duplicate block insertion fails. Don't disconnect @@ -1193,12 +1193,8 @@ func (b *blockManager) handleNotifyMsg(notification *blockchain.Notification) { 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. - iv := wire.NewInvVect(wire.InvTypeBlock, hash) + iv := wire.NewInvVect(wire.InvTypeBlock, block.Sha()) b.server.RelayInventory(iv, nil) // A block has been connected to the main block chain. diff --git a/chainindexer.go b/chainindexer.go index 72ae7da22..ada6d0288 100644 --- a/chainindexer.go +++ b/chainindexer.go @@ -368,7 +368,7 @@ out: for { select { case nextWrite := <-minHeightWrite: - sha, _ := nextWrite.blk.Sha() // Can never fail. + sha := nextWrite.blk.Sha() height := nextWrite.blk.Height() err := a.server.db.UpdateAddrIndexForBlock(sha, height, nextWrite.addrIndex) diff --git a/cmd/addblock/import.go b/cmd/addblock/import.go index 7512f2473..83fad3013 100644 --- a/cmd/addblock/import.go +++ b/cmd/addblock/import.go @@ -99,16 +99,12 @@ func (bi *blockImporter) processBlock(serializedBlock []byte) (bool, error) { return false, err } - blockSha, err := block.Sha() - 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 diff --git a/cmd/findcheckpoint/findcheckpoint.go b/cmd/findcheckpoint/findcheckpoint.go index 57d59a746..97a4e3366 100644 --- a/cmd/findcheckpoint/findcheckpoint.go +++ b/cmd/findcheckpoint/findcheckpoint.go @@ -95,13 +95,9 @@ func findCandidates(db database.Db, latestHash *wire.ShaHash) ([]*chaincfg.Check // All checks passed, so this node seems like a reasonable // checkpoint candidate. if isCandidate { - candidateHash, err := block.Sha() - if err != nil { - return nil, err - } checkpoint := chaincfg.Checkpoint{ Height: block.Height(), - Hash: candidateHash, + Hash: block.Sha(), } candidates = append(candidates, &checkpoint) } diff --git a/cpuminer.go b/cpuminer.go index 614c59c68..45ce7cfa2 100644 --- a/cpuminer.go +++ b/cpuminer.go @@ -148,10 +148,9 @@ func (m *CPUMiner) submitBlock(block *btcutil.Block) bool { } // The block was accepted. - blockSha, _ := block.Sha() coinbaseTx := block.MsgBlock().Transactions[0].TxOut[0] 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 } diff --git a/database/ldb/leveldb.go b/database/ldb/leveldb.go index 9a10f349a..05ee7cb3f 100644 --- a/database/ldb/leveldb.go +++ b/database/ldb/leveldb.go @@ -372,11 +372,7 @@ func (db *LevelDb) InsertBlock(block *btcutil.Block) (height int64, rerr error) } }() - blocksha, err := block.Sha() - if err != nil { - log.Warnf("Failed to compute block sha %v", blocksha) - return 0, err - } + blocksha := block.Sha() mblock := block.MsgBlock() rawMsg, err := block.Bytes() if err != nil { diff --git a/database/memdb/memdb.go b/database/memdb/memdb.go index 9c7ffc7bf..9c2073ece 100644 --- a/database/memdb/memdb.go +++ b/database/memdb/memdb.go @@ -537,11 +537,6 @@ func (db *MemDb) InsertBlock(block *btcutil.Block) (int64, error) { return 0, ErrDbClosed } - blockHash, err := block.Sha() - if err != nil { - return 0, err - } - // Reject the insert if the previously reference block does not exist // except in the case there are no blocks inserted yet where the first // 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.blocksBySha[*blockHash] = newHeight + db.blocksBySha[*block.Sha()] = newHeight // Insert information about eacj transaction and spend all of the // outputs referenced by the inputs to the transactions. diff --git a/peer.go b/peer.go index 0f5ccb1ab..0f9e94597 100644 --- a/peer.go +++ b/peer.go @@ -822,12 +822,7 @@ func (p *peer) handleBlockMsg(msg *wire.MsgBlock, buf []byte) { block := btcutil.NewBlockFromBlockAndBytes(msg, buf) // Add the block to the known inventory for the peer. - hash, err := block.Sha() - if err != nil { - peerLog.Errorf("Unable to get block hash: %v", err) - return - } - iv := wire.NewInvVect(wire.InvTypeBlock, hash) + iv := wire.NewInvVect(wire.InvTypeBlock, block.Sha()) p.AddKnownInventory(iv) // Queue the block up to be handled by the block diff --git a/rpcserver.go b/rpcserver.go index 7c9bdd34a..2987b5f83 100644 --- a/rpcserver.go +++ b/rpcserver.go @@ -2608,8 +2608,7 @@ func handleGetWorkSubmission(s *rpcServer, hexData string) (interface{}, error) } // The block was accepted. - blockSha, _ := block.Sha() - rpcsLog.Infof("Block submitted via getwork accepted: %s", blockSha) + rpcsLog.Infof("Block submitted via getwork accepted: %s", block.Sha()) return true, nil } @@ -2837,7 +2836,7 @@ func handleSearchRawTransactions(s *rpcServer, cmd interface{}, closeChan <-chan var blkHash *wire.ShaHash if blk != nil { - blkHash, _ = blk.Sha() + blkHash = blk.Sha() } 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 } - blockSha, err := block.Sha() - if err == nil { - rpcsLog.Infof("Accepted block %s via submitblock", blockSha) - } + rpcsLog.Infof("Accepted block %s via submitblock", block.Sha()) return nil, nil } diff --git a/rpcwebsocket.go b/rpcwebsocket.go index 6aa79b6cc..2e1c4e4ec 100644 --- a/rpcwebsocket.go +++ b/rpcwebsocket.go @@ -406,14 +406,9 @@ func (m *wsNotificationManager) UnregisterBlockUpdates(wsc *wsClient) { func (*wsNotificationManager) notifyBlockConnected(clients map[chan struct{}]*wsClient, 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. - ntfn := btcjson.NewBlockConnectedNtfn(hash.String(), int32(block.Height())) + ntfn := btcjson.NewBlockConnectedNtfn(block.Sha().String(), + int32(block.Height())) marshalledJSON, err := btcjson.MarshalCmd(nil, ntfn) if err != nil { rpcsLog.Error("Failed to marshal block connected notification: "+ @@ -435,15 +430,8 @@ func (*wsNotificationManager) notifyBlockDisconnected(clients map[chan struct{}] 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. - ntfn := btcjson.NewBlockDisconnectedNtfn(hash.String(), + ntfn := btcjson.NewBlockDisconnectedNtfn(block.Sha().String(), int32(block.Height())) marshalledJSON, err := btcjson.MarshalCmd(nil, ntfn) if err != nil { @@ -600,10 +588,9 @@ func blockDetails(block *btcutil.Block, txIndex int) *btcjson.BlockDetails { if block == nil { return nil } - blockSha, _ := block.Sha() // never errors return &btcjson.BlockDetails{ Height: int32(block.Height()), - Hash: blockSha.String(), + Hash: block.Sha().String(), Index: txIndex, Time: block.MsgBlock().Header.Timestamp.Unix(), } @@ -1983,12 +1970,7 @@ fetchRange: default: rescanBlock(wsc, &lookups, blk) lastBlock = blk - lastBlockHash, err = blk.Sha() - if err != nil { - context := "Failed to create block hash" - return nil, internalRPCError(err.Error(), - context) - } + lastBlockHash = blk.Sha() } // Periodically notify the client of the progress