1 // Copyright (c) 2013-2017 The btcsuite developers
2 // Use of this source code is governed by an ISC
3 // license that can be found in the LICENSE file.
13 "github.com/btcsuite/btcd/chaincfg"
14 "github.com/btcsuite/btcd/chaincfg/chainhash"
15 "github.com/btcsuite/btcd/database"
16 "github.com/btcsuite/btcd/txscript"
17 "github.com/btcsuite/btcd/wire"
18 "github.com/btcsuite/btcutil"
22 // maxOrphanBlocks is the maximum number of orphan blocks that can be
27 // BlockLocator is used to help locate a specific block. The algorithm for
28 // building the block locator is to add the hashes in reverse order until
29 // the genesis block is reached. In order to keep the list of locator hashes
30 // to a reasonable number of entries, first the most recent previous 12 block
31 // hashes are added, then the step is doubled each loop iteration to
32 // exponentially decrease the number of hashes as a function of the distance
33 // from the block being located.
35 // For example, assume a block chain with a side chain as depicted below:
36 // genesis -> 1 -> 2 -> ... -> 15 -> 16 -> 17 -> 18
39 // The block locator for block 17a would be the hashes of blocks:
40 // [17a 16a 15 14 13 12 11 10 9 8 7 6 4 genesis]
41 type BlockLocator []*chainhash.Hash
43 // orphanBlock represents a block that we don't yet have the parent for. It
44 // is a normal block plus an expiration time to prevent caching the orphan
46 type orphanBlock struct {
51 // BestState houses information about the current best block and other info
52 // related to the state of the main chain as it exists from the point of view of
53 // the current best block.
55 // The BestSnapshot method can be used to obtain access to this information
56 // in a concurrent safe manner and the data will not be changed out from under
57 // the caller when chain state changes occur as the function name implies.
58 // However, the returned snapshot must be treated as immutable since it is
59 // shared by all callers.
60 type BestState struct {
61 Hash chainhash.Hash // The hash of the block.
62 Height int32 // The height of the block.
63 Bits uint32 // The difficulty bits of the block.
64 BlockSize uint64 // The size of the block.
65 BlockWeight uint64 // The weight of the block.
66 NumTxns uint64 // The number of txns in the block.
67 TotalTxns uint64 // The total number of txns in the chain.
68 MedianTime time.Time // Median time as per CalcPastMedianTime.
71 // newBestState returns a new best stats instance for the given parameters.
72 func newBestState(node *blockNode, blockSize, blockWeight, numTxns,
73 totalTxns uint64, medianTime time.Time) *BestState {
80 BlockWeight: blockWeight,
83 MedianTime: medianTime,
87 // BlockChain provides functions for working with the bitcoin block chain.
88 // It includes functionality such as rejecting duplicate blocks, ensuring blocks
89 // follow all rules, orphan handling, checkpoint handling, and best chain
90 // selection with reorganization.
91 type BlockChain struct {
92 // The following fields are set when the instance is created and can't
93 // be changed afterwards, so there is no need to protect them with a
95 checkpoints []chaincfg.Checkpoint
96 checkpointsByHeight map[int32]*chaincfg.Checkpoint
98 chainParams *chaincfg.Params
99 timeSource MedianTimeSource
100 sigCache *txscript.SigCache
101 indexManager IndexManager
102 hashCache *txscript.HashCache
104 // The following fields are calculated based upon the provided chain
105 // parameters. They are also set when the instance is created and
106 // can't be changed afterwards, so there is no need to protect them with
108 minRetargetTimespan int64 // target timespan / adjustment factor
109 maxRetargetTimespan int64 // target timespan * adjustment factor
110 blocksPerRetarget int32 // target timespan / target time per block
112 // chainLock protects concurrent access to the vast majority of the
113 // fields in this struct below this point.
114 chainLock sync.RWMutex
116 // These fields are related to the memory block index. They both have
117 // their own locks, however they are often also protected by the chain
118 // lock to help prevent logic races when blocks are being processed.
120 // index houses the entire block index in memory. The block index is
121 // a tree-shaped structure.
123 // bestChain tracks the current active chain by making use of an
124 // efficient chain view into the block index.
128 // These fields are related to handling of orphan blocks. They are
129 // protected by a combination of the chain lock and the orphan lock.
130 orphanLock sync.RWMutex
131 orphans map[chainhash.Hash]*orphanBlock
132 prevOrphans map[chainhash.Hash][]*orphanBlock
133 oldestOrphan *orphanBlock
135 // These fields are related to checkpoint handling. They are protected
136 // by the chain lock.
137 nextCheckpoint *chaincfg.Checkpoint
138 checkpointNode *blockNode
140 // The state is used as a fairly efficient way to cache information
141 // about the current best chain state that is returned to callers when
142 // requested. It operates on the principle of MVCC such that any time a
143 // new block becomes the best block, the state pointer is replaced with
144 // a new struct and the old state is left untouched. In this way,
145 // multiple callers can be pointing to different best chain states.
146 // This is acceptable for most callers because the state is only being
147 // queried at a specific point in time.
149 // In addition, some of the fields are stored in the database so the
150 // chain state can be quickly reconstructed on load.
151 stateLock sync.RWMutex
152 stateSnapshot *BestState
154 // The following caches are used to efficiently keep track of the
155 // current deployment threshold state of each rule change deployment.
157 // This information is stored in the database so it can be quickly
158 // reconstructed on load.
160 // warningCaches caches the current deployment threshold state for blocks
161 // in each of the **possible** deployments. This is used in order to
162 // detect when new unrecognized rule changes are being voted on and/or
163 // have been activated such as will be the case when older versions of
164 // the software are being used
166 // deploymentCaches caches the current deployment threshold state for
167 // blocks in each of the actively defined deployments.
168 warningCaches []thresholdStateCache
169 deploymentCaches []thresholdStateCache
171 // The following fields are used to determine if certain warnings have
172 // already been shown.
174 // unknownRulesWarned refers to warnings due to unknown rules being
177 // unknownVersionsWarned refers to warnings due to unknown versions
179 unknownRulesWarned bool
180 unknownVersionsWarned bool
182 // The notifications field stores a slice of callbacks to be executed on
183 // certain blockchain events.
184 notificationsLock sync.RWMutex
185 notifications []NotificationCallback
188 // HaveBlock returns whether or not the chain instance has the block represented
189 // by the passed hash. This includes checking the various places a block can
190 // be like part of the main chain, on a side chain, or in the orphan pool.
192 // This function is safe for concurrent access.
193 func (b *BlockChain) HaveBlock(hash *chainhash.Hash) (bool, error) {
194 exists, err := b.blockExists(hash)
198 return exists || b.IsKnownOrphan(hash), nil
201 // IsKnownOrphan returns whether the passed hash is currently a known orphan.
202 // Keep in mind that only a limited number of orphans are held onto for a
203 // limited amount of time, so this function must not be used as an absolute
204 // way to test if a block is an orphan block. A full block (as opposed to just
205 // its hash) must be passed to ProcessBlock for that purpose. However, calling
206 // ProcessBlock with an orphan that already exists results in an error, so this
207 // function provides a mechanism for a caller to intelligently detect *recent*
208 // duplicate orphans and react accordingly.
210 // This function is safe for concurrent access.
211 func (b *BlockChain) IsKnownOrphan(hash *chainhash.Hash) bool {
212 // Protect concurrent access. Using a read lock only so multiple
213 // readers can query without blocking each other.
215 _, exists := b.orphans[*hash]
216 b.orphanLock.RUnlock()
221 // GetOrphanRoot returns the head of the chain for the provided hash from the
222 // map of orphan blocks.
224 // This function is safe for concurrent access.
225 func (b *BlockChain) GetOrphanRoot(hash *chainhash.Hash) *chainhash.Hash {
226 // Protect concurrent access. Using a read lock only so multiple
227 // readers can query without blocking each other.
229 defer b.orphanLock.RUnlock()
231 // Keep looping while the parent of each orphaned block is
232 // known and is an orphan itself.
236 orphan, exists := b.orphans[*prevHash]
240 orphanRoot = prevHash
241 prevHash = &orphan.block.MsgBlock().Header.PrevBlock
247 // removeOrphanBlock removes the passed orphan block from the orphan pool and
248 // previous orphan index.
249 func (b *BlockChain) removeOrphanBlock(orphan *orphanBlock) {
250 // Protect concurrent access.
252 defer b.orphanLock.Unlock()
254 // Remove the orphan block from the orphan pool.
255 orphanHash := orphan.block.Hash()
256 delete(b.orphans, *orphanHash)
258 // Remove the reference from the previous orphan index too. An indexing
259 // for loop is intentionally used over a range here as range does not
260 // reevaluate the slice on each iteration nor does it adjust the index
261 // for the modified slice.
262 prevHash := &orphan.block.MsgBlock().Header.PrevBlock
263 orphans := b.prevOrphans[*prevHash]
264 for i := 0; i < len(orphans); i++ {
265 hash := orphans[i].block.Hash()
266 if hash.IsEqual(orphanHash) {
267 copy(orphans[i:], orphans[i+1:])
268 orphans[len(orphans)-1] = nil
269 orphans = orphans[:len(orphans)-1]
273 b.prevOrphans[*prevHash] = orphans
275 // Remove the map entry altogether if there are no longer any orphans
276 // which depend on the parent hash.
277 if len(b.prevOrphans[*prevHash]) == 0 {
278 delete(b.prevOrphans, *prevHash)
282 // addOrphanBlock adds the passed block (which is already determined to be
283 // an orphan prior calling this function) to the orphan pool. It lazily cleans
284 // up any expired blocks so a separate cleanup poller doesn't need to be run.
285 // It also imposes a maximum limit on the number of outstanding orphan
286 // blocks and will remove the oldest received orphan block if the limit is
288 func (b *BlockChain) addOrphanBlock(block *btcutil.Block) {
289 // Remove expired orphan blocks.
290 for _, oBlock := range b.orphans {
291 if time.Now().After(oBlock.expiration) {
292 b.removeOrphanBlock(oBlock)
296 // Update the oldest orphan block pointer so it can be discarded
297 // in case the orphan pool fills up.
298 if b.oldestOrphan == nil || oBlock.expiration.Before(b.oldestOrphan.expiration) {
299 b.oldestOrphan = oBlock
303 // Limit orphan blocks to prevent memory exhaustion.
304 if len(b.orphans)+1 > maxOrphanBlocks {
305 // Remove the oldest orphan to make room for the new one.
306 b.removeOrphanBlock(b.oldestOrphan)
310 // Protect concurrent access. This is intentionally done here instead
311 // of near the top since removeOrphanBlock does its own locking and
312 // the range iterator is not invalidated by removing map entries.
314 defer b.orphanLock.Unlock()
316 // Insert the block into the orphan map with an expiration time
318 expiration := time.Now().Add(time.Hour)
319 oBlock := &orphanBlock{
321 expiration: expiration,
323 b.orphans[*block.Hash()] = oBlock
325 // Add to previous hash lookup index for faster dependency lookups.
326 prevHash := &block.MsgBlock().Header.PrevBlock
327 b.prevOrphans[*prevHash] = append(b.prevOrphans[*prevHash], oBlock)
330 // SequenceLock represents the converted relative lock-time in seconds, and
331 // absolute block-height for a transaction input's relative lock-times.
332 // According to SequenceLock, after the referenced input has been confirmed
333 // within a block, a transaction spending that input can be included into a
334 // block either after 'seconds' (according to past median time), or once the
335 // 'BlockHeight' has been reached.
336 type SequenceLock struct {
341 // CalcSequenceLock computes a relative lock-time SequenceLock for the passed
342 // transaction using the passed UtxoViewpoint to obtain the past median time
343 // for blocks in which the referenced inputs of the transactions were included
344 // within. The generated SequenceLock lock can be used in conjunction with a
345 // block height, and adjusted median block time to determine if all the inputs
346 // referenced within a transaction have reached sufficient maturity allowing
347 // the candidate transaction to be included in a block.
349 // This function is safe for concurrent access.
350 func (b *BlockChain) CalcSequenceLock(tx *btcutil.Tx, utxoView *UtxoViewpoint, mempool bool) (*SequenceLock, error) {
352 defer b.chainLock.Unlock()
354 return b.calcSequenceLock(b.bestChain.Tip(), tx, utxoView, mempool)
357 // calcSequenceLock computes the relative lock-times for the passed
358 // transaction. See the exported version, CalcSequenceLock for further details.
360 // This function MUST be called with the chain state lock held (for writes).
361 func (b *BlockChain) calcSequenceLock(node *blockNode, tx *btcutil.Tx, utxoView *UtxoViewpoint, mempool bool) (*SequenceLock, error) {
362 // A value of -1 for each relative lock type represents a relative time
363 // lock value that will allow a transaction to be included in a block
364 // at any given height or time. This value is returned as the relative
365 // lock time in the case that BIP 68 is disabled, or has not yet been
367 sequenceLock := &SequenceLock{Seconds: -1, BlockHeight: -1}
369 // The sequence locks semantics are always active for transactions
370 // within the mempool.
371 csvSoftforkActive := mempool
373 // If we're performing block validation, then we need to query the BIP9
375 if !csvSoftforkActive {
376 // Obtain the latest BIP9 version bits state for the
377 // CSV-package soft-fork deployment. The adherence of sequence
378 // locks depends on the current soft-fork state.
379 csvState, err := b.deploymentState(node.parent, chaincfg.DeploymentCSV)
383 csvSoftforkActive = csvState == ThresholdActive
386 // If the transaction's version is less than 2, and BIP 68 has not yet
387 // been activated then sequence locks are disabled. Additionally,
388 // sequence locks don't apply to coinbase transactions Therefore, we
389 // return sequence lock values of -1 indicating that this transaction
390 // can be included within a block at any given height or time.
392 sequenceLockActive := mTx.Version >= 2 && csvSoftforkActive
393 if !sequenceLockActive || IsCoinBase(tx) {
394 return sequenceLock, nil
397 // Grab the next height from the PoV of the passed blockNode to use for
398 // inputs present in the mempool.
399 nextHeight := node.height + 1
401 for txInIndex, txIn := range mTx.TxIn {
402 utxo := utxoView.LookupEntry(&txIn.PreviousOutPoint.Hash)
404 str := fmt.Sprintf("output %v referenced from "+
405 "transaction %s:%d either does not exist or "+
406 "has already been spent", txIn.PreviousOutPoint,
407 tx.Hash(), txInIndex)
408 return sequenceLock, ruleError(ErrMissingTxOut, str)
411 // If the input height is set to the mempool height, then we
412 // assume the transaction makes it into the next block when
413 // evaluating its sequence blocks.
414 inputHeight := utxo.BlockHeight()
415 if inputHeight == 0x7fffffff {
416 inputHeight = nextHeight
419 // Given a sequence number, we apply the relative time lock
420 // mask in order to obtain the time lock delta required before
421 // this input can be spent.
422 sequenceNum := txIn.Sequence
423 relativeLock := int64(sequenceNum & wire.SequenceLockTimeMask)
426 // Relative time locks are disabled for this input, so we can
427 // skip any further calculation.
428 case sequenceNum&wire.SequenceLockTimeDisabled == wire.SequenceLockTimeDisabled:
430 case sequenceNum&wire.SequenceLockTimeIsSeconds == wire.SequenceLockTimeIsSeconds:
431 // This input requires a relative time lock expressed
432 // in seconds before it can be spent. Therefore, we
433 // need to query for the block prior to the one in
434 // which this input was included within so we can
435 // compute the past median time for the block prior to
436 // the one which included this referenced output.
437 prevInputHeight := inputHeight - 1
438 if prevInputHeight < 0 {
441 blockNode := node.Ancestor(prevInputHeight)
442 medianTime := blockNode.CalcPastMedianTime()
444 // Time based relative time-locks as defined by BIP 68
445 // have a time granularity of RelativeLockSeconds, so
446 // we shift left by this amount to convert to the
447 // proper relative time-lock. We also subtract one from
448 // the relative lock to maintain the original lockTime
450 timeLockSeconds := (relativeLock << wire.SequenceLockTimeGranularity) - 1
451 timeLock := medianTime.Unix() + timeLockSeconds
452 if timeLock > sequenceLock.Seconds {
453 sequenceLock.Seconds = timeLock
456 // The relative lock-time for this input is expressed
457 // in blocks so we calculate the relative offset from
458 // the input's height as its converted absolute
459 // lock-time. We subtract one from the relative lock in
460 // order to maintain the original lockTime semantics.
461 blockHeight := inputHeight + int32(relativeLock-1)
462 if blockHeight > sequenceLock.BlockHeight {
463 sequenceLock.BlockHeight = blockHeight
468 return sequenceLock, nil
471 // LockTimeToSequence converts the passed relative locktime to a sequence
472 // number in accordance to BIP-68.
473 // See: https://github.com/bitcoin/bips/blob/master/bip-0068.mediawiki
475 func LockTimeToSequence(isSeconds bool, locktime uint32) uint32 {
476 // If we're expressing the relative lock time in blocks, then the
477 // corresponding sequence number is simply the desired input age.
482 // Set the 22nd bit which indicates the lock time is in seconds, then
483 // shift the locktime over by 9 since the time granularity is in
484 // 512-second intervals (2^9). This results in a max lock-time of
485 // 33,553,920 seconds, or 1.1 years.
486 return wire.SequenceLockTimeIsSeconds |
487 locktime>>wire.SequenceLockTimeGranularity
490 // getReorganizeNodes finds the fork point between the main chain and the passed
491 // node and returns a list of block nodes that would need to be detached from
492 // the main chain and a list of block nodes that would need to be attached to
493 // the fork point (which will be the end of the main chain after detaching the
494 // returned list of block nodes) in order to reorganize the chain such that the
495 // passed node is the new end of the main chain. The lists will be empty if the
496 // passed node is not on a side chain.
498 // This function MUST be called with the chain state lock held (for reads).
499 func (b *BlockChain) getReorganizeNodes(node *blockNode) (*list.List, *list.List) {
500 // Nothing to detach or attach if there is no node.
501 attachNodes := list.New()
502 detachNodes := list.New()
504 return detachNodes, attachNodes
507 // Find the fork point (if any) adding each block to the list of nodes
508 // to attach to the main tree. Push them onto the list in reverse order
509 // so they are attached in the appropriate order when iterating the list
511 forkNode := b.bestChain.FindFork(node)
512 for n := node; n != nil && n != forkNode; n = n.parent {
513 attachNodes.PushFront(n)
516 // Start from the end of the main chain and work backwards until the
517 // common ancestor adding each block to the list of nodes to detach from
519 for n := b.bestChain.Tip(); n != nil && n != forkNode; n = n.parent {
520 detachNodes.PushBack(n)
523 return detachNodes, attachNodes
526 // dbMaybeStoreBlock stores the provided block in the database if it's not
528 func dbMaybeStoreBlock(dbTx database.Tx, block *btcutil.Block) error {
529 hasBlock, err := dbTx.HasBlock(block.Hash())
537 return dbTx.StoreBlock(block)
540 // connectBlock handles connecting the passed node/block to the end of the main
543 // This passed utxo view must have all referenced txos the block spends marked
544 // as spent and all of the new txos the block creates added to it. In addition,
545 // the passed stxos slice must be populated with all of the information for the
546 // spent txos. This approach is used because the connection validation that
547 // must happen prior to calling this function requires the same details, so
548 // it would be inefficient to repeat it.
550 // This function MUST be called with the chain state lock held (for writes).
551 func (b *BlockChain) connectBlock(node *blockNode, block *btcutil.Block, view *UtxoViewpoint, stxos []spentTxOut) error {
552 // Make sure it's extending the end of the best chain.
553 prevHash := &block.MsgBlock().Header.PrevBlock
554 if !prevHash.IsEqual(&b.bestChain.Tip().hash) {
555 return AssertError("connectBlock must be called with a block " +
556 "that extends the main chain")
559 // Sanity check the correct number of stxos are provided.
560 if len(stxos) != countSpentOutputs(block) {
561 return AssertError("connectBlock called with inconsistent " +
562 "spent transaction out information")
565 // No warnings about unknown rules or versions until the chain is
568 // Warn if any unknown new rules are either about to activate or
569 // have already been activated.
570 if err := b.warnUnknownRuleActivations(node); err != nil {
574 // Warn if a high enough percentage of the last blocks have
575 // unexpected versions.
576 if err := b.warnUnknownVersions(node); err != nil {
581 // Generate a new best state snapshot that will be used to update the
582 // database and later memory if all database updates are successful.
584 curTotalTxns := b.stateSnapshot.TotalTxns
585 b.stateLock.RUnlock()
586 numTxns := uint64(len(block.MsgBlock().Transactions))
587 blockSize := uint64(block.MsgBlock().SerializeSize())
588 blockWeight := uint64(GetBlockWeight(block))
589 state := newBestState(node, blockSize, blockWeight, numTxns,
590 curTotalTxns+numTxns, node.CalcPastMedianTime())
592 // Atomically insert info into the database.
593 err := b.db.Update(func(dbTx database.Tx) error {
594 // Update best block state.
595 err := dbPutBestState(dbTx, state, node.workSum)
600 // Add the block hash and height to the block index which tracks
602 err = dbPutBlockIndex(dbTx, block.Hash(), node.height)
607 // Update the utxo set using the state of the utxo view. This
608 // entails removing all of the utxos spent and adding the new
609 // ones created by the block.
610 err = dbPutUtxoView(dbTx, view)
615 // Update the transaction spend journal by adding a record for
616 // the block that contains all txos spent by it.
617 err = dbPutSpendJournalEntry(dbTx, block.Hash(), stxos)
622 // Allow the index manager to call each of the currently active
623 // optional indexes with the block being connected so they can
624 // update themselves accordingly.
625 if b.indexManager != nil {
626 err := b.indexManager.ConnectBlock(dbTx, block, view)
638 // Prune fully spent entries and mark all entries in the view unmodified
639 // now that the modifications have been committed to the database.
642 // This node is now the end of the best chain.
643 b.bestChain.SetTip(node)
645 // Update the state for the best block. Notice how this replaces the
646 // entire struct instead of updating the existing one. This effectively
647 // allows the old version to act as a snapshot which callers can use
648 // freely without needing to hold a lock for the duration. See the
649 // comments on the state variable for more details.
651 b.stateSnapshot = state
654 // Notify the caller that the block was connected to the main chain.
655 // The caller would typically want to react with actions such as
658 b.sendNotification(NTBlockConnected, block)
664 // disconnectBlock handles disconnecting the passed node/block from the end of
665 // the main (best) chain.
667 // This function MUST be called with the chain state lock held (for writes).
668 func (b *BlockChain) disconnectBlock(node *blockNode, block *btcutil.Block, view *UtxoViewpoint) error {
669 // Make sure the node being disconnected is the end of the best chain.
670 if !node.hash.IsEqual(&b.bestChain.Tip().hash) {
671 return AssertError("disconnectBlock must be called with the " +
672 "block at the end of the main chain")
675 // Load the previous block since some details for it are needed below.
676 prevNode := node.parent
677 var prevBlock *btcutil.Block
678 err := b.db.View(func(dbTx database.Tx) error {
680 prevBlock, err = dbFetchBlockByNode(dbTx, prevNode)
687 // Generate a new best state snapshot that will be used to update the
688 // database and later memory if all database updates are successful.
690 curTotalTxns := b.stateSnapshot.TotalTxns
691 b.stateLock.RUnlock()
692 numTxns := uint64(len(prevBlock.MsgBlock().Transactions))
693 blockSize := uint64(prevBlock.MsgBlock().SerializeSize())
694 blockWeight := uint64(GetBlockWeight(prevBlock))
695 newTotalTxns := curTotalTxns - uint64(len(block.MsgBlock().Transactions))
696 state := newBestState(prevNode, blockSize, blockWeight, numTxns,
697 newTotalTxns, prevNode.CalcPastMedianTime())
699 err = b.db.Update(func(dbTx database.Tx) error {
700 // Update best block state.
701 err := dbPutBestState(dbTx, state, node.workSum)
706 // Remove the block hash and height from the block index which
707 // tracks the main chain.
708 err = dbRemoveBlockIndex(dbTx, block.Hash(), node.height)
713 // Update the utxo set using the state of the utxo view. This
714 // entails restoring all of the utxos spent and removing the new
715 // ones created by the block.
716 err = dbPutUtxoView(dbTx, view)
721 // Update the transaction spend journal by removing the record
722 // that contains all txos spent by the block .
723 err = dbRemoveSpendJournalEntry(dbTx, block.Hash())
728 // Allow the index manager to call each of the currently active
729 // optional indexes with the block being disconnected so they
730 // can update themselves accordingly.
731 if b.indexManager != nil {
732 err := b.indexManager.DisconnectBlock(dbTx, block, view)
744 // Prune fully spent entries and mark all entries in the view unmodified
745 // now that the modifications have been committed to the database.
748 // This node's parent is now the end of the best chain.
749 b.bestChain.SetTip(node.parent)
751 // Update the state for the best block. Notice how this replaces the
752 // entire struct instead of updating the existing one. This effectively
753 // allows the old version to act as a snapshot which callers can use
754 // freely without needing to hold a lock for the duration. See the
755 // comments on the state variable for more details.
757 b.stateSnapshot = state
760 // Notify the caller that the block was disconnected from the main
761 // chain. The caller would typically want to react with actions such as
764 b.sendNotification(NTBlockDisconnected, block)
770 // countSpentOutputs returns the number of utxos the passed block spends.
771 func countSpentOutputs(block *btcutil.Block) int {
772 // Exclude the coinbase transaction since it can't spend anything.
774 for _, tx := range block.Transactions()[1:] {
775 numSpent += len(tx.MsgTx().TxIn)
780 // reorganizeChain reorganizes the block chain by disconnecting the nodes in the
781 // detachNodes list and connecting the nodes in the attach list. It expects
782 // that the lists are already in the correct order and are in sync with the
783 // end of the current best chain. Specifically, nodes that are being
784 // disconnected must be in reverse order (think of popping them off the end of
785 // the chain) and nodes the are being attached must be in forwards order
786 // (think pushing them onto the end of the chain).
788 // The flags modify the behavior of this function as follows:
789 // - BFDryRun: Only the checks which ensure the reorganize can be completed
790 // successfully are performed. The chain is not reorganized.
792 // This function MUST be called with the chain state lock held (for writes).
793 func (b *BlockChain) reorganizeChain(detachNodes, attachNodes *list.List, flags BehaviorFlags) error {
794 // All of the blocks to detach and related spend journal entries needed
795 // to unspend transaction outputs in the blocks being disconnected must
796 // be loaded from the database during the reorg check phase below and
797 // then they are needed again when doing the actual database updates.
798 // Rather than doing two loads, cache the loaded data into these slices.
799 detachBlocks := make([]*btcutil.Block, 0, detachNodes.Len())
800 detachSpentTxOuts := make([][]spentTxOut, 0, detachNodes.Len())
801 attachBlocks := make([]*btcutil.Block, 0, attachNodes.Len())
803 // Disconnect all of the blocks back to the point of the fork. This
804 // entails loading the blocks and their associated spent txos from the
805 // database and using that information to unspend all of the spent txos
806 // and remove the utxos created by the blocks.
807 view := NewUtxoViewpoint()
808 view.SetBestHash(&b.bestChain.Tip().hash)
809 for e := detachNodes.Front(); e != nil; e = e.Next() {
810 n := e.Value.(*blockNode)
811 var block *btcutil.Block
812 err := b.db.View(func(dbTx database.Tx) error {
814 block, err = dbFetchBlockByNode(dbTx, n)
821 // Load all of the utxos referenced by the block that aren't
822 // already in the view.
823 err = view.fetchInputUtxos(b.db, block)
828 // Load all of the spent txos for the block from the spend
830 var stxos []spentTxOut
831 err = b.db.View(func(dbTx database.Tx) error {
832 stxos, err = dbFetchSpendJournalEntry(dbTx, block, view)
839 // Store the loaded block and spend journal entry for later.
840 detachBlocks = append(detachBlocks, block)
841 detachSpentTxOuts = append(detachSpentTxOuts, stxos)
843 err = view.disconnectTransactions(block, stxos)
849 // Perform several checks to verify each block that needs to be attached
850 // to the main chain can be connected without violating any rules and
851 // without actually connecting the block.
853 // NOTE: These checks could be done directly when connecting a block,
854 // however the downside to that approach is that if any of these checks
855 // fail after disconnecting some blocks or attaching others, all of the
856 // operations have to be rolled back to get the chain back into the
857 // state it was before the rule violation (or other failure). There are
858 // at least a couple of ways accomplish that rollback, but both involve
859 // tweaking the chain and/or database. This approach catches these
860 // issues before ever modifying the chain.
861 for e := attachNodes.Front(); e != nil; e = e.Next() {
862 n := e.Value.(*blockNode)
863 var block *btcutil.Block
864 err := b.db.View(func(dbTx database.Tx) error {
866 block, err = dbFetchBlockByNode(dbTx, n)
873 // Store the loaded block for later.
874 attachBlocks = append(attachBlocks, block)
876 // Notice the spent txout details are not requested here and
877 // thus will not be generated. This is done because the state
878 // is not being immediately written to the database, so it is
880 err = b.checkConnectBlock(n, block, view, nil)
886 // Skip disconnecting and connecting the blocks when running with the
888 if flags&BFDryRun == BFDryRun {
892 // Reset the view for the actual connection code below. This is
893 // required because the view was previously modified when checking if
894 // the reorg would be successful and the connection code requires the
895 // view to be valid from the viewpoint of each block being connected or
897 view = NewUtxoViewpoint()
898 view.SetBestHash(&b.bestChain.Tip().hash)
900 // Disconnect blocks from the main chain.
901 for i, e := 0, detachNodes.Front(); e != nil; i, e = i+1, e.Next() {
902 n := e.Value.(*blockNode)
903 block := detachBlocks[i]
905 // Load all of the utxos referenced by the block that aren't
906 // already in the view.
907 err := view.fetchInputUtxos(b.db, block)
912 // Update the view to unspend all of the spent txos and remove
913 // the utxos created by the block.
914 err = view.disconnectTransactions(block, detachSpentTxOuts[i])
919 // Update the database and chain state.
920 err = b.disconnectBlock(n, block, view)
926 // Connect the new best chain blocks.
927 for i, e := 0, attachNodes.Front(); e != nil; i, e = i+1, e.Next() {
928 n := e.Value.(*blockNode)
929 block := attachBlocks[i]
931 // Load all of the utxos referenced by the block that aren't
932 // already in the view.
933 err := view.fetchInputUtxos(b.db, block)
938 // Update the view to mark all utxos referenced by the block
939 // as spent and add all transactions being created by this block
940 // to it. Also, provide an stxo slice so the spent txout
941 // details are generated.
942 stxos := make([]spentTxOut, 0, countSpentOutputs(block))
943 err = view.connectTransactions(block, &stxos)
948 // Update the database and chain state.
949 err = b.connectBlock(n, block, view, stxos)
955 // Log the point where the chain forked and old and new best chain
957 firstAttachNode := attachNodes.Front().Value.(*blockNode)
958 firstDetachNode := detachNodes.Front().Value.(*blockNode)
959 lastAttachNode := attachNodes.Back().Value.(*blockNode)
960 log.Infof("REORGANIZE: Chain forks at %v", firstAttachNode.parent.hash)
961 log.Infof("REORGANIZE: Old best chain head was %v", firstDetachNode.hash)
962 log.Infof("REORGANIZE: New best chain head is %v", lastAttachNode.hash)
967 // connectBestChain handles connecting the passed block to the chain while
968 // respecting proper chain selection according to the chain with the most
969 // proof of work. In the typical case, the new block simply extends the main
970 // chain. However, it may also be extending (or creating) a side chain (fork)
971 // which may or may not end up becoming the main chain depending on which fork
972 // cumulatively has the most proof of work. It returns whether or not the block
973 // ended up on the main chain (either due to extending the main chain or causing
974 // a reorganization to become the main chain).
976 // The flags modify the behavior of this function as follows:
977 // - BFFastAdd: Avoids several expensive transaction validation operations.
978 // This is useful when using checkpoints.
979 // - BFDryRun: Prevents the block from actually being connected and avoids any
980 // log messages related to modifying the state.
982 // This function MUST be called with the chain state lock held (for writes).
983 func (b *BlockChain) connectBestChain(node *blockNode, block *btcutil.Block, flags BehaviorFlags) (bool, error) {
984 fastAdd := flags&BFFastAdd == BFFastAdd
985 dryRun := flags&BFDryRun == BFDryRun
987 // We are extending the main (best) chain with a new block. This is the
989 parentHash := &block.MsgBlock().Header.PrevBlock
990 if parentHash.IsEqual(&b.bestChain.Tip().hash) {
991 // Perform several checks to verify the block can be connected
992 // to the main chain without violating any rules and without
993 // actually connecting the block.
994 view := NewUtxoViewpoint()
995 view.SetBestHash(parentHash)
996 stxos := make([]spentTxOut, 0, countSpentOutputs(block))
998 err := b.checkConnectBlock(node, block, view, &stxos)
1004 // Don't connect the block if performing a dry run.
1009 // In the fast add case the code to check the block connection
1010 // was skipped, so the utxo view needs to load the referenced
1011 // utxos, spend them, and add the new utxos being created by
1014 err := view.fetchInputUtxos(b.db, block)
1018 err = view.connectTransactions(block, &stxos)
1024 // Connect the block to the main chain.
1025 err := b.connectBlock(node, block, view, stxos)
1033 log.Warnf("fastAdd set in the side chain case? %v\n",
1037 // We're extending (or creating) a side chain, but the cumulative
1038 // work for this new side chain is not enough to make it the new chain.
1039 if node.workSum.Cmp(b.bestChain.Tip().workSum) <= 0 {
1040 // Skip Logging info when the dry run flag is set.
1045 // Log information about how the block is forking the chain.
1046 fork := b.bestChain.FindFork(node)
1047 if fork.hash.IsEqual(parentHash) {
1048 log.Infof("FORK: Block %v forks the chain at height %d"+
1049 "/block %v, but does not cause a reorganize",
1050 node.hash, fork.height, fork.hash)
1052 log.Infof("EXTEND FORK: Block %v extends a side chain "+
1053 "which forks the chain at height %d/block %v",
1054 node.hash, fork.height, fork.hash)
1060 // We're extending (or creating) a side chain and the cumulative work
1061 // for this new side chain is more than the old best chain, so this side
1062 // chain needs to become the main chain. In order to accomplish that,
1063 // find the common ancestor of both sides of the fork, disconnect the
1064 // blocks that form the (now) old fork from the main chain, and attach
1065 // the blocks that form the new chain to the main chain starting at the
1066 // common ancenstor (the point where the chain forked).
1067 detachNodes, attachNodes := b.getReorganizeNodes(node)
1069 // Reorganize the chain.
1071 log.Infof("REORGANIZE: Block %v is causing a reorganize.",
1074 err := b.reorganizeChain(detachNodes, attachNodes, flags)
1082 // isCurrent returns whether or not the chain believes it is current. Several
1083 // factors are used to guess, but the key factors that allow the chain to
1084 // believe it is current are:
1085 // - Latest block height is after the latest checkpoint (if enabled)
1086 // - Latest block has a timestamp newer than 24 hours ago
1088 // This function MUST be called with the chain state lock held (for reads).
1089 func (b *BlockChain) isCurrent() bool {
1090 // Not current if the latest main (best) chain height is before the
1091 // latest known good checkpoint (when checkpoints are enabled).
1092 checkpoint := b.LatestCheckpoint()
1093 if checkpoint != nil && b.bestChain.Tip().height < checkpoint.Height {
1097 // Not current if the latest best block has a timestamp before 24 hours
1100 // The chain appears to be current if none of the checks reported
1102 minus24Hours := b.timeSource.AdjustedTime().Add(-24 * time.Hour).Unix()
1103 return b.bestChain.Tip().timestamp >= minus24Hours
1106 // IsCurrent returns whether or not the chain believes it is current. Several
1107 // factors are used to guess, but the key factors that allow the chain to
1108 // believe it is current are:
1109 // - Latest block height is after the latest checkpoint (if enabled)
1110 // - Latest block has a timestamp newer than 24 hours ago
1112 // This function is safe for concurrent access.
1113 func (b *BlockChain) IsCurrent() bool {
1115 defer b.chainLock.RUnlock()
1117 return b.isCurrent()
1120 // BestSnapshot returns information about the current best chain block and
1121 // related state as of the current point in time. The returned instance must be
1122 // treated as immutable since it is shared by all callers.
1124 // This function is safe for concurrent access.
1125 func (b *BlockChain) BestSnapshot() *BestState {
1127 snapshot := b.stateSnapshot
1128 b.stateLock.RUnlock()
1132 // FetchHeader returns the block header identified by the given hash or an error
1133 // if it doesn't exist.
1134 func (b *BlockChain) FetchHeader(hash *chainhash.Hash) (wire.BlockHeader, error) {
1135 // Reconstruct the header from the block index if possible.
1136 if node := b.index.LookupNode(hash); node != nil {
1137 return node.Header(), nil
1140 // Fall back to loading it from the database.
1141 var header *wire.BlockHeader
1142 err := b.db.View(func(dbTx database.Tx) error {
1144 header, err = dbFetchHeaderByHash(dbTx, hash)
1148 return wire.BlockHeader{}, err
1153 // MainChainHasBlock returns whether or not the block with the given hash is in
1156 // This function is safe for concurrent access.
1157 func (b *BlockChain) MainChainHasBlock(hash *chainhash.Hash) bool {
1158 node := b.index.LookupNode(hash)
1159 return node != nil && b.bestChain.Contains(node)
1162 // BlockLocatorFromHash returns a block locator for the passed block hash.
1163 // See BlockLocator for details on the algorithm used to create a block locator.
1165 // In addition to the general algorithm referenced above, this function will
1166 // return the block locator for the latest known tip of the main (best) chain if
1167 // the passed hash is not currently known.
1169 // This function is safe for concurrent access.
1170 func (b *BlockChain) BlockLocatorFromHash(hash *chainhash.Hash) BlockLocator {
1172 node := b.index.LookupNode(hash)
1173 locator := b.bestChain.blockLocator(node)
1174 b.chainLock.RUnlock()
1178 // LatestBlockLocator returns a block locator for the latest known tip of the
1179 // main (best) chain.
1181 // This function is safe for concurrent access.
1182 func (b *BlockChain) LatestBlockLocator() (BlockLocator, error) {
1184 locator := b.bestChain.BlockLocator(nil)
1185 b.chainLock.RUnlock()
1189 // BlockHeightByHash returns the height of the block with the given hash in the
1192 // This function is safe for concurrent access.
1193 func (b *BlockChain) BlockHeightByHash(hash *chainhash.Hash) (int32, error) {
1194 node := b.index.LookupNode(hash)
1195 if node == nil || !b.bestChain.Contains(node) {
1196 str := fmt.Sprintf("block %s is not in the main chain", hash)
1197 return 0, errNotInMainChain(str)
1200 return node.height, nil
1203 // BlockHashByHeight returns the hash of the block at the given height in the
1206 // This function is safe for concurrent access.
1207 func (b *BlockChain) BlockHashByHeight(blockHeight int32) (*chainhash.Hash, error) {
1208 node := b.bestChain.NodeByHeight(blockHeight)
1210 str := fmt.Sprintf("no block at height %d exists", blockHeight)
1211 return nil, errNotInMainChain(str)
1215 return &node.hash, nil
1218 // HeightRange returns a range of block hashes for the given start and end
1219 // heights. It is inclusive of the start height and exclusive of the end
1220 // height. The end height will be limited to the current main chain height.
1222 // This function is safe for concurrent access.
1223 func (b *BlockChain) HeightRange(startHeight, endHeight int32) ([]chainhash.Hash, error) {
1224 // Ensure requested heights are sane.
1225 if startHeight < 0 {
1226 return nil, fmt.Errorf("start height of fetch range must not "+
1227 "be less than zero - got %d", startHeight)
1229 if endHeight < startHeight {
1230 return nil, fmt.Errorf("end height of fetch range must not "+
1231 "be less than the start height - got start %d, end %d",
1232 startHeight, endHeight)
1235 // There is nothing to do when the start and end heights are the same,
1236 // so return now to avoid the chain view lock.
1237 if startHeight == endHeight {
1241 // Grab a lock on the chain view to prevent it from changing due to a
1242 // reorg while building the hashes.
1243 b.bestChain.mtx.Lock()
1244 defer b.bestChain.mtx.Unlock()
1246 // When the requested start height is after the most recent best chain
1247 // height, there is nothing to do.
1248 latestHeight := b.bestChain.tip().height
1249 if startHeight > latestHeight {
1253 // Limit the ending height to the latest height of the chain.
1254 if endHeight > latestHeight+1 {
1255 endHeight = latestHeight + 1
1258 // Fetch as many as are available within the specified range.
1259 hashes := make([]chainhash.Hash, 0, endHeight-startHeight)
1260 for i := startHeight; i < endHeight; i++ {
1261 hashes = append(hashes, b.bestChain.nodeByHeight(i).hash)
1266 // locateInventory returns the node of the block after the first known block in
1267 // the locator along with the number of subsequent nodes needed to either reach
1268 // the provided stop hash or the provided max number of entries.
1270 // In addition, there are two special cases:
1272 // - When no locators are provided, the stop hash is treated as a request for
1273 // that block, so it will either return the node associated with the stop hash
1274 // if it is known, or nil if it is unknown
1275 // - When locators are provided, but none of them are known, nodes starting
1276 // after the genesis block will be returned
1278 // This is primarily a helper function for the locateBlocks and locateHeaders
1281 // This function MUST be called with the chain state lock held (for reads).
1282 func (b *BlockChain) locateInventory(locator BlockLocator, hashStop *chainhash.Hash, maxEntries uint32) (*blockNode, uint32) {
1283 // There are no block locators so a specific block is being requested
1284 // as identified by the stop hash.
1285 stopNode := b.index.LookupNode(hashStop)
1286 if len(locator) == 0 {
1287 if stopNode == nil {
1288 // No blocks with the stop hash were found so there is
1295 // Find the most recent locator block hash in the main chain. In the
1296 // case none of the hashes in the locator are in the main chain, fall
1297 // back to the genesis block.
1298 startNode := b.bestChain.Genesis()
1299 for _, hash := range locator {
1300 node := b.index.LookupNode(hash)
1301 if node != nil && b.bestChain.Contains(node) {
1307 // Start at the block after the most recently known block. When there
1308 // is no next block it means the most recently known block is the tip of
1309 // the best chain, so there is nothing more to do.
1310 startNode = b.bestChain.Next(startNode)
1311 if startNode == nil {
1315 // Calculate how many entries are needed.
1316 total := uint32((b.bestChain.Tip().height - startNode.height) + 1)
1317 if stopNode != nil && b.bestChain.Contains(stopNode) &&
1318 stopNode.height >= startNode.height {
1320 total = uint32((stopNode.height - startNode.height) + 1)
1322 if total > maxEntries {
1326 return startNode, total
1329 // locateBlocks returns the hashes of the blocks after the first known block in
1330 // the locator until the provided stop hash is reached, or up to the provided
1331 // max number of block hashes.
1333 // See the comment on the exported function for more details on special cases.
1335 // This function MUST be called with the chain state lock held (for reads).
1336 func (b *BlockChain) locateBlocks(locator BlockLocator, hashStop *chainhash.Hash, maxHashes uint32) []chainhash.Hash {
1337 // Find the node after the first known block in the locator and the
1338 // total number of nodes after it needed while respecting the stop hash
1340 node, total := b.locateInventory(locator, hashStop, maxHashes)
1345 // Populate and return the found hashes.
1346 hashes := make([]chainhash.Hash, 0, total)
1347 for i := uint32(0); i < total; i++ {
1348 hashes = append(hashes, node.hash)
1349 node = b.bestChain.Next(node)
1354 // LocateBlocks returns the hashes of the blocks after the first known block in
1355 // the locator until the provided stop hash is reached, or up to the provided
1356 // max number of block hashes.
1358 // In addition, there are two special cases:
1360 // - When no locators are provided, the stop hash is treated as a request for
1361 // that block, so it will either return the stop hash itself if it is known,
1362 // or nil if it is unknown
1363 // - When locators are provided, but none of them are known, hashes starting
1364 // after the genesis block will be returned
1366 // This function is safe for concurrent access.
1367 func (b *BlockChain) LocateBlocks(locator BlockLocator, hashStop *chainhash.Hash, maxHashes uint32) []chainhash.Hash {
1369 hashes := b.locateBlocks(locator, hashStop, maxHashes)
1370 b.chainLock.RUnlock()
1374 // locateHeaders returns the headers of the blocks after the first known block
1375 // in the locator until the provided stop hash is reached, or up to the provided
1376 // max number of block headers.
1378 // See the comment on the exported function for more details on special cases.
1380 // This function MUST be called with the chain state lock held (for reads).
1381 func (b *BlockChain) locateHeaders(locator BlockLocator, hashStop *chainhash.Hash, maxHeaders uint32) []wire.BlockHeader {
1382 // Find the node after the first known block in the locator and the
1383 // total number of nodes after it needed while respecting the stop hash
1385 node, total := b.locateInventory(locator, hashStop, maxHeaders)
1390 // Populate and return the found headers.
1391 headers := make([]wire.BlockHeader, 0, total)
1392 for i := uint32(0); i < total; i++ {
1393 headers = append(headers, node.Header())
1394 node = b.bestChain.Next(node)
1399 // LocateHeaders returns the headers of the blocks after the first known block
1400 // in the locator until the provided stop hash is reached, or up to a max of
1401 // wire.MaxBlockHeadersPerMsg headers.
1403 // In addition, there are two special cases:
1405 // - When no locators are provided, the stop hash is treated as a request for
1406 // that header, so it will either return the header for the stop hash itself
1407 // if it is known, or nil if it is unknown
1408 // - When locators are provided, but none of them are known, headers starting
1409 // after the genesis block will be returned
1411 // This function is safe for concurrent access.
1412 func (b *BlockChain) LocateHeaders(locator BlockLocator, hashStop *chainhash.Hash) []wire.BlockHeader {
1414 headers := b.locateHeaders(locator, hashStop, wire.MaxBlockHeadersPerMsg)
1415 b.chainLock.RUnlock()
1419 // IndexManager provides a generic interface that the is called when blocks are
1420 // connected and disconnected to and from the tip of the main chain for the
1421 // purpose of supporting optional indexes.
1422 type IndexManager interface {
1423 // Init is invoked during chain initialize in order to allow the index
1424 // manager to initialize itself and any indexes it is managing.
1425 Init(*BlockChain) error
1427 // ConnectBlock is invoked when a new block has been connected to the
1429 ConnectBlock(database.Tx, *btcutil.Block, *UtxoViewpoint) error
1431 // DisconnectBlock is invoked when a block has been disconnected from
1433 DisconnectBlock(database.Tx, *btcutil.Block, *UtxoViewpoint) error
1436 // Config is a descriptor which specifies the blockchain instance configuration.
1437 type Config struct {
1438 // DB defines the database which houses the blocks and will be used to
1439 // store all metadata created by this package such as the utxo set.
1441 // This field is required.
1444 // ChainParams identifies which chain parameters the chain is associated
1447 // This field is required.
1448 ChainParams *chaincfg.Params
1450 // Checkpoints hold caller-defined checkpoints that should be added to
1451 // the default checkpoints in ChainParams. Checkpoints must be sorted
1454 // This field can be nil if the caller does not wish to specify any
1456 Checkpoints []chaincfg.Checkpoint
1458 // TimeSource defines the median time source to use for things such as
1459 // block processing and determining whether or not the chain is current.
1461 // The caller is expected to keep a reference to the time source as well
1462 // and add time samples from other peers on the network so the local
1463 // time is adjusted to be in agreement with other peers.
1464 TimeSource MedianTimeSource
1466 // SigCache defines a signature cache to use when when validating
1467 // signatures. This is typically most useful when individual
1468 // transactions are already being validated prior to their inclusion in
1469 // a block such as what is usually done via a transaction memory pool.
1471 // This field can be nil if the caller is not interested in using a
1473 SigCache *txscript.SigCache
1475 // IndexManager defines an index manager to use when initializing the
1476 // chain and connecting and disconnecting blocks.
1478 // This field can be nil if the caller does not wish to make use of an
1480 IndexManager IndexManager
1482 // HashCache defines a transaction hash mid-state cache to use when
1483 // validating transactions. This cache has the potential to greatly
1484 // speed up transaction validation as re-using the pre-calculated
1485 // mid-state eliminates the O(N^2) validation complexity due to the
1488 // This field can be nil if the caller is not interested in using a
1490 HashCache *txscript.HashCache
1493 // New returns a BlockChain instance using the provided configuration details.
1494 func New(config *Config) (*BlockChain, error) {
1495 // Enforce required config fields.
1496 if config.DB == nil {
1497 return nil, AssertError("blockchain.New database is nil")
1499 if config.ChainParams == nil {
1500 return nil, AssertError("blockchain.New chain parameters nil")
1502 if config.TimeSource == nil {
1503 return nil, AssertError("blockchain.New timesource is nil")
1506 // Generate a checkpoint by height map from the provided checkpoints
1507 // and assert the provided checkpoints are sorted by height as required.
1508 var checkpointsByHeight map[int32]*chaincfg.Checkpoint
1509 var prevCheckpointHeight int32
1510 if len(config.Checkpoints) > 0 {
1511 checkpointsByHeight = make(map[int32]*chaincfg.Checkpoint)
1512 for i := range config.Checkpoints {
1513 checkpoint := &config.Checkpoints[i]
1514 if checkpoint.Height <= prevCheckpointHeight {
1515 return nil, AssertError("blockchain.New " +
1516 "checkpoints are not sorted by height")
1519 checkpointsByHeight[checkpoint.Height] = checkpoint
1520 prevCheckpointHeight = checkpoint.Height
1524 params := config.ChainParams
1525 targetTimespan := int64(params.TargetTimespan / time.Second)
1526 targetTimePerBlock := int64(params.TargetTimePerBlock / time.Second)
1527 adjustmentFactor := params.RetargetAdjustmentFactor
1529 checkpoints: config.Checkpoints,
1530 checkpointsByHeight: checkpointsByHeight,
1532 chainParams: params,
1533 timeSource: config.TimeSource,
1534 sigCache: config.SigCache,
1535 indexManager: config.IndexManager,
1536 minRetargetTimespan: targetTimespan / adjustmentFactor,
1537 maxRetargetTimespan: targetTimespan * adjustmentFactor,
1538 blocksPerRetarget: int32(targetTimespan / targetTimePerBlock),
1539 index: newBlockIndex(config.DB, params),
1540 hashCache: config.HashCache,
1541 bestChain: newChainView(nil),
1542 orphans: make(map[chainhash.Hash]*orphanBlock),
1543 prevOrphans: make(map[chainhash.Hash][]*orphanBlock),
1544 warningCaches: newThresholdCaches(vbNumBits),
1545 deploymentCaches: newThresholdCaches(chaincfg.DefinedDeployments),
1548 // Initialize the chain state from the passed database. When the db
1549 // does not yet contain any chain state, both it and the chain state
1550 // will be initialized to contain only the genesis block.
1551 if err := b.initChainState(); err != nil {
1555 // Initialize and catch up all of the currently active optional indexes
1557 if config.IndexManager != nil {
1558 if err := config.IndexManager.Init(&b); err != nil {
1563 // Initialize rule change threshold state caches.
1564 if err := b.initThresholdCaches(); err != nil {
1568 bestNode := b.bestChain.Tip()
1569 log.Infof("Chain state (height %d, hash %v, totaltx %d, work %v)",
1570 bestNode.height, bestNode.hash, b.stateSnapshot.TotalTxns,