From 0a9fb535489c295cd59bdfeade4faa746f75831c Mon Sep 17 00:00:00 2001 From: Jim Posen Date: Wed, 30 Aug 2017 11:27:02 -0700 Subject: [PATCH] blockchain: Add node to block index in maybeAcceptBlock. This has the same effect but makes it clearer that all blocks written to the database end up in the block index. --- blockchain/accept.go | 9 +++++++++ blockchain/blockindex.go | 11 +++++++++++ blockchain/chain.go | 18 ------------------ 3 files changed, 20 insertions(+), 18 deletions(-) diff --git a/blockchain/accept.go b/blockchain/accept.go index 3d32f8c0..73169ebb 100644 --- a/blockchain/accept.go +++ b/blockchain/accept.go @@ -67,6 +67,15 @@ func (b *BlockChain) maybeAcceptBlock(block *btcutil.Block, flags BehaviorFlags) newNode.height = blockHeight newNode.workSum.Add(prevNode.workSum, newNode.workSum) } + b.index.AddNode(newNode) + + // Disconnect it from the parent node when the function returns when + // running in dry run mode. + if dryRun { + defer func() { + b.index.RemoveNode(newNode) + }() + } // Connect the passed block to the chain while respecting proper chain // selection according to the chain with the most proof of work. This diff --git a/blockchain/blockindex.go b/blockchain/blockindex.go index d65619eb..64d66ffa 100644 --- a/blockchain/blockindex.go +++ b/blockchain/blockindex.go @@ -224,3 +224,14 @@ func (bi *blockIndex) AddNode(node *blockNode) { bi.index[node.hash] = node bi.Unlock() } + +// RemoveNode removes the provided node to the block index. There is no check +// whether another node in the index depends on this one, so it is up to caller +// to avoid that situation. +// +// This function is safe for concurrent access. +func (bi *blockIndex) RemoveNode(node *blockNode) { + bi.Lock() + delete(bi.index, node.hash) + bi.Unlock() +} diff --git a/blockchain/chain.go b/blockchain/chain.go index d1ee628b..04160a09 100644 --- a/blockchain/chain.go +++ b/blockchain/chain.go @@ -648,7 +648,6 @@ func (b *BlockChain) connectBlock(node *blockNode, block *btcutil.Block, view *U view.commit() // This node is now the end of the best chain. - b.index.AddNode(node) b.bestChain.SetTip(node) // Update the state for the best block. Notice how this replaces the @@ -1044,23 +1043,6 @@ func (b *BlockChain) connectBestChain(node *blockNode, block *btcutil.Block, fla block.Hash()) } - // We're extending (or creating) a side chain which may or may not - // become the main chain, but in either case the entry is needed in the - // index for future processing. - b.index.Lock() - b.index.index[node.hash] = node - b.index.Unlock() - - // Disconnect it from the parent node when the function returns when - // running in dry run mode. - if dryRun { - defer func() { - b.index.Lock() - delete(b.index.index, node.hash) - b.index.Unlock() - }() - } - // We're extending (or creating) a side chain, but the cumulative // work for this new side chain is not enough to make it the new chain. if node.workSum.Cmp(b.bestChain.Tip().workSum) <= 0 {