github.com/btcsuite/btcd@v0.24.0/blockchain/chain.go (about)

     1  // Copyright (c) 2013-2018 The btcsuite developers
     2  // Copyright (c) 2015-2018 The Decred developers
     3  // Use of this source code is governed by an ISC
     4  // license that can be found in the LICENSE file.
     5  
     6  package blockchain
     7  
     8  import (
     9  	"container/list"
    10  	"fmt"
    11  	"sync"
    12  	"time"
    13  
    14  	"github.com/btcsuite/btcd/btcutil"
    15  	"github.com/btcsuite/btcd/chaincfg"
    16  	"github.com/btcsuite/btcd/chaincfg/chainhash"
    17  	"github.com/btcsuite/btcd/database"
    18  	"github.com/btcsuite/btcd/txscript"
    19  	"github.com/btcsuite/btcd/wire"
    20  )
    21  
    22  const (
    23  	// maxOrphanBlocks is the maximum number of orphan blocks that can be
    24  	// queued.
    25  	maxOrphanBlocks = 100
    26  )
    27  
    28  // BlockLocator is used to help locate a specific block.  The algorithm for
    29  // building the block locator is to add the hashes in reverse order until
    30  // the genesis block is reached.  In order to keep the list of locator hashes
    31  // to a reasonable number of entries, first the most recent previous 12 block
    32  // hashes are added, then the step is doubled each loop iteration to
    33  // exponentially decrease the number of hashes as a function of the distance
    34  // from the block being located.
    35  //
    36  // For example, assume a block chain with a side chain as depicted below:
    37  //
    38  //	genesis -> 1 -> 2 -> ... -> 15 -> 16  -> 17  -> 18
    39  //	                              \-> 16a -> 17a
    40  //
    41  // The block locator for block 17a would be the hashes of blocks:
    42  // [17a 16a 15 14 13 12 11 10 9 8 7 6 4 genesis]
    43  type BlockLocator []*chainhash.Hash
    44  
    45  // orphanBlock represents a block that we don't yet have the parent for.  It
    46  // is a normal block plus an expiration time to prevent caching the orphan
    47  // forever.
    48  type orphanBlock struct {
    49  	block      *btcutil.Block
    50  	expiration time.Time
    51  }
    52  
    53  // BestState houses information about the current best block and other info
    54  // related to the state of the main chain as it exists from the point of view of
    55  // the current best block.
    56  //
    57  // The BestSnapshot method can be used to obtain access to this information
    58  // in a concurrent safe manner and the data will not be changed out from under
    59  // the caller when chain state changes occur as the function name implies.
    60  // However, the returned snapshot must be treated as immutable since it is
    61  // shared by all callers.
    62  type BestState struct {
    63  	Hash        chainhash.Hash // The hash of the block.
    64  	Height      int32          // The height of the block.
    65  	Bits        uint32         // The difficulty bits of the block.
    66  	BlockSize   uint64         // The size of the block.
    67  	BlockWeight uint64         // The weight of the block.
    68  	NumTxns     uint64         // The number of txns in the block.
    69  	TotalTxns   uint64         // The total number of txns in the chain.
    70  	MedianTime  time.Time      // Median time as per CalcPastMedianTime.
    71  }
    72  
    73  // newBestState returns a new best stats instance for the given parameters.
    74  func newBestState(node *blockNode, blockSize, blockWeight, numTxns,
    75  	totalTxns uint64, medianTime time.Time) *BestState {
    76  
    77  	return &BestState{
    78  		Hash:        node.hash,
    79  		Height:      node.height,
    80  		Bits:        node.bits,
    81  		BlockSize:   blockSize,
    82  		BlockWeight: blockWeight,
    83  		NumTxns:     numTxns,
    84  		TotalTxns:   totalTxns,
    85  		MedianTime:  medianTime,
    86  	}
    87  }
    88  
    89  // BlockChain provides functions for working with the bitcoin block chain.
    90  // It includes functionality such as rejecting duplicate blocks, ensuring blocks
    91  // follow all rules, orphan handling, checkpoint handling, and best chain
    92  // selection with reorganization.
    93  type BlockChain struct {
    94  	// The following fields are set when the instance is created and can't
    95  	// be changed afterwards, so there is no need to protect them with a
    96  	// separate mutex.
    97  	checkpoints         []chaincfg.Checkpoint
    98  	checkpointsByHeight map[int32]*chaincfg.Checkpoint
    99  	db                  database.DB
   100  	chainParams         *chaincfg.Params
   101  	timeSource          MedianTimeSource
   102  	sigCache            *txscript.SigCache
   103  	indexManager        IndexManager
   104  	hashCache           *txscript.HashCache
   105  
   106  	// The following fields are calculated based upon the provided chain
   107  	// parameters.  They are also set when the instance is created and
   108  	// can't be changed afterwards, so there is no need to protect them with
   109  	// a separate mutex.
   110  	minRetargetTimespan int64 // target timespan / adjustment factor
   111  	maxRetargetTimespan int64 // target timespan * adjustment factor
   112  	blocksPerRetarget   int32 // target timespan / target time per block
   113  
   114  	// chainLock protects concurrent access to the vast majority of the
   115  	// fields in this struct below this point.
   116  	chainLock sync.RWMutex
   117  
   118  	// pruneTarget is the size in bytes the database targets for when the node
   119  	// is pruned.
   120  	pruneTarget uint64
   121  
   122  	// These fields are related to the memory block index.  They both have
   123  	// their own locks, however they are often also protected by the chain
   124  	// lock to help prevent logic races when blocks are being processed.
   125  	//
   126  	// index houses the entire block index in memory.  The block index is
   127  	// a tree-shaped structure.
   128  	//
   129  	// bestChain tracks the current active chain by making use of an
   130  	// efficient chain view into the block index.
   131  	index     *blockIndex
   132  	bestChain *chainView
   133  
   134  	// The UTXO state holds a cached view of the UTXO state of the chain.
   135  	// It is protected by the chain lock.
   136  	utxoCache *utxoCache
   137  
   138  	// These fields are related to handling of orphan blocks.  They are
   139  	// protected by a combination of the chain lock and the orphan lock.
   140  	orphanLock   sync.RWMutex
   141  	orphans      map[chainhash.Hash]*orphanBlock
   142  	prevOrphans  map[chainhash.Hash][]*orphanBlock
   143  	oldestOrphan *orphanBlock
   144  
   145  	// These fields are related to checkpoint handling.  They are protected
   146  	// by the chain lock.
   147  	nextCheckpoint *chaincfg.Checkpoint
   148  	checkpointNode *blockNode
   149  
   150  	// The state is used as a fairly efficient way to cache information
   151  	// about the current best chain state that is returned to callers when
   152  	// requested.  It operates on the principle of MVCC such that any time a
   153  	// new block becomes the best block, the state pointer is replaced with
   154  	// a new struct and the old state is left untouched.  In this way,
   155  	// multiple callers can be pointing to different best chain states.
   156  	// This is acceptable for most callers because the state is only being
   157  	// queried at a specific point in time.
   158  	//
   159  	// In addition, some of the fields are stored in the database so the
   160  	// chain state can be quickly reconstructed on load.
   161  	stateLock     sync.RWMutex
   162  	stateSnapshot *BestState
   163  
   164  	// The following caches are used to efficiently keep track of the
   165  	// current deployment threshold state of each rule change deployment.
   166  	//
   167  	// This information is stored in the database so it can be quickly
   168  	// reconstructed on load.
   169  	//
   170  	// warningCaches caches the current deployment threshold state for blocks
   171  	// in each of the **possible** deployments.  This is used in order to
   172  	// detect when new unrecognized rule changes are being voted on and/or
   173  	// have been activated such as will be the case when older versions of
   174  	// the software are being used
   175  	//
   176  	// deploymentCaches caches the current deployment threshold state for
   177  	// blocks in each of the actively defined deployments.
   178  	warningCaches    []thresholdStateCache
   179  	deploymentCaches []thresholdStateCache
   180  
   181  	// The following fields are used to determine if certain warnings have
   182  	// already been shown.
   183  	//
   184  	// unknownRulesWarned refers to warnings due to unknown rules being
   185  	// activated.
   186  	unknownRulesWarned bool
   187  
   188  	// The notifications field stores a slice of callbacks to be executed on
   189  	// certain blockchain events.
   190  	notificationsLock sync.RWMutex
   191  	notifications     []NotificationCallback
   192  }
   193  
   194  // HaveBlock returns whether or not the chain instance has the block represented
   195  // by the passed hash.  This includes checking the various places a block can
   196  // be like part of the main chain, on a side chain, or in the orphan pool.
   197  //
   198  // This function is safe for concurrent access.
   199  func (b *BlockChain) HaveBlock(hash *chainhash.Hash) (bool, error) {
   200  	exists, err := b.blockExists(hash)
   201  	if err != nil {
   202  		return false, err
   203  	}
   204  	return exists || b.IsKnownOrphan(hash), nil
   205  }
   206  
   207  // IsKnownOrphan returns whether the passed hash is currently a known orphan.
   208  // Keep in mind that only a limited number of orphans are held onto for a
   209  // limited amount of time, so this function must not be used as an absolute
   210  // way to test if a block is an orphan block.  A full block (as opposed to just
   211  // its hash) must be passed to ProcessBlock for that purpose.  However, calling
   212  // ProcessBlock with an orphan that already exists results in an error, so this
   213  // function provides a mechanism for a caller to intelligently detect *recent*
   214  // duplicate orphans and react accordingly.
   215  //
   216  // This function is safe for concurrent access.
   217  func (b *BlockChain) IsKnownOrphan(hash *chainhash.Hash) bool {
   218  	// Protect concurrent access.  Using a read lock only so multiple
   219  	// readers can query without blocking each other.
   220  	b.orphanLock.RLock()
   221  	_, exists := b.orphans[*hash]
   222  	b.orphanLock.RUnlock()
   223  
   224  	return exists
   225  }
   226  
   227  // GetOrphanRoot returns the head of the chain for the provided hash from the
   228  // map of orphan blocks.
   229  //
   230  // This function is safe for concurrent access.
   231  func (b *BlockChain) GetOrphanRoot(hash *chainhash.Hash) *chainhash.Hash {
   232  	// Protect concurrent access.  Using a read lock only so multiple
   233  	// readers can query without blocking each other.
   234  	b.orphanLock.RLock()
   235  	defer b.orphanLock.RUnlock()
   236  
   237  	// Keep looping while the parent of each orphaned block is
   238  	// known and is an orphan itself.
   239  	orphanRoot := hash
   240  	prevHash := hash
   241  	for {
   242  		orphan, exists := b.orphans[*prevHash]
   243  		if !exists {
   244  			break
   245  		}
   246  		orphanRoot = prevHash
   247  		prevHash = &orphan.block.MsgBlock().Header.PrevBlock
   248  	}
   249  
   250  	return orphanRoot
   251  }
   252  
   253  // removeOrphanBlock removes the passed orphan block from the orphan pool and
   254  // previous orphan index.
   255  func (b *BlockChain) removeOrphanBlock(orphan *orphanBlock) {
   256  	// Protect concurrent access.
   257  	b.orphanLock.Lock()
   258  	defer b.orphanLock.Unlock()
   259  
   260  	// Remove the orphan block from the orphan pool.
   261  	orphanHash := orphan.block.Hash()
   262  	delete(b.orphans, *orphanHash)
   263  
   264  	// Remove the reference from the previous orphan index too.  An indexing
   265  	// for loop is intentionally used over a range here as range does not
   266  	// reevaluate the slice on each iteration nor does it adjust the index
   267  	// for the modified slice.
   268  	prevHash := &orphan.block.MsgBlock().Header.PrevBlock
   269  	orphans := b.prevOrphans[*prevHash]
   270  	for i := 0; i < len(orphans); i++ {
   271  		hash := orphans[i].block.Hash()
   272  		if hash.IsEqual(orphanHash) {
   273  			copy(orphans[i:], orphans[i+1:])
   274  			orphans[len(orphans)-1] = nil
   275  			orphans = orphans[:len(orphans)-1]
   276  			i--
   277  		}
   278  	}
   279  	b.prevOrphans[*prevHash] = orphans
   280  
   281  	// Remove the map entry altogether if there are no longer any orphans
   282  	// which depend on the parent hash.
   283  	if len(b.prevOrphans[*prevHash]) == 0 {
   284  		delete(b.prevOrphans, *prevHash)
   285  	}
   286  }
   287  
   288  // addOrphanBlock adds the passed block (which is already determined to be
   289  // an orphan prior calling this function) to the orphan pool.  It lazily cleans
   290  // up any expired blocks so a separate cleanup poller doesn't need to be run.
   291  // It also imposes a maximum limit on the number of outstanding orphan
   292  // blocks and will remove the oldest received orphan block if the limit is
   293  // exceeded.
   294  func (b *BlockChain) addOrphanBlock(block *btcutil.Block) {
   295  	// Remove expired orphan blocks.
   296  	for _, oBlock := range b.orphans {
   297  		if time.Now().After(oBlock.expiration) {
   298  			b.removeOrphanBlock(oBlock)
   299  			continue
   300  		}
   301  
   302  		// Update the oldest orphan block pointer so it can be discarded
   303  		// in case the orphan pool fills up.
   304  		if b.oldestOrphan == nil || oBlock.expiration.Before(b.oldestOrphan.expiration) {
   305  			b.oldestOrphan = oBlock
   306  		}
   307  	}
   308  
   309  	// Limit orphan blocks to prevent memory exhaustion.
   310  	if len(b.orphans)+1 > maxOrphanBlocks {
   311  		// Remove the oldest orphan to make room for the new one.
   312  		b.removeOrphanBlock(b.oldestOrphan)
   313  		b.oldestOrphan = nil
   314  	}
   315  
   316  	// Protect concurrent access.  This is intentionally done here instead
   317  	// of near the top since removeOrphanBlock does its own locking and
   318  	// the range iterator is not invalidated by removing map entries.
   319  	b.orphanLock.Lock()
   320  	defer b.orphanLock.Unlock()
   321  
   322  	// Insert the block into the orphan map with an expiration time
   323  	// 1 hour from now.
   324  	expiration := time.Now().Add(time.Hour)
   325  	oBlock := &orphanBlock{
   326  		block:      block,
   327  		expiration: expiration,
   328  	}
   329  	b.orphans[*block.Hash()] = oBlock
   330  
   331  	// Add to previous hash lookup index for faster dependency lookups.
   332  	prevHash := &block.MsgBlock().Header.PrevBlock
   333  	b.prevOrphans[*prevHash] = append(b.prevOrphans[*prevHash], oBlock)
   334  }
   335  
   336  // SequenceLock represents the converted relative lock-time in seconds, and
   337  // absolute block-height for a transaction input's relative lock-times.
   338  // According to SequenceLock, after the referenced input has been confirmed
   339  // within a block, a transaction spending that input can be included into a
   340  // block either after 'seconds' (according to past median time), or once the
   341  // 'BlockHeight' has been reached.
   342  type SequenceLock struct {
   343  	Seconds     int64
   344  	BlockHeight int32
   345  }
   346  
   347  // CalcSequenceLock computes a relative lock-time SequenceLock for the passed
   348  // transaction using the passed UtxoViewpoint to obtain the past median time
   349  // for blocks in which the referenced inputs of the transactions were included
   350  // within. The generated SequenceLock lock can be used in conjunction with a
   351  // block height, and adjusted median block time to determine if all the inputs
   352  // referenced within a transaction have reached sufficient maturity allowing
   353  // the candidate transaction to be included in a block.
   354  //
   355  // This function is safe for concurrent access.
   356  func (b *BlockChain) CalcSequenceLock(tx *btcutil.Tx, utxoView *UtxoViewpoint, mempool bool) (*SequenceLock, error) {
   357  	b.chainLock.Lock()
   358  	defer b.chainLock.Unlock()
   359  
   360  	return b.calcSequenceLock(b.bestChain.Tip(), tx, utxoView, mempool)
   361  }
   362  
   363  // calcSequenceLock computes the relative lock-times for the passed
   364  // transaction. See the exported version, CalcSequenceLock for further details.
   365  //
   366  // This function MUST be called with the chain state lock held (for writes).
   367  func (b *BlockChain) calcSequenceLock(node *blockNode, tx *btcutil.Tx, utxoView *UtxoViewpoint, mempool bool) (*SequenceLock, error) {
   368  	// A value of -1 for each relative lock type represents a relative time
   369  	// lock value that will allow a transaction to be included in a block
   370  	// at any given height or time. This value is returned as the relative
   371  	// lock time in the case that BIP 68 is disabled, or has not yet been
   372  	// activated.
   373  	sequenceLock := &SequenceLock{Seconds: -1, BlockHeight: -1}
   374  
   375  	// The sequence locks semantics are always active for transactions
   376  	// within the mempool.
   377  	csvSoftforkActive := mempool
   378  
   379  	// If we're performing block validation, then we need to query the BIP9
   380  	// state.
   381  	if !csvSoftforkActive {
   382  		// Obtain the latest BIP9 version bits state for the
   383  		// CSV-package soft-fork deployment. The adherence of sequence
   384  		// locks depends on the current soft-fork state.
   385  		csvState, err := b.deploymentState(node.parent, chaincfg.DeploymentCSV)
   386  		if err != nil {
   387  			return nil, err
   388  		}
   389  		csvSoftforkActive = csvState == ThresholdActive
   390  	}
   391  
   392  	// If the transaction's version is less than 2, and BIP 68 has not yet
   393  	// been activated then sequence locks are disabled. Additionally,
   394  	// sequence locks don't apply to coinbase transactions Therefore, we
   395  	// return sequence lock values of -1 indicating that this transaction
   396  	// can be included within a block at any given height or time.
   397  	mTx := tx.MsgTx()
   398  	sequenceLockActive := uint32(mTx.Version) >= 2 && csvSoftforkActive
   399  	if !sequenceLockActive || IsCoinBase(tx) {
   400  		return sequenceLock, nil
   401  	}
   402  
   403  	// Grab the next height from the PoV of the passed blockNode to use for
   404  	// inputs present in the mempool.
   405  	nextHeight := node.height + 1
   406  
   407  	for txInIndex, txIn := range mTx.TxIn {
   408  		utxo := utxoView.LookupEntry(txIn.PreviousOutPoint)
   409  		if utxo == nil {
   410  			str := fmt.Sprintf("output %v referenced from "+
   411  				"transaction %s:%d either does not exist or "+
   412  				"has already been spent", txIn.PreviousOutPoint,
   413  				tx.Hash(), txInIndex)
   414  			return sequenceLock, ruleError(ErrMissingTxOut, str)
   415  		}
   416  
   417  		// If the input height is set to the mempool height, then we
   418  		// assume the transaction makes it into the next block when
   419  		// evaluating its sequence blocks.
   420  		inputHeight := utxo.BlockHeight()
   421  		if inputHeight == 0x7fffffff {
   422  			inputHeight = nextHeight
   423  		}
   424  
   425  		// Given a sequence number, we apply the relative time lock
   426  		// mask in order to obtain the time lock delta required before
   427  		// this input can be spent.
   428  		sequenceNum := txIn.Sequence
   429  		relativeLock := int64(sequenceNum & wire.SequenceLockTimeMask)
   430  
   431  		switch {
   432  		// Relative time locks are disabled for this input, so we can
   433  		// skip any further calculation.
   434  		case sequenceNum&wire.SequenceLockTimeDisabled == wire.SequenceLockTimeDisabled:
   435  			continue
   436  		case sequenceNum&wire.SequenceLockTimeIsSeconds == wire.SequenceLockTimeIsSeconds:
   437  			// This input requires a relative time lock expressed
   438  			// in seconds before it can be spent.  Therefore, we
   439  			// need to query for the block prior to the one in
   440  			// which this input was included within so we can
   441  			// compute the past median time for the block prior to
   442  			// the one which included this referenced output.
   443  			prevInputHeight := inputHeight - 1
   444  			if prevInputHeight < 0 {
   445  				prevInputHeight = 0
   446  			}
   447  			blockNode := node.Ancestor(prevInputHeight)
   448  			medianTime := CalcPastMedianTime(blockNode)
   449  
   450  			// Time based relative time-locks as defined by BIP 68
   451  			// have a time granularity of RelativeLockSeconds, so
   452  			// we shift left by this amount to convert to the
   453  			// proper relative time-lock. We also subtract one from
   454  			// the relative lock to maintain the original lockTime
   455  			// semantics.
   456  			timeLockSeconds := (relativeLock << wire.SequenceLockTimeGranularity) - 1
   457  			timeLock := medianTime.Unix() + timeLockSeconds
   458  			if timeLock > sequenceLock.Seconds {
   459  				sequenceLock.Seconds = timeLock
   460  			}
   461  		default:
   462  			// The relative lock-time for this input is expressed
   463  			// in blocks so we calculate the relative offset from
   464  			// the input's height as its converted absolute
   465  			// lock-time. We subtract one from the relative lock in
   466  			// order to maintain the original lockTime semantics.
   467  			blockHeight := inputHeight + int32(relativeLock-1)
   468  			if blockHeight > sequenceLock.BlockHeight {
   469  				sequenceLock.BlockHeight = blockHeight
   470  			}
   471  		}
   472  	}
   473  
   474  	return sequenceLock, nil
   475  }
   476  
   477  // LockTimeToSequence converts the passed relative locktime to a sequence
   478  // number in accordance to BIP-68.
   479  // See: https://github.com/bitcoin/bips/blob/master/bip-0068.mediawiki
   480  //   - (Compatibility)
   481  func LockTimeToSequence(isSeconds bool, locktime uint32) uint32 {
   482  	// If we're expressing the relative lock time in blocks, then the
   483  	// corresponding sequence number is simply the desired input age.
   484  	if !isSeconds {
   485  		return locktime
   486  	}
   487  
   488  	// Set the 22nd bit which indicates the lock time is in seconds, then
   489  	// shift the locktime over by 9 since the time granularity is in
   490  	// 512-second intervals (2^9). This results in a max lock-time of
   491  	// 33,553,920 seconds, or 1.1 years.
   492  	return wire.SequenceLockTimeIsSeconds |
   493  		locktime>>wire.SequenceLockTimeGranularity
   494  }
   495  
   496  // getReorganizeNodes finds the fork point between the main chain and the passed
   497  // node and returns a list of block nodes that would need to be detached from
   498  // the main chain and a list of block nodes that would need to be attached to
   499  // the fork point (which will be the end of the main chain after detaching the
   500  // returned list of block nodes) in order to reorganize the chain such that the
   501  // passed node is the new end of the main chain.  The lists will be empty if the
   502  // passed node is not on a side chain.
   503  //
   504  // This function may modify node statuses in the block index without flushing.
   505  //
   506  // This function MUST be called with the chain state lock held (for reads).
   507  func (b *BlockChain) getReorganizeNodes(node *blockNode) (*list.List, *list.List) {
   508  	attachNodes := list.New()
   509  	detachNodes := list.New()
   510  
   511  	// Do not reorganize to a known invalid chain. Ancestors deeper than the
   512  	// direct parent are checked below but this is a quick check before doing
   513  	// more unnecessary work.
   514  	if b.index.NodeStatus(node.parent).KnownInvalid() {
   515  		b.index.SetStatusFlags(node, statusInvalidAncestor)
   516  		return detachNodes, attachNodes
   517  	}
   518  
   519  	// Find the fork point (if any) adding each block to the list of nodes
   520  	// to attach to the main tree.  Push them onto the list in reverse order
   521  	// so they are attached in the appropriate order when iterating the list
   522  	// later.
   523  	forkNode := b.bestChain.FindFork(node)
   524  	invalidChain := false
   525  	for n := node; n != nil && n != forkNode; n = n.parent {
   526  		if b.index.NodeStatus(n).KnownInvalid() {
   527  			invalidChain = true
   528  			break
   529  		}
   530  		attachNodes.PushFront(n)
   531  	}
   532  
   533  	// If any of the node's ancestors are invalid, unwind attachNodes, marking
   534  	// each one as invalid for future reference.
   535  	if invalidChain {
   536  		var next *list.Element
   537  		for e := attachNodes.Front(); e != nil; e = next {
   538  			next = e.Next()
   539  			n := attachNodes.Remove(e).(*blockNode)
   540  			b.index.SetStatusFlags(n, statusInvalidAncestor)
   541  		}
   542  		return detachNodes, attachNodes
   543  	}
   544  
   545  	// Start from the end of the main chain and work backwards until the
   546  	// common ancestor adding each block to the list of nodes to detach from
   547  	// the main chain.
   548  	for n := b.bestChain.Tip(); n != nil && n != forkNode; n = n.parent {
   549  		detachNodes.PushBack(n)
   550  	}
   551  
   552  	return detachNodes, attachNodes
   553  }
   554  
   555  // connectBlock handles connecting the passed node/block to the end of the main
   556  // (best) chain.
   557  //
   558  // Passing in a utxo view is optional.  If the passed in utxo view is nil,
   559  // connectBlock will assume that the utxo cache has already connected all the
   560  // txs in the block being connected.
   561  // If a utxo view is passed in, this passed utxo view must have all referenced
   562  // txos the block spends marked as spent and all of the new txos the block creates
   563  // added to it.
   564  //
   565  // The passed stxos slice must be populated with all of the information for the
   566  // spent txos.  This approach is used because the connection validation that
   567  // must happen prior to calling this function requires the same details, so
   568  // it would be inefficient to repeat it.
   569  //
   570  // This function MUST be called with the chain state lock held (for writes).
   571  func (b *BlockChain) connectBlock(node *blockNode, block *btcutil.Block,
   572  	view *UtxoViewpoint, stxos []SpentTxOut) error {
   573  
   574  	// Make sure it's extending the end of the best chain.
   575  	prevHash := &block.MsgBlock().Header.PrevBlock
   576  	if !prevHash.IsEqual(&b.bestChain.Tip().hash) {
   577  		return AssertError("connectBlock must be called with a block " +
   578  			"that extends the main chain")
   579  	}
   580  
   581  	// Sanity check the correct number of stxos are provided.
   582  	if len(stxos) != countSpentOutputs(block) {
   583  		return AssertError("connectBlock called with inconsistent " +
   584  			"spent transaction out information")
   585  	}
   586  
   587  	// No warnings about unknown rules until the chain is current.
   588  	if b.isCurrent() {
   589  		// Warn if any unknown new rules are either about to activate or
   590  		// have already been activated.
   591  		if err := b.warnUnknownRuleActivations(node); err != nil {
   592  			return err
   593  		}
   594  	}
   595  
   596  	// Write any block status changes to DB before updating best state.
   597  	err := b.index.flushToDB()
   598  	if err != nil {
   599  		return err
   600  	}
   601  
   602  	// Generate a new best state snapshot that will be used to update the
   603  	// database and later memory if all database updates are successful.
   604  	b.stateLock.RLock()
   605  	curTotalTxns := b.stateSnapshot.TotalTxns
   606  	b.stateLock.RUnlock()
   607  	numTxns := uint64(len(block.MsgBlock().Transactions))
   608  	blockSize := uint64(block.MsgBlock().SerializeSize())
   609  	blockWeight := uint64(GetBlockWeight(block))
   610  	state := newBestState(node, blockSize, blockWeight, numTxns,
   611  		curTotalTxns+numTxns, CalcPastMedianTime(node),
   612  	)
   613  
   614  	// If a utxoviewpoint was passed in, we'll be writing that viewpoint
   615  	// directly to the database on disk.  In order for the database to be
   616  	// consistent, we must flush the cache before writing the viewpoint.
   617  	if view != nil {
   618  		err = b.db.Update(func(dbTx database.Tx) error {
   619  			return b.utxoCache.flush(dbTx, FlushRequired, state)
   620  		})
   621  		if err != nil {
   622  			return err
   623  		}
   624  	}
   625  
   626  	// Atomically insert info into the database.
   627  	err = b.db.Update(func(dbTx database.Tx) error {
   628  		// If the pruneTarget isn't 0, we should attempt to delete older blocks
   629  		// from the database.
   630  		if b.pruneTarget != 0 {
   631  			// When the total block size is under the prune target, prune blocks is
   632  			// a no-op and the deleted hashes are nil.
   633  			deletedHashes, err := dbTx.PruneBlocks(b.pruneTarget)
   634  			if err != nil {
   635  				return err
   636  			}
   637  
   638  			// Only attempt to delete if we have any deleted blocks.
   639  			if len(deletedHashes) != 0 {
   640  				// Delete the spend journals of the pruned blocks.
   641  				err = dbPruneSpendJournalEntry(dbTx, deletedHashes)
   642  				if err != nil {
   643  					return err
   644  				}
   645  
   646  				// We may need to flush if the prune will delete blocks that
   647  				// are past our last flush block.
   648  				//
   649  				// NOTE: the database will never be inconsistent here as the
   650  				// actual blocks are not deleted until the db.Update returns.
   651  				needsFlush, err := b.flushNeededAfterPrune(deletedHashes)
   652  				if err != nil {
   653  					return err
   654  				}
   655  				if needsFlush {
   656  					// Since the deleted hashes are past our last
   657  					// flush block, flush the utxo cache now.
   658  					err = b.utxoCache.flush(dbTx, FlushRequired, state)
   659  					if err != nil {
   660  						return err
   661  					}
   662  				}
   663  			}
   664  		}
   665  
   666  		// Update best block state.
   667  		err := dbPutBestState(dbTx, state, node.workSum)
   668  		if err != nil {
   669  			return err
   670  		}
   671  
   672  		// Add the block hash and height to the block index which tracks
   673  		// the main chain.
   674  		err = dbPutBlockIndex(dbTx, block.Hash(), node.height)
   675  		if err != nil {
   676  			return err
   677  		}
   678  
   679  		// Update the utxo set using the state of the utxo view.  This
   680  		// entails removing all of the utxos spent and adding the new
   681  		// ones created by the block.
   682  		//
   683  		// A nil viewpoint is a no-op.
   684  		err = dbPutUtxoView(dbTx, view)
   685  		if err != nil {
   686  			return err
   687  		}
   688  
   689  		// Update the transaction spend journal by adding a record for
   690  		// the block that contains all txos spent by it.
   691  		err = dbPutSpendJournalEntry(dbTx, block.Hash(), stxos)
   692  		if err != nil {
   693  			return err
   694  		}
   695  
   696  		// Allow the index manager to call each of the currently active
   697  		// optional indexes with the block being connected so they can
   698  		// update themselves accordingly.
   699  		if b.indexManager != nil {
   700  			err := b.indexManager.ConnectBlock(dbTx, block, stxos)
   701  			if err != nil {
   702  				return err
   703  			}
   704  		}
   705  
   706  		return nil
   707  	})
   708  	if err != nil {
   709  		return err
   710  	}
   711  
   712  	// Prune fully spent entries and mark all entries in the view unmodified
   713  	// now that the modifications have been committed to the database.
   714  	if view != nil {
   715  		view.commit()
   716  	}
   717  
   718  	// This node is now the end of the best chain.
   719  	b.bestChain.SetTip(node)
   720  
   721  	// Update the state for the best block.  Notice how this replaces the
   722  	// entire struct instead of updating the existing one.  This effectively
   723  	// allows the old version to act as a snapshot which callers can use
   724  	// freely without needing to hold a lock for the duration.  See the
   725  	// comments on the state variable for more details.
   726  	b.stateLock.Lock()
   727  	b.stateSnapshot = state
   728  	b.stateLock.Unlock()
   729  
   730  	// Notify the caller that the block was connected to the main chain.
   731  	// The caller would typically want to react with actions such as
   732  	// updating wallets.
   733  	b.chainLock.Unlock()
   734  	b.sendNotification(NTBlockConnected, block)
   735  	b.chainLock.Lock()
   736  
   737  	// Since we may have changed the UTXO cache, we make sure it didn't exceed its
   738  	// maximum size.  If we're pruned and have flushed already, this will be a no-op.
   739  	return b.db.Update(func(dbTx database.Tx) error {
   740  		return b.utxoCache.flush(dbTx, FlushIfNeeded, state)
   741  	})
   742  }
   743  
   744  // disconnectBlock handles disconnecting the passed node/block from the end of
   745  // the main (best) chain.
   746  //
   747  // This function MUST be called with the chain state lock held (for writes).
   748  func (b *BlockChain) disconnectBlock(node *blockNode, block *btcutil.Block, view *UtxoViewpoint) error {
   749  	// Make sure the node being disconnected is the end of the best chain.
   750  	if !node.hash.IsEqual(&b.bestChain.Tip().hash) {
   751  		return AssertError("disconnectBlock must be called with the " +
   752  			"block at the end of the main chain")
   753  	}
   754  
   755  	// Load the previous block since some details for it are needed below.
   756  	prevNode := node.parent
   757  	var prevBlock *btcutil.Block
   758  	err := b.db.View(func(dbTx database.Tx) error {
   759  		var err error
   760  		prevBlock, err = dbFetchBlockByNode(dbTx, prevNode)
   761  		return err
   762  	})
   763  	if err != nil {
   764  		return err
   765  	}
   766  
   767  	// Write any block status changes to DB before updating best state.
   768  	err = b.index.flushToDB()
   769  	if err != nil {
   770  		return err
   771  	}
   772  
   773  	// Generate a new best state snapshot that will be used to update the
   774  	// database and later memory if all database updates are successful.
   775  	b.stateLock.RLock()
   776  	curTotalTxns := b.stateSnapshot.TotalTxns
   777  	b.stateLock.RUnlock()
   778  	numTxns := uint64(len(prevBlock.MsgBlock().Transactions))
   779  	blockSize := uint64(prevBlock.MsgBlock().SerializeSize())
   780  	blockWeight := uint64(GetBlockWeight(prevBlock))
   781  	newTotalTxns := curTotalTxns - uint64(len(block.MsgBlock().Transactions))
   782  	state := newBestState(prevNode, blockSize, blockWeight, numTxns,
   783  		newTotalTxns, CalcPastMedianTime(prevNode))
   784  
   785  	err = b.db.Update(func(dbTx database.Tx) error {
   786  		// Update best block state.
   787  		err := dbPutBestState(dbTx, state, node.workSum)
   788  		if err != nil {
   789  			return err
   790  		}
   791  
   792  		// Remove the block hash and height from the block index which
   793  		// tracks the main chain.
   794  		err = dbRemoveBlockIndex(dbTx, block.Hash(), node.height)
   795  		if err != nil {
   796  			return err
   797  		}
   798  
   799  		// Update the utxo set using the state of the utxo view.  This
   800  		// entails restoring all of the utxos spent and removing the new
   801  		// ones created by the block.
   802  		err = dbPutUtxoView(dbTx, view)
   803  		if err != nil {
   804  			return err
   805  		}
   806  
   807  		// Before we delete the spend journal entry for this back,
   808  		// we'll fetch it as is so the indexers can utilize if needed.
   809  		stxos, err := dbFetchSpendJournalEntry(dbTx, block)
   810  		if err != nil {
   811  			return err
   812  		}
   813  
   814  		// Update the transaction spend journal by removing the record
   815  		// that contains all txos spent by the block.
   816  		err = dbRemoveSpendJournalEntry(dbTx, block.Hash())
   817  		if err != nil {
   818  			return err
   819  		}
   820  
   821  		// Allow the index manager to call each of the currently active
   822  		// optional indexes with the block being disconnected so they
   823  		// can update themselves accordingly.
   824  		if b.indexManager != nil {
   825  			err := b.indexManager.DisconnectBlock(dbTx, block, stxos)
   826  			if err != nil {
   827  				return err
   828  			}
   829  		}
   830  
   831  		return nil
   832  	})
   833  	if err != nil {
   834  		return err
   835  	}
   836  
   837  	// Prune fully spent entries and mark all entries in the view unmodified
   838  	// now that the modifications have been committed to the database.
   839  	view.commit()
   840  
   841  	// This node's parent is now the end of the best chain.
   842  	b.bestChain.SetTip(node.parent)
   843  
   844  	// Update the state for the best block.  Notice how this replaces the
   845  	// entire struct instead of updating the existing one.  This effectively
   846  	// allows the old version to act as a snapshot which callers can use
   847  	// freely without needing to hold a lock for the duration.  See the
   848  	// comments on the state variable for more details.
   849  	b.stateLock.Lock()
   850  	b.stateSnapshot = state
   851  	b.stateLock.Unlock()
   852  
   853  	// Notify the caller that the block was disconnected from the main
   854  	// chain.  The caller would typically want to react with actions such as
   855  	// updating wallets.
   856  	b.chainLock.Unlock()
   857  	b.sendNotification(NTBlockDisconnected, block)
   858  	b.chainLock.Lock()
   859  
   860  	return nil
   861  }
   862  
   863  // countSpentOutputs returns the number of utxos the passed block spends.
   864  func countSpentOutputs(block *btcutil.Block) int {
   865  	// Exclude the coinbase transaction since it can't spend anything.
   866  	var numSpent int
   867  	for _, tx := range block.Transactions()[1:] {
   868  		numSpent += len(tx.MsgTx().TxIn)
   869  	}
   870  	return numSpent
   871  }
   872  
   873  // reorganizeChain reorganizes the block chain by disconnecting the nodes in the
   874  // detachNodes list and connecting the nodes in the attach list.  It expects
   875  // that the lists are already in the correct order and are in sync with the
   876  // end of the current best chain.  Specifically, nodes that are being
   877  // disconnected must be in reverse order (think of popping them off the end of
   878  // the chain) and nodes the are being attached must be in forwards order
   879  // (think pushing them onto the end of the chain).
   880  //
   881  // This function may modify node statuses in the block index without flushing.
   882  //
   883  // This function MUST be called with the chain state lock held (for writes).
   884  func (b *BlockChain) reorganizeChain(detachNodes, attachNodes *list.List) error {
   885  	// Nothing to do if no reorganize nodes were provided.
   886  	if detachNodes.Len() == 0 && attachNodes.Len() == 0 {
   887  		return nil
   888  	}
   889  
   890  	// The rest of the reorg depends on all STXOs already being in the database
   891  	// so we flush before reorg.
   892  	err := b.db.Update(func(dbTx database.Tx) error {
   893  		return b.utxoCache.flush(dbTx, FlushRequired, b.BestSnapshot())
   894  	})
   895  	if err != nil {
   896  		return err
   897  	}
   898  
   899  	// Ensure the provided nodes match the current best chain.
   900  	tip := b.bestChain.Tip()
   901  	if detachNodes.Len() != 0 {
   902  		firstDetachNode := detachNodes.Front().Value.(*blockNode)
   903  		if firstDetachNode.hash != tip.hash {
   904  			return AssertError(fmt.Sprintf("reorganize nodes to detach are "+
   905  				"not for the current best chain -- first detach node %v, "+
   906  				"current chain %v", &firstDetachNode.hash, &tip.hash))
   907  		}
   908  	}
   909  
   910  	// Ensure the provided nodes are for the same fork point.
   911  	if attachNodes.Len() != 0 && detachNodes.Len() != 0 {
   912  		firstAttachNode := attachNodes.Front().Value.(*blockNode)
   913  		lastDetachNode := detachNodes.Back().Value.(*blockNode)
   914  		if firstAttachNode.parent.hash != lastDetachNode.parent.hash {
   915  			return AssertError(fmt.Sprintf("reorganize nodes do not have the "+
   916  				"same fork point -- first attach parent %v, last detach "+
   917  				"parent %v", &firstAttachNode.parent.hash,
   918  				&lastDetachNode.parent.hash))
   919  		}
   920  	}
   921  
   922  	// Track the old and new best chains heads.
   923  	oldBest := tip
   924  	newBest := tip
   925  
   926  	// All of the blocks to detach and related spend journal entries needed
   927  	// to unspend transaction outputs in the blocks being disconnected must
   928  	// be loaded from the database during the reorg check phase below and
   929  	// then they are needed again when doing the actual database updates.
   930  	// Rather than doing two loads, cache the loaded data into these slices.
   931  	detachBlocks := make([]*btcutil.Block, 0, detachNodes.Len())
   932  	detachSpentTxOuts := make([][]SpentTxOut, 0, detachNodes.Len())
   933  	attachBlocks := make([]*btcutil.Block, 0, attachNodes.Len())
   934  
   935  	// Disconnect all of the blocks back to the point of the fork.  This
   936  	// entails loading the blocks and their associated spent txos from the
   937  	// database and using that information to unspend all of the spent txos
   938  	// and remove the utxos created by the blocks.
   939  	view := NewUtxoViewpoint()
   940  	view.SetBestHash(&oldBest.hash)
   941  	for e := detachNodes.Front(); e != nil; e = e.Next() {
   942  		n := e.Value.(*blockNode)
   943  		var block *btcutil.Block
   944  		err := b.db.View(func(dbTx database.Tx) error {
   945  			var err error
   946  			block, err = dbFetchBlockByNode(dbTx, n)
   947  			return err
   948  		})
   949  		if err != nil {
   950  			return err
   951  		}
   952  		if n.hash != *block.Hash() {
   953  			return AssertError(fmt.Sprintf("detach block node hash %v (height "+
   954  				"%v) does not match previous parent block hash %v", &n.hash,
   955  				n.height, block.Hash()))
   956  		}
   957  
   958  		// Load all of the utxos referenced by the block that aren't
   959  		// already in the view.
   960  		err = view.fetchInputUtxos(b.db, nil, block)
   961  		if err != nil {
   962  			return err
   963  		}
   964  
   965  		// Load all of the spent txos for the block from the spend
   966  		// journal.
   967  		var stxos []SpentTxOut
   968  		err = b.db.View(func(dbTx database.Tx) error {
   969  			stxos, err = dbFetchSpendJournalEntry(dbTx, block)
   970  			return err
   971  		})
   972  		if err != nil {
   973  			return err
   974  		}
   975  
   976  		// Store the loaded block and spend journal entry for later.
   977  		detachBlocks = append(detachBlocks, block)
   978  		detachSpentTxOuts = append(detachSpentTxOuts, stxos)
   979  
   980  		err = view.disconnectTransactions(b.db, block, stxos)
   981  		if err != nil {
   982  			return err
   983  		}
   984  
   985  		newBest = n.parent
   986  	}
   987  
   988  	// Set the fork point only if there are nodes to attach since otherwise
   989  	// blocks are only being disconnected and thus there is no fork point.
   990  	var forkNode *blockNode
   991  	if attachNodes.Len() > 0 {
   992  		forkNode = newBest
   993  	}
   994  
   995  	// Perform several checks to verify each block that needs to be attached
   996  	// to the main chain can be connected without violating any rules and
   997  	// without actually connecting the block.
   998  	//
   999  	// NOTE: These checks could be done directly when connecting a block,
  1000  	// however the downside to that approach is that if any of these checks
  1001  	// fail after disconnecting some blocks or attaching others, all of the
  1002  	// operations have to be rolled back to get the chain back into the
  1003  	// state it was before the rule violation (or other failure).  There are
  1004  	// at least a couple of ways accomplish that rollback, but both involve
  1005  	// tweaking the chain and/or database.  This approach catches these
  1006  	// issues before ever modifying the chain.
  1007  	for e := attachNodes.Front(); e != nil; e = e.Next() {
  1008  		n := e.Value.(*blockNode)
  1009  
  1010  		var block *btcutil.Block
  1011  		err := b.db.View(func(dbTx database.Tx) error {
  1012  			var err error
  1013  			block, err = dbFetchBlockByNode(dbTx, n)
  1014  			return err
  1015  		})
  1016  		if err != nil {
  1017  			return err
  1018  		}
  1019  
  1020  		// Store the loaded block for later.
  1021  		attachBlocks = append(attachBlocks, block)
  1022  
  1023  		// Skip checks if node has already been fully validated. Although
  1024  		// checkConnectBlock gets skipped, we still need to update the UTXO
  1025  		// view.
  1026  		if b.index.NodeStatus(n).KnownValid() {
  1027  			err = view.fetchInputUtxos(b.db, nil, block)
  1028  			if err != nil {
  1029  				return err
  1030  			}
  1031  			err = view.connectTransactions(block, nil)
  1032  			if err != nil {
  1033  				return err
  1034  			}
  1035  
  1036  			newBest = n
  1037  			continue
  1038  		}
  1039  
  1040  		// Notice the spent txout details are not requested here and
  1041  		// thus will not be generated.  This is done because the state
  1042  		// is not being immediately written to the database, so it is
  1043  		// not needed.
  1044  		//
  1045  		// In the case the block is determined to be invalid due to a
  1046  		// rule violation, mark it as invalid and mark all of its
  1047  		// descendants as having an invalid ancestor.
  1048  		err = b.checkConnectBlock(n, block, view, nil)
  1049  		if err != nil {
  1050  			if _, ok := err.(RuleError); ok {
  1051  				b.index.SetStatusFlags(n, statusValidateFailed)
  1052  				for de := e.Next(); de != nil; de = de.Next() {
  1053  					dn := de.Value.(*blockNode)
  1054  					b.index.SetStatusFlags(dn, statusInvalidAncestor)
  1055  				}
  1056  			}
  1057  			return err
  1058  		}
  1059  		b.index.SetStatusFlags(n, statusValid)
  1060  
  1061  		newBest = n
  1062  	}
  1063  
  1064  	// Reset the view for the actual connection code below.  This is
  1065  	// required because the view was previously modified when checking if
  1066  	// the reorg would be successful and the connection code requires the
  1067  	// view to be valid from the viewpoint of each block being connected or
  1068  	// disconnected.
  1069  	view = NewUtxoViewpoint()
  1070  	view.SetBestHash(&b.bestChain.Tip().hash)
  1071  
  1072  	// Disconnect blocks from the main chain.
  1073  	for i, e := 0, detachNodes.Front(); e != nil; i, e = i+1, e.Next() {
  1074  		n := e.Value.(*blockNode)
  1075  		block := detachBlocks[i]
  1076  
  1077  		// Load all of the utxos referenced by the block that aren't
  1078  		// already in the view.
  1079  		err := view.fetchInputUtxos(b.db, nil, block)
  1080  		if err != nil {
  1081  			return err
  1082  		}
  1083  
  1084  		// Update the view to unspend all of the spent txos and remove
  1085  		// the utxos created by the block.
  1086  		err = view.disconnectTransactions(b.db, block,
  1087  			detachSpentTxOuts[i])
  1088  		if err != nil {
  1089  			return err
  1090  		}
  1091  
  1092  		// Update the database and chain state.
  1093  		err = b.disconnectBlock(n, block, view)
  1094  		if err != nil {
  1095  			return err
  1096  		}
  1097  	}
  1098  
  1099  	// Connect the new best chain blocks.
  1100  	for i, e := 0, attachNodes.Front(); e != nil; i, e = i+1, e.Next() {
  1101  		n := e.Value.(*blockNode)
  1102  		block := attachBlocks[i]
  1103  
  1104  		// Load all of the utxos referenced by the block that aren't
  1105  		// already in the view.
  1106  		err := view.fetchInputUtxos(b.db, nil, block)
  1107  		if err != nil {
  1108  			return err
  1109  		}
  1110  
  1111  		// Update the view to mark all utxos referenced by the block
  1112  		// as spent and add all transactions being created by this block
  1113  		// to it.  Also, provide an stxo slice so the spent txout
  1114  		// details are generated.
  1115  		stxos := make([]SpentTxOut, 0, countSpentOutputs(block))
  1116  		err = view.connectTransactions(block, &stxos)
  1117  		if err != nil {
  1118  			return err
  1119  		}
  1120  
  1121  		// Update the database and chain state.
  1122  		err = b.connectBlock(n, block, view, stxos)
  1123  		if err != nil {
  1124  			return err
  1125  		}
  1126  	}
  1127  
  1128  	// We call the flush at the end to update the last flush hash to the new
  1129  	// best tip.
  1130  	err = b.db.Update(func(dbTx database.Tx) error {
  1131  		return b.utxoCache.flush(dbTx, FlushRequired, b.BestSnapshot())
  1132  	})
  1133  	if err != nil {
  1134  		return err
  1135  	}
  1136  
  1137  	// Log the point where the chain forked and old and new best chain
  1138  	// heads.
  1139  	if forkNode != nil {
  1140  		log.Infof("REORGANIZE: Chain forks at %v (height %v)", forkNode.hash,
  1141  			forkNode.height)
  1142  	}
  1143  	log.Infof("REORGANIZE: Old best chain head was %v (height %v)",
  1144  		&oldBest.hash, oldBest.height)
  1145  	log.Infof("REORGANIZE: New best chain head is %v (height %v)",
  1146  		newBest.hash, newBest.height)
  1147  
  1148  	return nil
  1149  }
  1150  
  1151  // connectBestChain handles connecting the passed block to the chain while
  1152  // respecting proper chain selection according to the chain with the most
  1153  // proof of work.  In the typical case, the new block simply extends the main
  1154  // chain.  However, it may also be extending (or creating) a side chain (fork)
  1155  // which may or may not end up becoming the main chain depending on which fork
  1156  // cumulatively has the most proof of work.  It returns whether or not the block
  1157  // ended up on the main chain (either due to extending the main chain or causing
  1158  // a reorganization to become the main chain).
  1159  //
  1160  // The flags modify the behavior of this function as follows:
  1161  //   - BFFastAdd: Avoids several expensive transaction validation operations.
  1162  //     This is useful when using checkpoints.
  1163  //
  1164  // This function MUST be called with the chain state lock held (for writes).
  1165  func (b *BlockChain) connectBestChain(node *blockNode, block *btcutil.Block, flags BehaviorFlags) (bool, error) {
  1166  	fastAdd := flags&BFFastAdd == BFFastAdd
  1167  
  1168  	flushIndexState := func() {
  1169  		// Intentionally ignore errors writing updated node status to DB. If
  1170  		// it fails to write, it's not the end of the world. If the block is
  1171  		// valid, we flush in connectBlock and if the block is invalid, the
  1172  		// worst that can happen is we revalidate the block after a restart.
  1173  		if writeErr := b.index.flushToDB(); writeErr != nil {
  1174  			log.Warnf("Error flushing block index changes to disk: %v",
  1175  				writeErr)
  1176  		}
  1177  	}
  1178  
  1179  	// We are extending the main (best) chain with a new block.  This is the
  1180  	// most common case.
  1181  	parentHash := &block.MsgBlock().Header.PrevBlock
  1182  	if parentHash.IsEqual(&b.bestChain.Tip().hash) {
  1183  		// Skip checks if node has already been fully validated.
  1184  		fastAdd = fastAdd || b.index.NodeStatus(node).KnownValid()
  1185  
  1186  		// Perform several checks to verify the block can be connected
  1187  		// to the main chain without violating any rules and without
  1188  		// actually connecting the block.
  1189  		if !fastAdd {
  1190  			// We create a viewpoint here to avoid spending or adding new
  1191  			// coins to the utxo cache.
  1192  			//
  1193  			// checkConnectBlock spends and adds utxos before doing the
  1194  			// signature validation and if the signature validation fails,
  1195  			// we would be forced to undo the utxo cache.
  1196  			//
  1197  			// TODO (kcalvinalvin): Doing all of the validation before connecting
  1198  			// the tx inside check connect block would allow us to pass the utxo
  1199  			// cache directly to the check connect block.  This would save on the
  1200  			// expensive memory allocation done by fetch input utxos.
  1201  			view := NewUtxoViewpoint()
  1202  			view.SetBestHash(parentHash)
  1203  			err := b.checkConnectBlock(node, block, view, nil)
  1204  			if err == nil {
  1205  				b.index.SetStatusFlags(node, statusValid)
  1206  			} else if _, ok := err.(RuleError); ok {
  1207  				b.index.SetStatusFlags(node, statusValidateFailed)
  1208  			} else {
  1209  				return false, err
  1210  			}
  1211  
  1212  			flushIndexState()
  1213  
  1214  			if err != nil {
  1215  				return false, err
  1216  			}
  1217  		}
  1218  
  1219  		// Connect the transactions to the cache.  All the txs are considered valid
  1220  		// at this point as they have passed validation or was considered valid already.
  1221  		stxos := make([]SpentTxOut, 0, countSpentOutputs(block))
  1222  		err := b.utxoCache.connectTransactions(block, &stxos)
  1223  		if err != nil {
  1224  			return false, err
  1225  		}
  1226  
  1227  		// Connect the block to the main chain.
  1228  		err = b.connectBlock(node, block, nil, stxos)
  1229  		if err != nil {
  1230  			// If we got hit with a rule error, then we'll mark
  1231  			// that status of the block as invalid and flush the
  1232  			// index state to disk before returning with the error.
  1233  			if _, ok := err.(RuleError); ok {
  1234  				b.index.SetStatusFlags(
  1235  					node, statusValidateFailed,
  1236  				)
  1237  			}
  1238  
  1239  			flushIndexState()
  1240  
  1241  			return false, err
  1242  		}
  1243  
  1244  		// If this is fast add, or this block node isn't yet marked as
  1245  		// valid, then we'll update its status and flush the state to
  1246  		// disk again.
  1247  		if fastAdd || !b.index.NodeStatus(node).KnownValid() {
  1248  			b.index.SetStatusFlags(node, statusValid)
  1249  			flushIndexState()
  1250  		}
  1251  
  1252  		return true, nil
  1253  	}
  1254  	if fastAdd {
  1255  		log.Warnf("fastAdd set in the side chain case? %v\n",
  1256  			block.Hash())
  1257  	}
  1258  
  1259  	// We're extending (or creating) a side chain, but the cumulative
  1260  	// work for this new side chain is not enough to make it the new chain.
  1261  	if node.workSum.Cmp(b.bestChain.Tip().workSum) <= 0 {
  1262  		// Log information about how the block is forking the chain.
  1263  		fork := b.bestChain.FindFork(node)
  1264  		if fork.hash.IsEqual(parentHash) {
  1265  			log.Infof("FORK: Block %v forks the chain at height %d"+
  1266  				"/block %v, but does not cause a reorganize",
  1267  				node.hash, fork.height, fork.hash)
  1268  		} else {
  1269  			log.Infof("EXTEND FORK: Block %v extends a side chain "+
  1270  				"which forks the chain at height %d/block %v",
  1271  				node.hash, fork.height, fork.hash)
  1272  		}
  1273  
  1274  		return false, nil
  1275  	}
  1276  
  1277  	// We're extending (or creating) a side chain and the cumulative work
  1278  	// for this new side chain is more than the old best chain, so this side
  1279  	// chain needs to become the main chain.  In order to accomplish that,
  1280  	// find the common ancestor of both sides of the fork, disconnect the
  1281  	// blocks that form the (now) old fork from the main chain, and attach
  1282  	// the blocks that form the new chain to the main chain starting at the
  1283  	// common ancenstor (the point where the chain forked).
  1284  	detachNodes, attachNodes := b.getReorganizeNodes(node)
  1285  
  1286  	// Reorganize the chain.
  1287  	log.Infof("REORGANIZE: Block %v is causing a reorganize.", node.hash)
  1288  	err := b.reorganizeChain(detachNodes, attachNodes)
  1289  
  1290  	// Either getReorganizeNodes or reorganizeChain could have made unsaved
  1291  	// changes to the block index, so flush regardless of whether there was an
  1292  	// error. The index would only be dirty if the block failed to connect, so
  1293  	// we can ignore any errors writing.
  1294  	if writeErr := b.index.flushToDB(); writeErr != nil {
  1295  		log.Warnf("Error flushing block index changes to disk: %v", writeErr)
  1296  	}
  1297  
  1298  	return err == nil, err
  1299  }
  1300  
  1301  // isCurrent returns whether or not the chain believes it is current.  Several
  1302  // factors are used to guess, but the key factors that allow the chain to
  1303  // believe it is current are:
  1304  //   - Latest block height is after the latest checkpoint (if enabled)
  1305  //   - Latest block has a timestamp newer than 24 hours ago
  1306  //
  1307  // This function MUST be called with the chain state lock held (for reads).
  1308  func (b *BlockChain) isCurrent() bool {
  1309  	// Not current if the latest main (best) chain height is before the
  1310  	// latest known good checkpoint (when checkpoints are enabled).
  1311  	checkpoint := b.LatestCheckpoint()
  1312  	if checkpoint != nil && b.bestChain.Tip().height < checkpoint.Height {
  1313  		return false
  1314  	}
  1315  
  1316  	// Not current if the latest best block has a timestamp before 24 hours
  1317  	// ago.
  1318  	//
  1319  	// The chain appears to be current if none of the checks reported
  1320  	// otherwise.
  1321  	minus24Hours := b.timeSource.AdjustedTime().Add(-24 * time.Hour).Unix()
  1322  	return b.bestChain.Tip().timestamp >= minus24Hours
  1323  }
  1324  
  1325  // IsCurrent returns whether or not the chain believes it is current.  Several
  1326  // factors are used to guess, but the key factors that allow the chain to
  1327  // believe it is current are:
  1328  //   - Latest block height is after the latest checkpoint (if enabled)
  1329  //   - Latest block has a timestamp newer than 24 hours ago
  1330  //
  1331  // This function is safe for concurrent access.
  1332  func (b *BlockChain) IsCurrent() bool {
  1333  	b.chainLock.RLock()
  1334  	defer b.chainLock.RUnlock()
  1335  
  1336  	return b.isCurrent()
  1337  }
  1338  
  1339  // BestSnapshot returns information about the current best chain block and
  1340  // related state as of the current point in time.  The returned instance must be
  1341  // treated as immutable since it is shared by all callers.
  1342  //
  1343  // This function is safe for concurrent access.
  1344  func (b *BlockChain) BestSnapshot() *BestState {
  1345  	b.stateLock.RLock()
  1346  	snapshot := b.stateSnapshot
  1347  	b.stateLock.RUnlock()
  1348  	return snapshot
  1349  }
  1350  
  1351  // TipStatus is the status of a chain tip.
  1352  type TipStatus byte
  1353  
  1354  const (
  1355  	// StatusUnknown indicates that the tip status isn't any of the defined
  1356  	// statuses.
  1357  	StatusUnknown TipStatus = iota
  1358  
  1359  	// StatusActive indicates that the tip is considered active and is in
  1360  	// the best chain.
  1361  	StatusActive
  1362  
  1363  	// StatusInvalid indicates that this tip or any of the ancestors of this
  1364  	// tip are invalid.
  1365  	StatusInvalid
  1366  
  1367  	// StatusValidFork is given if:
  1368  	// 1: Not a part of the best chain.
  1369  	// 2: Is not invalid.
  1370  	// 3: Has the block data stored to disk.
  1371  	StatusValidFork
  1372  )
  1373  
  1374  // String returns the status flags as string.
  1375  func (ts TipStatus) String() string {
  1376  	switch ts {
  1377  	case StatusActive:
  1378  		return "active"
  1379  	case StatusInvalid:
  1380  		return "invalid"
  1381  	case StatusValidFork:
  1382  		return "valid-fork"
  1383  	}
  1384  	return fmt.Sprintf("unknown: %b", ts)
  1385  }
  1386  
  1387  // ChainTip represents the last block in a branch of the block tree.
  1388  type ChainTip struct {
  1389  	// Height of the tip.
  1390  	Height int32
  1391  
  1392  	// BlockHash hash of the tip.
  1393  	BlockHash chainhash.Hash
  1394  
  1395  	// BranchLen is length of the fork point of this chain from the main chain.
  1396  	// Returns 0 if the chain tip is a part of the best chain.
  1397  	BranchLen int32
  1398  
  1399  	// Status is the validity status of the branch this tip is in.
  1400  	Status TipStatus
  1401  }
  1402  
  1403  // ChainTips returns all the chain tips the node itself is aware of.  Each tip is
  1404  // represented by its height, block hash, branch length, and status.
  1405  //
  1406  // This function is safe for concurrent access.
  1407  func (b *BlockChain) ChainTips() []ChainTip {
  1408  	b.chainLock.RLock()
  1409  	defer b.chainLock.RUnlock()
  1410  
  1411  	// Grab all the inactive tips.
  1412  	tips := b.index.InactiveTips(b.bestChain)
  1413  
  1414  	// Add the current tip.
  1415  	tips = append(tips, b.bestChain.Tip())
  1416  
  1417  	chainTips := make([]ChainTip, 0, len(tips))
  1418  
  1419  	// Go through all the tips and grab the height, hash, branch length, and the block
  1420  	// status.
  1421  	for _, tip := range tips {
  1422  		var status TipStatus
  1423  		switch {
  1424  		// The tip is considered active if it's in the best chain.
  1425  		case b.bestChain.Contains(tip):
  1426  			status = StatusActive
  1427  
  1428  		// This block or any of the ancestors of this block are invalid.
  1429  		case tip.status.KnownInvalid():
  1430  			status = StatusInvalid
  1431  
  1432  		// If the tip meets the following criteria:
  1433  		// 1: Not a part of the best chain.
  1434  		// 2: Is not invalid.
  1435  		// 3: Has the block data stored to disk.
  1436  		//
  1437  		// The tip is considered a valid fork.
  1438  		//
  1439  		// We can check if a tip is a valid-fork by checking that
  1440  		// its data is available. Since the behavior is to give a
  1441  		// block node the statusDataStored status once it passes
  1442  		// the proof of work checks and basic chain validity checks.
  1443  		//
  1444  		// We can't use the KnownValid status since it's only given
  1445  		// to blocks that passed the validation AND were a part of
  1446  		// the bestChain.
  1447  		case tip.status.HaveData():
  1448  			status = StatusValidFork
  1449  		}
  1450  
  1451  		chainTip := ChainTip{
  1452  			Height:    tip.height,
  1453  			BlockHash: tip.hash,
  1454  			BranchLen: tip.height - b.bestChain.FindFork(tip).height,
  1455  			Status:    status,
  1456  		}
  1457  
  1458  		chainTips = append(chainTips, chainTip)
  1459  	}
  1460  
  1461  	return chainTips
  1462  }
  1463  
  1464  // HeaderByHash returns the block header identified by the given hash or an
  1465  // error if it doesn't exist. Note that this will return headers from both the
  1466  // main and side chains.
  1467  func (b *BlockChain) HeaderByHash(hash *chainhash.Hash) (wire.BlockHeader, error) {
  1468  	node := b.index.LookupNode(hash)
  1469  	if node == nil {
  1470  		err := fmt.Errorf("block %s is not known", hash)
  1471  		return wire.BlockHeader{}, err
  1472  	}
  1473  
  1474  	return node.Header(), nil
  1475  }
  1476  
  1477  // MainChainHasBlock returns whether or not the block with the given hash is in
  1478  // the main chain.
  1479  //
  1480  // This function is safe for concurrent access.
  1481  func (b *BlockChain) MainChainHasBlock(hash *chainhash.Hash) bool {
  1482  	node := b.index.LookupNode(hash)
  1483  	return node != nil && b.bestChain.Contains(node)
  1484  }
  1485  
  1486  // BlockLocatorFromHash returns a block locator for the passed block hash.
  1487  // See BlockLocator for details on the algorithm used to create a block locator.
  1488  //
  1489  // In addition to the general algorithm referenced above, this function will
  1490  // return the block locator for the latest known tip of the main (best) chain if
  1491  // the passed hash is not currently known.
  1492  //
  1493  // This function is safe for concurrent access.
  1494  func (b *BlockChain) BlockLocatorFromHash(hash *chainhash.Hash) BlockLocator {
  1495  	b.chainLock.RLock()
  1496  	node := b.index.LookupNode(hash)
  1497  	locator := b.bestChain.blockLocator(node)
  1498  	b.chainLock.RUnlock()
  1499  	return locator
  1500  }
  1501  
  1502  // LatestBlockLocator returns a block locator for the latest known tip of the
  1503  // main (best) chain.
  1504  //
  1505  // This function is safe for concurrent access.
  1506  func (b *BlockChain) LatestBlockLocator() (BlockLocator, error) {
  1507  	b.chainLock.RLock()
  1508  	locator := b.bestChain.BlockLocator(nil)
  1509  	b.chainLock.RUnlock()
  1510  	return locator, nil
  1511  }
  1512  
  1513  // BlockHeightByHash returns the height of the block with the given hash in the
  1514  // main chain.
  1515  //
  1516  // This function is safe for concurrent access.
  1517  func (b *BlockChain) BlockHeightByHash(hash *chainhash.Hash) (int32, error) {
  1518  	node := b.index.LookupNode(hash)
  1519  	if node == nil || !b.bestChain.Contains(node) {
  1520  		str := fmt.Sprintf("block %s is not in the main chain", hash)
  1521  		return 0, errNotInMainChain(str)
  1522  	}
  1523  
  1524  	return node.height, nil
  1525  }
  1526  
  1527  // BlockHashByHeight returns the hash of the block at the given height in the
  1528  // main chain.
  1529  //
  1530  // This function is safe for concurrent access.
  1531  func (b *BlockChain) BlockHashByHeight(blockHeight int32) (*chainhash.Hash, error) {
  1532  	node := b.bestChain.NodeByHeight(blockHeight)
  1533  	if node == nil {
  1534  		str := fmt.Sprintf("no block at height %d exists", blockHeight)
  1535  		return nil, errNotInMainChain(str)
  1536  
  1537  	}
  1538  
  1539  	return &node.hash, nil
  1540  }
  1541  
  1542  // HeightRange returns a range of block hashes for the given start and end
  1543  // heights.  It is inclusive of the start height and exclusive of the end
  1544  // height.  The end height will be limited to the current main chain height.
  1545  //
  1546  // This function is safe for concurrent access.
  1547  func (b *BlockChain) HeightRange(startHeight, endHeight int32) ([]chainhash.Hash, error) {
  1548  	// Ensure requested heights are sane.
  1549  	if startHeight < 0 {
  1550  		return nil, fmt.Errorf("start height of fetch range must not "+
  1551  			"be less than zero - got %d", startHeight)
  1552  	}
  1553  	if endHeight < startHeight {
  1554  		return nil, fmt.Errorf("end height of fetch range must not "+
  1555  			"be less than the start height - got start %d, end %d",
  1556  			startHeight, endHeight)
  1557  	}
  1558  
  1559  	// There is nothing to do when the start and end heights are the same,
  1560  	// so return now to avoid the chain view lock.
  1561  	if startHeight == endHeight {
  1562  		return nil, nil
  1563  	}
  1564  
  1565  	// Grab a lock on the chain view to prevent it from changing due to a
  1566  	// reorg while building the hashes.
  1567  	b.bestChain.mtx.Lock()
  1568  	defer b.bestChain.mtx.Unlock()
  1569  
  1570  	// When the requested start height is after the most recent best chain
  1571  	// height, there is nothing to do.
  1572  	latestHeight := b.bestChain.tip().height
  1573  	if startHeight > latestHeight {
  1574  		return nil, nil
  1575  	}
  1576  
  1577  	// Limit the ending height to the latest height of the chain.
  1578  	if endHeight > latestHeight+1 {
  1579  		endHeight = latestHeight + 1
  1580  	}
  1581  
  1582  	// Fetch as many as are available within the specified range.
  1583  	hashes := make([]chainhash.Hash, 0, endHeight-startHeight)
  1584  	for i := startHeight; i < endHeight; i++ {
  1585  		hashes = append(hashes, b.bestChain.nodeByHeight(i).hash)
  1586  	}
  1587  	return hashes, nil
  1588  }
  1589  
  1590  // HeightToHashRange returns a range of block hashes for the given start height
  1591  // and end hash, inclusive on both ends.  The hashes are for all blocks that are
  1592  // ancestors of endHash with height greater than or equal to startHeight.  The
  1593  // end hash must belong to a block that is known to be valid.
  1594  //
  1595  // This function is safe for concurrent access.
  1596  func (b *BlockChain) HeightToHashRange(startHeight int32,
  1597  	endHash *chainhash.Hash, maxResults int) ([]chainhash.Hash, error) {
  1598  
  1599  	endNode := b.index.LookupNode(endHash)
  1600  	if endNode == nil {
  1601  		return nil, fmt.Errorf("no known block header with hash %v", endHash)
  1602  	}
  1603  	if !b.index.NodeStatus(endNode).KnownValid() {
  1604  		return nil, fmt.Errorf("block %v is not yet validated", endHash)
  1605  	}
  1606  	endHeight := endNode.height
  1607  
  1608  	if startHeight < 0 {
  1609  		return nil, fmt.Errorf("start height (%d) is below 0", startHeight)
  1610  	}
  1611  	if startHeight > endHeight {
  1612  		return nil, fmt.Errorf("start height (%d) is past end height (%d)",
  1613  			startHeight, endHeight)
  1614  	}
  1615  
  1616  	resultsLength := int(endHeight - startHeight + 1)
  1617  	if resultsLength > maxResults {
  1618  		return nil, fmt.Errorf("number of results (%d) would exceed max (%d)",
  1619  			resultsLength, maxResults)
  1620  	}
  1621  
  1622  	// Walk backwards from endHeight to startHeight, collecting block hashes.
  1623  	node := endNode
  1624  	hashes := make([]chainhash.Hash, resultsLength)
  1625  	for i := resultsLength - 1; i >= 0; i-- {
  1626  		hashes[i] = node.hash
  1627  		node = node.parent
  1628  	}
  1629  	return hashes, nil
  1630  }
  1631  
  1632  // IntervalBlockHashes returns hashes for all blocks that are ancestors of
  1633  // endHash where the block height is a positive multiple of interval.
  1634  //
  1635  // This function is safe for concurrent access.
  1636  func (b *BlockChain) IntervalBlockHashes(endHash *chainhash.Hash, interval int,
  1637  ) ([]chainhash.Hash, error) {
  1638  
  1639  	endNode := b.index.LookupNode(endHash)
  1640  	if endNode == nil {
  1641  		return nil, fmt.Errorf("no known block header with hash %v", endHash)
  1642  	}
  1643  	if !b.index.NodeStatus(endNode).KnownValid() {
  1644  		return nil, fmt.Errorf("block %v is not yet validated", endHash)
  1645  	}
  1646  	endHeight := endNode.height
  1647  
  1648  	resultsLength := int(endHeight) / interval
  1649  	hashes := make([]chainhash.Hash, resultsLength)
  1650  
  1651  	b.bestChain.mtx.Lock()
  1652  	defer b.bestChain.mtx.Unlock()
  1653  
  1654  	blockNode := endNode
  1655  	for index := int(endHeight) / interval; index > 0; index-- {
  1656  		// Use the bestChain chainView for faster lookups once lookup intersects
  1657  		// the best chain.
  1658  		blockHeight := int32(index * interval)
  1659  		if b.bestChain.contains(blockNode) {
  1660  			blockNode = b.bestChain.nodeByHeight(blockHeight)
  1661  		} else {
  1662  			blockNode = blockNode.Ancestor(blockHeight)
  1663  		}
  1664  
  1665  		hashes[index-1] = blockNode.hash
  1666  	}
  1667  
  1668  	return hashes, nil
  1669  }
  1670  
  1671  // locateInventory returns the node of the block after the first known block in
  1672  // the locator along with the number of subsequent nodes needed to either reach
  1673  // the provided stop hash or the provided max number of entries.
  1674  //
  1675  // In addition, there are two special cases:
  1676  //
  1677  //   - When no locators are provided, the stop hash is treated as a request for
  1678  //     that block, so it will either return the node associated with the stop hash
  1679  //     if it is known, or nil if it is unknown
  1680  //   - When locators are provided, but none of them are known, nodes starting
  1681  //     after the genesis block will be returned
  1682  //
  1683  // This is primarily a helper function for the locateBlocks and locateHeaders
  1684  // functions.
  1685  //
  1686  // This function MUST be called with the chain state lock held (for reads).
  1687  func (b *BlockChain) locateInventory(locator BlockLocator, hashStop *chainhash.Hash, maxEntries uint32) (*blockNode, uint32) {
  1688  	// There are no block locators so a specific block is being requested
  1689  	// as identified by the stop hash.
  1690  	stopNode := b.index.LookupNode(hashStop)
  1691  	if len(locator) == 0 {
  1692  		if stopNode == nil {
  1693  			// No blocks with the stop hash were found so there is
  1694  			// nothing to do.
  1695  			return nil, 0
  1696  		}
  1697  		return stopNode, 1
  1698  	}
  1699  
  1700  	// Find the most recent locator block hash in the main chain.  In the
  1701  	// case none of the hashes in the locator are in the main chain, fall
  1702  	// back to the genesis block.
  1703  	startNode := b.bestChain.Genesis()
  1704  	for _, hash := range locator {
  1705  		node := b.index.LookupNode(hash)
  1706  		if node != nil && b.bestChain.Contains(node) {
  1707  			startNode = node
  1708  			break
  1709  		}
  1710  	}
  1711  
  1712  	// Start at the block after the most recently known block.  When there
  1713  	// is no next block it means the most recently known block is the tip of
  1714  	// the best chain, so there is nothing more to do.
  1715  	startNode = b.bestChain.Next(startNode)
  1716  	if startNode == nil {
  1717  		return nil, 0
  1718  	}
  1719  
  1720  	// Calculate how many entries are needed.
  1721  	total := uint32((b.bestChain.Tip().height - startNode.height) + 1)
  1722  	if stopNode != nil && b.bestChain.Contains(stopNode) &&
  1723  		stopNode.height >= startNode.height {
  1724  
  1725  		total = uint32((stopNode.height - startNode.height) + 1)
  1726  	}
  1727  	if total > maxEntries {
  1728  		total = maxEntries
  1729  	}
  1730  
  1731  	return startNode, total
  1732  }
  1733  
  1734  // locateBlocks returns the hashes of the blocks after the first known block in
  1735  // the locator until the provided stop hash is reached, or up to the provided
  1736  // max number of block hashes.
  1737  //
  1738  // See the comment on the exported function for more details on special cases.
  1739  //
  1740  // This function MUST be called with the chain state lock held (for reads).
  1741  func (b *BlockChain) locateBlocks(locator BlockLocator, hashStop *chainhash.Hash, maxHashes uint32) []chainhash.Hash {
  1742  	// Find the node after the first known block in the locator and the
  1743  	// total number of nodes after it needed while respecting the stop hash
  1744  	// and max entries.
  1745  	node, total := b.locateInventory(locator, hashStop, maxHashes)
  1746  	if total == 0 {
  1747  		return nil
  1748  	}
  1749  
  1750  	// Populate and return the found hashes.
  1751  	hashes := make([]chainhash.Hash, 0, total)
  1752  	for i := uint32(0); i < total; i++ {
  1753  		hashes = append(hashes, node.hash)
  1754  		node = b.bestChain.Next(node)
  1755  	}
  1756  	return hashes
  1757  }
  1758  
  1759  // LocateBlocks returns the hashes of the blocks after the first known block in
  1760  // the locator until the provided stop hash is reached, or up to the provided
  1761  // max number of block hashes.
  1762  //
  1763  // In addition, there are two special cases:
  1764  //
  1765  //   - When no locators are provided, the stop hash is treated as a request for
  1766  //     that block, so it will either return the stop hash itself if it is known,
  1767  //     or nil if it is unknown
  1768  //   - When locators are provided, but none of them are known, hashes starting
  1769  //     after the genesis block will be returned
  1770  //
  1771  // This function is safe for concurrent access.
  1772  func (b *BlockChain) LocateBlocks(locator BlockLocator, hashStop *chainhash.Hash, maxHashes uint32) []chainhash.Hash {
  1773  	b.chainLock.RLock()
  1774  	hashes := b.locateBlocks(locator, hashStop, maxHashes)
  1775  	b.chainLock.RUnlock()
  1776  	return hashes
  1777  }
  1778  
  1779  // locateHeaders returns the headers of the blocks after the first known block
  1780  // in the locator until the provided stop hash is reached, or up to the provided
  1781  // max number of block headers.
  1782  //
  1783  // See the comment on the exported function for more details on special cases.
  1784  //
  1785  // This function MUST be called with the chain state lock held (for reads).
  1786  func (b *BlockChain) locateHeaders(locator BlockLocator, hashStop *chainhash.Hash, maxHeaders uint32) []wire.BlockHeader {
  1787  	// Find the node after the first known block in the locator and the
  1788  	// total number of nodes after it needed while respecting the stop hash
  1789  	// and max entries.
  1790  	node, total := b.locateInventory(locator, hashStop, maxHeaders)
  1791  	if total == 0 {
  1792  		return nil
  1793  	}
  1794  
  1795  	// Populate and return the found headers.
  1796  	headers := make([]wire.BlockHeader, 0, total)
  1797  	for i := uint32(0); i < total; i++ {
  1798  		headers = append(headers, node.Header())
  1799  		node = b.bestChain.Next(node)
  1800  	}
  1801  	return headers
  1802  }
  1803  
  1804  // LocateHeaders returns the headers of the blocks after the first known block
  1805  // in the locator until the provided stop hash is reached, or up to a max of
  1806  // wire.MaxBlockHeadersPerMsg headers.
  1807  //
  1808  // In addition, there are two special cases:
  1809  //
  1810  //   - When no locators are provided, the stop hash is treated as a request for
  1811  //     that header, so it will either return the header for the stop hash itself
  1812  //     if it is known, or nil if it is unknown
  1813  //   - When locators are provided, but none of them are known, headers starting
  1814  //     after the genesis block will be returned
  1815  //
  1816  // This function is safe for concurrent access.
  1817  func (b *BlockChain) LocateHeaders(locator BlockLocator, hashStop *chainhash.Hash) []wire.BlockHeader {
  1818  	b.chainLock.RLock()
  1819  	headers := b.locateHeaders(locator, hashStop, wire.MaxBlockHeadersPerMsg)
  1820  	b.chainLock.RUnlock()
  1821  	return headers
  1822  }
  1823  
  1824  // IndexManager provides a generic interface that the is called when blocks are
  1825  // connected and disconnected to and from the tip of the main chain for the
  1826  // purpose of supporting optional indexes.
  1827  type IndexManager interface {
  1828  	// Init is invoked during chain initialize in order to allow the index
  1829  	// manager to initialize itself and any indexes it is managing.  The
  1830  	// channel parameter specifies a channel the caller can close to signal
  1831  	// that the process should be interrupted.  It can be nil if that
  1832  	// behavior is not desired.
  1833  	Init(*BlockChain, <-chan struct{}) error
  1834  
  1835  	// ConnectBlock is invoked when a new block has been connected to the
  1836  	// main chain. The set of output spent within a block is also passed in
  1837  	// so indexers can access the previous output scripts input spent if
  1838  	// required.
  1839  	ConnectBlock(database.Tx, *btcutil.Block, []SpentTxOut) error
  1840  
  1841  	// DisconnectBlock is invoked when a block has been disconnected from
  1842  	// the main chain. The set of outputs scripts that were spent within
  1843  	// this block is also returned so indexers can clean up the prior index
  1844  	// state for this block.
  1845  	DisconnectBlock(database.Tx, *btcutil.Block, []SpentTxOut) error
  1846  }
  1847  
  1848  // Config is a descriptor which specifies the blockchain instance configuration.
  1849  type Config struct {
  1850  	// DB defines the database which houses the blocks and will be used to
  1851  	// store all metadata created by this package such as the utxo set.
  1852  	//
  1853  	// This field is required.
  1854  	DB database.DB
  1855  
  1856  	// The maximum size in bytes of the UTXO cache.
  1857  	//
  1858  	// This field is required.
  1859  	UtxoCacheMaxSize uint64
  1860  
  1861  	// Interrupt specifies a channel the caller can close to signal that
  1862  	// long running operations, such as catching up indexes or performing
  1863  	// database migrations, should be interrupted.
  1864  	//
  1865  	// This field can be nil if the caller does not desire the behavior.
  1866  	Interrupt <-chan struct{}
  1867  
  1868  	// ChainParams identifies which chain parameters the chain is associated
  1869  	// with.
  1870  	//
  1871  	// This field is required.
  1872  	ChainParams *chaincfg.Params
  1873  
  1874  	// Checkpoints hold caller-defined checkpoints that should be added to
  1875  	// the default checkpoints in ChainParams.  Checkpoints must be sorted
  1876  	// by height.
  1877  	//
  1878  	// This field can be nil if the caller does not wish to specify any
  1879  	// checkpoints.
  1880  	Checkpoints []chaincfg.Checkpoint
  1881  
  1882  	// TimeSource defines the median time source to use for things such as
  1883  	// block processing and determining whether or not the chain is current.
  1884  	//
  1885  	// The caller is expected to keep a reference to the time source as well
  1886  	// and add time samples from other peers on the network so the local
  1887  	// time is adjusted to be in agreement with other peers.
  1888  	TimeSource MedianTimeSource
  1889  
  1890  	// SigCache defines a signature cache to use when when validating
  1891  	// signatures.  This is typically most useful when individual
  1892  	// transactions are already being validated prior to their inclusion in
  1893  	// a block such as what is usually done via a transaction memory pool.
  1894  	//
  1895  	// This field can be nil if the caller is not interested in using a
  1896  	// signature cache.
  1897  	SigCache *txscript.SigCache
  1898  
  1899  	// IndexManager defines an index manager to use when initializing the
  1900  	// chain and connecting and disconnecting blocks.
  1901  	//
  1902  	// This field can be nil if the caller does not wish to make use of an
  1903  	// index manager.
  1904  	IndexManager IndexManager
  1905  
  1906  	// HashCache defines a transaction hash mid-state cache to use when
  1907  	// validating transactions. This cache has the potential to greatly
  1908  	// speed up transaction validation as re-using the pre-calculated
  1909  	// mid-state eliminates the O(N^2) validation complexity due to the
  1910  	// SigHashAll flag.
  1911  	//
  1912  	// This field can be nil if the caller is not interested in using a
  1913  	// signature cache.
  1914  	HashCache *txscript.HashCache
  1915  
  1916  	// Prune specifies the target database usage (in bytes) the database
  1917  	// will target for with block files.  Prune at 0 specifies that no
  1918  	// blocks will be deleted.
  1919  	Prune uint64
  1920  }
  1921  
  1922  // New returns a BlockChain instance using the provided configuration details.
  1923  func New(config *Config) (*BlockChain, error) {
  1924  	// Enforce required config fields.
  1925  	if config.DB == nil {
  1926  		return nil, AssertError("blockchain.New database is nil")
  1927  	}
  1928  	if config.ChainParams == nil {
  1929  		return nil, AssertError("blockchain.New chain parameters nil")
  1930  	}
  1931  	if config.TimeSource == nil {
  1932  		return nil, AssertError("blockchain.New timesource is nil")
  1933  	}
  1934  
  1935  	// Generate a checkpoint by height map from the provided checkpoints
  1936  	// and assert the provided checkpoints are sorted by height as required.
  1937  	var checkpointsByHeight map[int32]*chaincfg.Checkpoint
  1938  	var prevCheckpointHeight int32
  1939  	if len(config.Checkpoints) > 0 {
  1940  		checkpointsByHeight = make(map[int32]*chaincfg.Checkpoint)
  1941  		for i := range config.Checkpoints {
  1942  			checkpoint := &config.Checkpoints[i]
  1943  			if checkpoint.Height <= prevCheckpointHeight {
  1944  				return nil, AssertError("blockchain.New " +
  1945  					"checkpoints are not sorted by height")
  1946  			}
  1947  
  1948  			checkpointsByHeight[checkpoint.Height] = checkpoint
  1949  			prevCheckpointHeight = checkpoint.Height
  1950  		}
  1951  	}
  1952  
  1953  	params := config.ChainParams
  1954  	targetTimespan := int64(params.TargetTimespan / time.Second)
  1955  	targetTimePerBlock := int64(params.TargetTimePerBlock / time.Second)
  1956  	adjustmentFactor := params.RetargetAdjustmentFactor
  1957  	b := BlockChain{
  1958  		checkpoints:         config.Checkpoints,
  1959  		checkpointsByHeight: checkpointsByHeight,
  1960  		db:                  config.DB,
  1961  		chainParams:         params,
  1962  		timeSource:          config.TimeSource,
  1963  		sigCache:            config.SigCache,
  1964  		indexManager:        config.IndexManager,
  1965  		minRetargetTimespan: targetTimespan / adjustmentFactor,
  1966  		maxRetargetTimespan: targetTimespan * adjustmentFactor,
  1967  		blocksPerRetarget:   int32(targetTimespan / targetTimePerBlock),
  1968  		index:               newBlockIndex(config.DB, params),
  1969  		utxoCache:           newUtxoCache(config.DB, config.UtxoCacheMaxSize),
  1970  		hashCache:           config.HashCache,
  1971  		bestChain:           newChainView(nil),
  1972  		orphans:             make(map[chainhash.Hash]*orphanBlock),
  1973  		prevOrphans:         make(map[chainhash.Hash][]*orphanBlock),
  1974  		warningCaches:       newThresholdCaches(vbNumBits),
  1975  		deploymentCaches:    newThresholdCaches(chaincfg.DefinedDeployments),
  1976  		pruneTarget:         config.Prune,
  1977  	}
  1978  
  1979  	// Ensure all the deployments are synchronized with our clock if
  1980  	// needed.
  1981  	for _, deployment := range b.chainParams.Deployments {
  1982  		deploymentStarter := deployment.DeploymentStarter
  1983  		if clockStarter, ok := deploymentStarter.(chaincfg.ClockConsensusDeploymentStarter); ok {
  1984  			clockStarter.SynchronizeClock(&b)
  1985  		}
  1986  
  1987  		deploymentEnder := deployment.DeploymentEnder
  1988  		if clockEnder, ok := deploymentEnder.(chaincfg.ClockConsensusDeploymentEnder); ok {
  1989  			clockEnder.SynchronizeClock(&b)
  1990  		}
  1991  	}
  1992  
  1993  	// Initialize the chain state from the passed database.  When the db
  1994  	// does not yet contain any chain state, both it and the chain state
  1995  	// will be initialized to contain only the genesis block.
  1996  	if err := b.initChainState(); err != nil {
  1997  		return nil, err
  1998  	}
  1999  
  2000  	// Perform any upgrades to the various chain-specific buckets as needed.
  2001  	if err := b.maybeUpgradeDbBuckets(config.Interrupt); err != nil {
  2002  		return nil, err
  2003  	}
  2004  
  2005  	// Initialize and catch up all of the currently active optional indexes
  2006  	// as needed.
  2007  	if config.IndexManager != nil {
  2008  		err := config.IndexManager.Init(&b, config.Interrupt)
  2009  		if err != nil {
  2010  			return nil, err
  2011  		}
  2012  	}
  2013  
  2014  	// Initialize rule change threshold state caches.
  2015  	if err := b.initThresholdCaches(); err != nil {
  2016  		return nil, err
  2017  	}
  2018  
  2019  	// Make sure the utxo state is catched up if it was left in an inconsistent
  2020  	// state.
  2021  	bestNode := b.bestChain.Tip()
  2022  	if err := b.InitConsistentState(bestNode, config.Interrupt); err != nil {
  2023  		return nil, err
  2024  	}
  2025  	log.Infof("Chain state (height %d, hash %v, totaltx %d, work %v)",
  2026  		bestNode.height, bestNode.hash, b.stateSnapshot.TotalTxns,
  2027  		bestNode.workSum)
  2028  
  2029  	return &b, nil
  2030  }
  2031  
  2032  // CachedStateSize returns the total size of the cached state of the blockchain
  2033  // in bytes.
  2034  func (b *BlockChain) CachedStateSize() uint64 {
  2035  	b.chainLock.Lock()
  2036  	defer b.chainLock.Unlock()
  2037  	return b.utxoCache.totalMemoryUsage()
  2038  }