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