github.com/Unheilbar/quorum@v1.0.0/core/blockchain.go (about) 1 // Copyright 2014 The go-ethereum Authors 2 // This file is part of the go-ethereum library. 3 // 4 // The go-ethereum library is free software: you can redistribute it and/or modify 5 // it under the terms of the GNU Lesser General Public License as published by 6 // the Free Software Foundation, either version 3 of the License, or 7 // (at your option) any later version. 8 // 9 // The go-ethereum library is distributed in the hope that it will be useful, 10 // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 // GNU Lesser General Public License for more details. 13 // 14 // You should have received a copy of the GNU Lesser General Public License 15 // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>. 16 17 // Package core implements the Ethereum consensus protocol. 18 package core 19 20 import ( 21 "context" 22 "errors" 23 "fmt" 24 "io" 25 "math/big" 26 mrand "math/rand" 27 "sort" 28 "sync" 29 "sync/atomic" 30 "time" 31 32 "github.com/ethereum/go-ethereum/common" 33 "github.com/ethereum/go-ethereum/common/mclock" 34 "github.com/ethereum/go-ethereum/common/prque" 35 "github.com/ethereum/go-ethereum/consensus" 36 "github.com/ethereum/go-ethereum/core/mps" 37 "github.com/ethereum/go-ethereum/core/privatecache" 38 "github.com/ethereum/go-ethereum/core/rawdb" 39 "github.com/ethereum/go-ethereum/core/state" 40 "github.com/ethereum/go-ethereum/core/state/snapshot" 41 "github.com/ethereum/go-ethereum/core/types" 42 "github.com/ethereum/go-ethereum/core/vm" 43 "github.com/ethereum/go-ethereum/ethdb" 44 "github.com/ethereum/go-ethereum/event" 45 "github.com/ethereum/go-ethereum/log" 46 "github.com/ethereum/go-ethereum/metrics" 47 "github.com/ethereum/go-ethereum/params" 48 "github.com/ethereum/go-ethereum/qlight" 49 "github.com/ethereum/go-ethereum/rlp" 50 "github.com/ethereum/go-ethereum/trie" 51 lru "github.com/hashicorp/golang-lru" 52 ) 53 54 var ( 55 headBlockGauge = metrics.NewRegisteredGauge("chain/head/block", nil) 56 headHeaderGauge = metrics.NewRegisteredGauge("chain/head/header", nil) 57 headFastBlockGauge = metrics.NewRegisteredGauge("chain/head/receipt", nil) 58 59 accountReadTimer = metrics.NewRegisteredTimer("chain/account/reads", nil) 60 accountHashTimer = metrics.NewRegisteredTimer("chain/account/hashes", nil) 61 accountUpdateTimer = metrics.NewRegisteredTimer("chain/account/updates", nil) 62 accountCommitTimer = metrics.NewRegisteredTimer("chain/account/commits", nil) 63 64 storageReadTimer = metrics.NewRegisteredTimer("chain/storage/reads", nil) 65 storageHashTimer = metrics.NewRegisteredTimer("chain/storage/hashes", nil) 66 storageUpdateTimer = metrics.NewRegisteredTimer("chain/storage/updates", nil) 67 storageCommitTimer = metrics.NewRegisteredTimer("chain/storage/commits", nil) 68 69 snapshotAccountReadTimer = metrics.NewRegisteredTimer("chain/snapshot/account/reads", nil) 70 snapshotStorageReadTimer = metrics.NewRegisteredTimer("chain/snapshot/storage/reads", nil) 71 snapshotCommitTimer = metrics.NewRegisteredTimer("chain/snapshot/commits", nil) 72 73 blockInsertTimer = metrics.NewRegisteredTimer("chain/inserts", nil) 74 blockValidationTimer = metrics.NewRegisteredTimer("chain/validation", nil) 75 blockExecutionTimer = metrics.NewRegisteredTimer("chain/execution", nil) 76 blockWriteTimer = metrics.NewRegisteredTimer("chain/write", nil) 77 78 blockReorgMeter = metrics.NewRegisteredMeter("chain/reorg/executes", nil) 79 blockReorgAddMeter = metrics.NewRegisteredMeter("chain/reorg/add", nil) 80 blockReorgDropMeter = metrics.NewRegisteredMeter("chain/reorg/drop", nil) 81 blockReorgInvalidatedTx = metrics.NewRegisteredMeter("chain/reorg/invalidTx", nil) 82 83 blockPrefetchExecuteTimer = metrics.NewRegisteredTimer("chain/prefetch/executes", nil) 84 blockPrefetchInterruptMeter = metrics.NewRegisteredMeter("chain/prefetch/interrupts", nil) 85 86 errInsertionInterrupted = errors.New("insertion is interrupted") 87 ) 88 89 const ( 90 bodyCacheLimit = 256 91 blockCacheLimit = 256 92 receiptsCacheLimit = 32 93 txLookupCacheLimit = 1024 94 maxFutureBlocks = 256 95 maxTimeFutureBlocks = 30 96 TriesInMemory = 128 97 98 // BlockChainVersion ensures that an incompatible database forces a resync from scratch. 99 // 100 // Changelog: 101 // 102 // - Version 4 103 // The following incompatible database changes were added: 104 // * the `BlockNumber`, `TxHash`, `TxIndex`, `BlockHash` and `Index` fields of log are deleted 105 // * the `Bloom` field of receipt is deleted 106 // * the `BlockIndex` and `TxIndex` fields of txlookup are deleted 107 // - Version 5 108 // The following incompatible database changes were added: 109 // * the `TxHash`, `GasCost`, and `ContractAddress` fields are no longer stored for a receipt 110 // * the `TxHash`, `GasCost`, and `ContractAddress` fields are computed by looking up the 111 // receipts' corresponding block 112 // - Version 6 113 // The following incompatible database changes were added: 114 // * Transaction lookup information stores the corresponding block number instead of block hash 115 // - Version 7 116 // The following incompatible database changes were added: 117 // * Use freezer as the ancient database to maintain all ancient data 118 // - Version 8 119 // The following incompatible database changes were added: 120 // * New scheme for contract code in order to separate the codes and trie nodes 121 BlockChainVersion uint64 = 8 122 ) 123 124 // CacheConfig contains the configuration values for the trie caching/pruning 125 // that's resident in a blockchain. 126 type CacheConfig struct { 127 TrieCleanLimit int // Memory allowance (MB) to use for caching trie nodes in memory 128 TrieCleanJournal string // Disk journal for saving clean cache entries. 129 TrieCleanRejournal time.Duration // Time interval to dump clean cache to disk periodically 130 TrieCleanNoPrefetch bool // Whether to disable heuristic state prefetching for followup blocks 131 TrieDirtyLimit int // Memory limit (MB) at which to start flushing dirty trie nodes to disk 132 TrieDirtyDisabled bool // Whether to disable trie write caching and GC altogether (archive node) 133 TrieTimeLimit time.Duration // Time limit after which to flush the current in-memory trie to disk 134 SnapshotLimit int // Memory allowance (MB) to use for caching snapshot entries in memory 135 Preimages bool // Whether to store preimage of trie key to the disk 136 137 SnapshotWait bool // Wait for snapshot construction on startup. TODO(karalabe): This is a dirty hack for testing, nuke it 138 } 139 140 // defaultCacheConfig are the default caching values if none are specified by the 141 // user (also used during testing). 142 var defaultCacheConfig = &CacheConfig{ 143 TrieCleanLimit: 256, 144 TrieDirtyLimit: 256, 145 TrieTimeLimit: 5 * time.Minute, 146 SnapshotLimit: 256, 147 SnapshotWait: true, 148 } 149 150 // BlockChain represents the canonical chain given a database with a genesis 151 // block. The Blockchain manages chain imports, reverts, chain reorganisations. 152 // 153 // Importing blocks in to the block chain happens according to the set of rules 154 // defined by the two stage Validator. Processing of blocks is done using the 155 // Processor which processes the included transaction. The validation of the state 156 // is done in the second part of the Validator. Failing results in aborting of 157 // the import. 158 // 159 // The BlockChain also helps in returning blocks from **any** chain included 160 // in the database as well as blocks that represents the canonical chain. It's 161 // important to note that GetBlock can return any block and does not need to be 162 // included in the canonical one where as GetBlockByNumber always represents the 163 // canonical chain. 164 type BlockChain struct { 165 chainConfig *params.ChainConfig // Chain & network configuration 166 cacheConfig *CacheConfig // Cache configuration for pruning 167 168 db ethdb.Database // Low level persistent database to store final content in 169 snaps *snapshot.Tree // Snapshot tree for fast trie leaf access 170 triegc *prque.Prque // Priority queue mapping block numbers to tries to gc 171 gcproc time.Duration // Accumulates canonical block processing for trie dumping 172 173 // txLookupLimit is the maximum number of blocks from head whose tx indices 174 // are reserved: 175 // * 0: means no limit and regenerate any missing indexes 176 // * N: means N block limit [HEAD-N+1, HEAD] and delete extra indexes 177 // * nil: disable tx reindexer/deleter, but still index new blocks 178 txLookupLimit uint64 179 180 hc *HeaderChain 181 rmLogsFeed event.Feed 182 chainFeed event.Feed 183 chainSideFeed event.Feed 184 chainHeadFeed event.Feed 185 logsFeed event.Feed 186 blockProcFeed event.Feed 187 scope event.SubscriptionScope 188 genesisBlock *types.Block 189 190 chainmu sync.RWMutex // blockchain insertion lock 191 192 currentBlock atomic.Value // Current head of the block chain 193 currentFastBlock atomic.Value // Current head of the fast-sync chain (may be above the block chain!) 194 195 stateCache state.Database // State database to reuse between imports (contains state cache) 196 bodyCache *lru.Cache // Cache for the most recent block bodies 197 bodyRLPCache *lru.Cache // Cache for the most recent block bodies in RLP encoded format 198 receiptsCache *lru.Cache // Cache for the most recent receipts per block 199 blockCache *lru.Cache // Cache for the most recent entire blocks 200 txLookupCache *lru.Cache // Cache for the most recent transaction lookup data. 201 futureBlocks *lru.Cache // future blocks are blocks added for later processing 202 203 quit chan struct{} // blockchain quit channel 204 wg sync.WaitGroup // chain processing wait group for shutting down 205 running int32 // 0 if chain is running, 1 when stopped 206 procInterrupt int32 // interrupt signaler for block processing 207 208 engine consensus.Engine 209 validator Validator // Block and state validator interface 210 prefetcher Prefetcher 211 processor Processor // Block transaction processor interface 212 vmConfig vm.Config 213 214 shouldPreserve func(*types.Block) bool // Function used to determine whether should preserve the given block. 215 terminateInsert func(common.Hash, uint64) bool // Testing hook used to terminate ancient receipt chain insertion. 216 217 // Quorum 218 quorumConfig *QuorumChainConfig // quorum chain config holds all the possible configuration fields for GoQuorum 219 setPrivateState func([]*types.Log, *state.StateDB, types.PrivateStateIdentifier) // Function to check extension and set private state 220 221 // privateStateManager manages private state(s) for this blockchain 222 privateStateManager mps.PrivateStateManager 223 privateStateRootHashValidator qlight.PrivateStateRootHashValidator 224 // End Quorum 225 } 226 227 // NewBlockChain returns a fully initialised block chain using information 228 // available in the database. It initialises the default Ethereum Validator and 229 // Processor. 230 func NewBlockChain(db ethdb.Database, cacheConfig *CacheConfig, chainConfig *params.ChainConfig, engine consensus.Engine, vmConfig vm.Config, shouldPreserve func(block *types.Block) bool, txLookupLimit *uint64, quorumChainConfig *QuorumChainConfig) (*BlockChain, error) { 231 if cacheConfig == nil { 232 cacheConfig = defaultCacheConfig 233 } 234 if quorumChainConfig == nil { 235 quorumChainConfig = &QuorumChainConfig{} 236 } 237 bodyCache, _ := lru.New(bodyCacheLimit) 238 bodyRLPCache, _ := lru.New(bodyCacheLimit) 239 receiptsCache, _ := lru.New(receiptsCacheLimit) 240 blockCache, _ := lru.New(blockCacheLimit) 241 txLookupCache, _ := lru.New(txLookupCacheLimit) 242 futureBlocks, _ := lru.New(maxFutureBlocks) 243 244 bc := &BlockChain{ 245 chainConfig: chainConfig, 246 cacheConfig: cacheConfig, 247 db: db, 248 triegc: prque.New(nil), 249 stateCache: state.NewDatabaseWithConfig(db, &trie.Config{ 250 Cache: cacheConfig.TrieCleanLimit, 251 Journal: cacheConfig.TrieCleanJournal, 252 Preimages: cacheConfig.Preimages, 253 }), 254 quit: make(chan struct{}), 255 shouldPreserve: shouldPreserve, 256 bodyCache: bodyCache, 257 bodyRLPCache: bodyRLPCache, 258 receiptsCache: receiptsCache, 259 blockCache: blockCache, 260 txLookupCache: txLookupCache, 261 futureBlocks: futureBlocks, 262 engine: engine, 263 vmConfig: vmConfig, 264 // Quorum 265 quorumConfig: quorumChainConfig, 266 } 267 bc.validator = NewBlockValidator(chainConfig, bc, engine) 268 bc.prefetcher = newStatePrefetcher(chainConfig, bc, engine) 269 bc.processor = NewStateProcessor(chainConfig, bc, engine) 270 271 var err error 272 privateStateCacheProvider := privatecache.NewPrivateCacheProvider(db, &trie.Config{Cache: cacheConfig.TrieCleanLimit, 273 Preimages: cacheConfig.Preimages}, bc.stateCache, quorumChainConfig.privateTrieCacheEnabled) 274 // Quorum: attempt to initialize PSM 275 if bc.privateStateManager, err = newPrivateStateManager(bc.db, privateStateCacheProvider, chainConfig.IsMPS); err != nil { 276 return nil, err 277 } 278 bc.hc, err = NewHeaderChain(db, chainConfig, engine, bc.insertStopped) 279 if err != nil { 280 return nil, err 281 } 282 bc.genesisBlock = bc.GetBlockByNumber(0) 283 if bc.genesisBlock == nil { 284 return nil, ErrNoGenesis 285 } 286 287 var nilBlock *types.Block 288 bc.currentBlock.Store(nilBlock) 289 bc.currentFastBlock.Store(nilBlock) 290 291 // Initialize the chain with ancient data if it isn't empty. 292 var txIndexBlock uint64 293 294 if bc.empty() { 295 rawdb.InitDatabaseFromFreezer(bc.db) 296 // If ancient database is not empty, reconstruct all missing 297 // indices in the background. 298 frozen, _ := bc.db.Ancients() 299 if frozen > 0 { 300 txIndexBlock = frozen 301 } 302 } 303 if err := bc.loadLastState(); err != nil { 304 return nil, err 305 } 306 // Make sure the state associated with the block is available 307 head := bc.CurrentBlock() 308 if _, err := state.New(head.Root(), bc.stateCache, bc.snaps); err != nil { 309 // Head state is missing, before the state recovery, find out the 310 // disk layer point of snapshot(if it's enabled). Make sure the 311 // rewound point is lower than disk layer. 312 var diskRoot common.Hash 313 if bc.cacheConfig.SnapshotLimit > 0 { 314 diskRoot = rawdb.ReadSnapshotRoot(bc.db) 315 } 316 if diskRoot != (common.Hash{}) { 317 log.Warn("Head state missing, repairing", "number", head.Number(), "hash", head.Hash(), "snaproot", diskRoot) 318 319 snapDisk, err := bc.SetHeadBeyondRoot(head.NumberU64(), diskRoot) 320 if err != nil { 321 return nil, err 322 } 323 // Chain rewound, persist old snapshot number to indicate recovery procedure 324 if snapDisk != 0 { 325 rawdb.WriteSnapshotRecoveryNumber(bc.db, snapDisk) 326 } 327 } else { 328 log.Warn("Head state missing, repairing", "number", head.Number(), "hash", head.Hash()) 329 if err := bc.SetHead(head.NumberU64()); err != nil { 330 return nil, err 331 } 332 } 333 } 334 335 // Quorum 336 if err := bc.privateStateManager.CheckAt(head.Root()); err != nil { 337 log.Warn("Head private state missing, resetting chain", "number", head.Number(), "hash", head.Hash()) 338 return nil, bc.Reset() 339 } 340 // End Quorum 341 342 // Ensure that a previous crash in SetHead doesn't leave extra ancients 343 if frozen, err := bc.db.Ancients(); err == nil && frozen > 0 { 344 var ( 345 needRewind bool 346 low uint64 347 ) 348 // The head full block may be rolled back to a very low height due to 349 // blockchain repair. If the head full block is even lower than the ancient 350 // chain, truncate the ancient store. 351 fullBlock := bc.CurrentBlock() 352 if fullBlock != nil && fullBlock.Hash() != bc.genesisBlock.Hash() && fullBlock.NumberU64() < frozen-1 { 353 needRewind = true 354 low = fullBlock.NumberU64() 355 } 356 // In fast sync, it may happen that ancient data has been written to the 357 // ancient store, but the LastFastBlock has not been updated, truncate the 358 // extra data here. 359 fastBlock := bc.CurrentFastBlock() 360 if fastBlock != nil && fastBlock.NumberU64() < frozen-1 { 361 needRewind = true 362 if fastBlock.NumberU64() < low || low == 0 { 363 low = fastBlock.NumberU64() 364 } 365 } 366 if needRewind { 367 log.Error("Truncating ancient chain", "from", bc.CurrentHeader().Number.Uint64(), "to", low) 368 if err := bc.SetHead(low); err != nil { 369 return nil, err 370 } 371 } 372 } 373 // The first thing the node will do is reconstruct the verification data for 374 // the head block (ethash cache or clique voting snapshot). Might as well do 375 // it in advance. 376 bc.engine.VerifyHeader(bc, bc.CurrentHeader(), true) 377 378 // Check the current state of the block hashes and make sure that we do not have any of the bad blocks in our chain 379 for hash := range BadHashes { 380 if header := bc.GetHeaderByHash(hash); header != nil { 381 // get the canonical block corresponding to the offending header's number 382 headerByNumber := bc.GetHeaderByNumber(header.Number.Uint64()) 383 // make sure the headerByNumber (if present) is in our current canonical chain 384 if headerByNumber != nil && headerByNumber.Hash() == header.Hash() { 385 log.Error("Found bad hash, rewinding chain", "number", header.Number, "hash", header.ParentHash) 386 if err := bc.SetHead(header.Number.Uint64() - 1); err != nil { 387 return nil, err 388 } 389 log.Error("Chain rewind was successful, resuming normal operation") 390 } 391 } 392 } 393 // Load any existing snapshot, regenerating it if loading failed 394 if bc.cacheConfig.SnapshotLimit > 0 { 395 // If the chain was rewound past the snapshot persistent layer (causing 396 // a recovery block number to be persisted to disk), check if we're still 397 // in recovery mode and in that case, don't invalidate the snapshot on a 398 // head mismatch. 399 var recover bool 400 401 head := bc.CurrentBlock() 402 if layer := rawdb.ReadSnapshotRecoveryNumber(bc.db); layer != nil && *layer > head.NumberU64() { 403 log.Warn("Enabling snapshot recovery", "chainhead", head.NumberU64(), "diskbase", *layer) 404 recover = true 405 } 406 bc.snaps, err = snapshot.New(bc.db, bc.stateCache.TrieDB(), bc.cacheConfig.SnapshotLimit, head.Root(), !bc.cacheConfig.SnapshotWait, true, recover) 407 if err != nil { 408 log.Error("Error trying to load snapshot", "err", err) 409 } 410 } 411 // Take ownership of this particular state 412 go bc.update() 413 if txLookupLimit != nil { 414 bc.txLookupLimit = *txLookupLimit 415 416 bc.wg.Add(1) 417 go bc.maintainTxIndex(txIndexBlock) 418 } 419 // If periodic cache journal is required, spin it up. 420 if bc.cacheConfig.TrieCleanRejournal > 0 { 421 if bc.cacheConfig.TrieCleanRejournal < time.Minute { 422 log.Warn("Sanitizing invalid trie cache journal time", "provided", bc.cacheConfig.TrieCleanRejournal, "updated", time.Minute) 423 bc.cacheConfig.TrieCleanRejournal = time.Minute 424 } 425 triedb := bc.stateCache.TrieDB() 426 bc.wg.Add(1) 427 go func() { 428 defer bc.wg.Done() 429 triedb.SaveCachePeriodically(bc.cacheConfig.TrieCleanJournal, bc.cacheConfig.TrieCleanRejournal, bc.quit) 430 }() 431 } 432 return bc, nil 433 } 434 435 // Quorum 436 // Decorates NewBlockChain with multitenancy flag 437 func NewMultitenantBlockChain(db ethdb.Database, cacheConfig *CacheConfig, chainConfig *params.ChainConfig, engine consensus.Engine, vmConfig vm.Config, shouldPreserve func(block *types.Block) bool, txLookupLimit *uint64, quorumChainConfig *QuorumChainConfig) (*BlockChain, error) { 438 if quorumChainConfig == nil { 439 quorumChainConfig = &QuorumChainConfig{multiTenantEnabled: true} 440 } else { 441 quorumChainConfig.multiTenantEnabled = true 442 } 443 bc, err := NewBlockChain(db, cacheConfig, chainConfig, engine, vmConfig, shouldPreserve, txLookupLimit, quorumChainConfig) 444 if err != nil { 445 return nil, err 446 } 447 return bc, err 448 } 449 450 func (bc *BlockChain) PrivateStateManager() mps.PrivateStateManager { 451 return bc.privateStateManager 452 } 453 454 func (bc *BlockChain) SetPrivateStateManager(psm mps.PrivateStateManager) { 455 bc.privateStateManager = psm 456 } 457 458 // End Quorum 459 460 // GetVMConfig returns the block chain VM config. 461 func (bc *BlockChain) GetVMConfig() *vm.Config { 462 return &bc.vmConfig 463 } 464 465 // empty returns an indicator whether the blockchain is empty. 466 // Note, it's a special case that we connect a non-empty ancient 467 // database with an empty node, so that we can plugin the ancient 468 // into node seamlessly. 469 func (bc *BlockChain) empty() bool { 470 genesis := bc.genesisBlock.Hash() 471 for _, hash := range []common.Hash{rawdb.ReadHeadBlockHash(bc.db), rawdb.ReadHeadHeaderHash(bc.db), rawdb.ReadHeadFastBlockHash(bc.db)} { 472 if hash != genesis { 473 return false 474 } 475 } 476 return true 477 } 478 479 // loadLastState loads the last known chain state from the database. This method 480 // assumes that the chain manager mutex is held. 481 func (bc *BlockChain) loadLastState() error { 482 // Restore the last known head block 483 head := rawdb.ReadHeadBlockHash(bc.db) 484 if head == (common.Hash{}) { 485 // Corrupt or empty database, init from scratch 486 log.Warn("Empty database, resetting chain") 487 return bc.Reset() 488 } 489 // Make sure the entire head block is available 490 currentBlock := bc.GetBlockByHash(head) 491 if currentBlock == nil { 492 // Corrupt or empty database, init from scratch 493 log.Warn("Head block missing, resetting chain", "hash", head) 494 return bc.Reset() 495 } 496 497 // Quorum 498 if _, err := bc.privateStateManager.StateRepository(currentBlock.Root()); err != nil { 499 log.Warn("Head private state missing, resetting chain", "number", currentBlock.Number(), "hash", currentBlock.Hash()) 500 bc.currentBlock.Store(currentBlock) 501 return bc.Reset() 502 } 503 // /Quorum 504 505 // Everything seems to be fine, set as the head block 506 bc.currentBlock.Store(currentBlock) 507 headBlockGauge.Update(int64(currentBlock.NumberU64())) 508 509 // Restore the last known head header 510 currentHeader := currentBlock.Header() 511 if head := rawdb.ReadHeadHeaderHash(bc.db); head != (common.Hash{}) { 512 if header := bc.GetHeaderByHash(head); header != nil { 513 currentHeader = header 514 } 515 } 516 bc.hc.SetCurrentHeader(currentHeader) 517 518 // Restore the last known head fast block 519 bc.currentFastBlock.Store(currentBlock) 520 headFastBlockGauge.Update(int64(currentBlock.NumberU64())) 521 522 if head := rawdb.ReadHeadFastBlockHash(bc.db); head != (common.Hash{}) { 523 if block := bc.GetBlockByHash(head); block != nil { 524 bc.currentFastBlock.Store(block) 525 headFastBlockGauge.Update(int64(block.NumberU64())) 526 } 527 } 528 // Issue a status log for the user 529 currentFastBlock := bc.CurrentFastBlock() 530 531 headerTd := bc.GetTd(currentHeader.Hash(), currentHeader.Number.Uint64()) 532 blockTd := bc.GetTd(currentBlock.Hash(), currentBlock.NumberU64()) 533 fastTd := bc.GetTd(currentFastBlock.Hash(), currentFastBlock.NumberU64()) 534 535 log.Info("Loaded most recent local header", "number", currentHeader.Number, "hash", currentHeader.Hash(), "td", headerTd, "age", common.PrettyAge(time.Unix(int64(currentHeader.Time), 0))) 536 log.Info("Loaded most recent local full block", "number", currentBlock.Number(), "hash", currentBlock.Hash(), "td", blockTd, "age", common.PrettyAge(time.Unix(int64(currentBlock.Time()), 0))) 537 log.Info("Loaded most recent local fast block", "number", currentFastBlock.Number(), "hash", currentFastBlock.Hash(), "td", fastTd, "age", common.PrettyAge(time.Unix(int64(currentFastBlock.Time()), 0))) 538 if pivot := rawdb.ReadLastPivotNumber(bc.db); pivot != nil { 539 log.Info("Loaded last fast-sync pivot marker", "number", *pivot) 540 } 541 return nil 542 } 543 544 // SetHead rewinds the local chain to a new head. Depending on whether the node 545 // was fast synced or full synced and in which state, the method will try to 546 // delete minimal data from disk whilst retaining chain consistency. 547 func (bc *BlockChain) SetHead(head uint64) error { 548 _, err := bc.SetHeadBeyondRoot(head, common.Hash{}) 549 return err 550 } 551 552 // SetHeadBeyondRoot rewinds the local chain to a new head with the extra condition 553 // that the rewind must pass the specified state root. This method is meant to be 554 // used when rewinding with snapshots enabled to ensure that we go back further than 555 // persistent disk layer. Depending on whether the node was fast synced or full, and 556 // in which state, the method will try to delete minimal data from disk whilst 557 // retaining chain consistency. 558 // 559 // The method returns the block number where the requested root cap was found. 560 func (bc *BlockChain) SetHeadBeyondRoot(head uint64, root common.Hash) (uint64, error) { 561 bc.chainmu.Lock() 562 defer bc.chainmu.Unlock() 563 564 // Track the block number of the requested root hash 565 var rootNumber uint64 // (no root == always 0) 566 567 // Retrieve the last pivot block to short circuit rollbacks beyond it and the 568 // current freezer limit to start nuking id underflown 569 pivot := rawdb.ReadLastPivotNumber(bc.db) 570 frozen, _ := bc.db.Ancients() 571 572 updateFn := func(db ethdb.KeyValueWriter, header *types.Header) (uint64, bool) { 573 // Rewind the block chain, ensuring we don't end up with a stateless head 574 // block. Note, depth equality is permitted to allow using SetHead as a 575 // chain reparation mechanism without deleting any data! 576 if currentBlock := bc.CurrentBlock(); currentBlock != nil && header.Number.Uint64() <= currentBlock.NumberU64() { 577 newHeadBlock := bc.GetBlock(header.Hash(), header.Number.Uint64()) 578 if newHeadBlock == nil { 579 log.Error("Gap in the chain, rewinding to genesis", "number", header.Number, "hash", header.Hash()) 580 newHeadBlock = bc.genesisBlock 581 } else { 582 // Block exists, keep rewinding until we find one with state, 583 // keeping rewinding until we exceed the optional threshold 584 // root hash 585 beyondRoot := (root == common.Hash{}) // Flag whether we're beyond the requested root (no root, always true) 586 587 for { 588 // If a root threshold was requested but not yet crossed, check 589 if root != (common.Hash{}) && !beyondRoot && newHeadBlock.Root() == root { 590 beyondRoot, rootNumber = true, newHeadBlock.NumberU64() 591 } 592 if _, err := state.New(newHeadBlock.Root(), bc.stateCache, bc.snaps); err != nil { 593 log.Trace("Block state missing, rewinding further", "number", newHeadBlock.NumberU64(), "hash", newHeadBlock.Hash()) 594 if pivot == nil || newHeadBlock.NumberU64() > *pivot { 595 parent := bc.GetBlock(newHeadBlock.ParentHash(), newHeadBlock.NumberU64()-1) 596 if parent != nil { 597 newHeadBlock = parent 598 continue 599 } 600 log.Error("Missing block in the middle, aiming genesis", "number", newHeadBlock.NumberU64()-1, "hash", newHeadBlock.ParentHash()) 601 newHeadBlock = bc.genesisBlock 602 } else { 603 log.Trace("Rewind passed pivot, aiming genesis", "number", newHeadBlock.NumberU64(), "hash", newHeadBlock.Hash(), "pivot", *pivot) 604 newHeadBlock = bc.genesisBlock 605 } 606 } 607 if beyondRoot || newHeadBlock.NumberU64() == 0 { 608 log.Debug("Rewound to block with state", "number", newHeadBlock.NumberU64(), "hash", newHeadBlock.Hash()) 609 break 610 } 611 log.Debug("Skipping block with threshold state", "number", newHeadBlock.NumberU64(), "hash", newHeadBlock.Hash(), "root", newHeadBlock.Root()) 612 newHeadBlock = bc.GetBlock(newHeadBlock.ParentHash(), newHeadBlock.NumberU64()-1) // Keep rewinding 613 } 614 } 615 rawdb.WriteHeadBlockHash(db, newHeadBlock.Hash()) 616 617 // Degrade the chain markers if they are explicitly reverted. 618 // In theory we should update all in-memory markers in the 619 // last step, however the direction of SetHead is from high 620 // to low, so it's safe the update in-memory markers directly. 621 bc.currentBlock.Store(newHeadBlock) 622 headBlockGauge.Update(int64(newHeadBlock.NumberU64())) 623 } 624 // Rewind the fast block in a simpleton way to the target head 625 if currentFastBlock := bc.CurrentFastBlock(); currentFastBlock != nil && header.Number.Uint64() < currentFastBlock.NumberU64() { 626 newHeadFastBlock := bc.GetBlock(header.Hash(), header.Number.Uint64()) 627 // If either blocks reached nil, reset to the genesis state 628 if newHeadFastBlock == nil { 629 newHeadFastBlock = bc.genesisBlock 630 } 631 rawdb.WriteHeadFastBlockHash(db, newHeadFastBlock.Hash()) 632 633 // Degrade the chain markers if they are explicitly reverted. 634 // In theory we should update all in-memory markers in the 635 // last step, however the direction of SetHead is from high 636 // to low, so it's safe the update in-memory markers directly. 637 bc.currentFastBlock.Store(newHeadFastBlock) 638 headFastBlockGauge.Update(int64(newHeadFastBlock.NumberU64())) 639 } 640 localHead := head 641 if bc.CurrentBlock() != nil { 642 localHead = bc.CurrentBlock().NumberU64() 643 } 644 645 // If setHead underflown the freezer threshold and the block processing 646 // intent afterwards is full block importing, delete the chain segment 647 // between the stateful-block and the sethead target. 648 var wipe bool 649 if localHead+1 < frozen { 650 wipe = pivot == nil || localHead >= *pivot 651 } 652 return localHead, wipe // Only force wipe if full synced 653 } 654 // Rewind the header chain, deleting all block bodies until then 655 delFn := func(db ethdb.KeyValueWriter, hash common.Hash, num uint64) { 656 // Ignore the error here since light client won't hit this path 657 frozen, _ := bc.db.Ancients() 658 if num+1 <= frozen { 659 // Truncate all relative data(header, total difficulty, body, receipt 660 // and canonical hash) from ancient store. 661 if err := bc.db.TruncateAncients(num); err != nil { 662 log.Crit("Failed to truncate ancient data", "number", num, "err", err) 663 } 664 // Remove the hash <-> number mapping from the active store. 665 rawdb.DeleteHeaderNumber(db, hash) 666 } else { 667 // Remove relative body and receipts from the active store. 668 // The header, total difficulty and canonical hash will be 669 // removed in the hc.SetHead function. 670 rawdb.DeleteBody(db, hash, num) 671 rawdb.DeleteReceipts(db, hash, num) 672 } 673 // Todo(rjl493456442) txlookup, bloombits, etc 674 } 675 // If SetHead was only called as a chain reparation method, try to skip 676 // touching the header chain altogether, unless the freezer is broken 677 if block := bc.CurrentBlock(); block != nil && block.NumberU64() == head { 678 if target, force := updateFn(bc.db, block.Header()); force { 679 bc.hc.SetHead(target, updateFn, delFn) 680 } 681 } else { 682 // Rewind the chain to the requested head and keep going backwards until a 683 // block with a state is found or fast sync pivot is passed 684 log.Warn("Rewinding blockchain", "target", head) 685 bc.hc.SetHead(head, updateFn, delFn) 686 } 687 // Clear out any stale content from the caches 688 bc.bodyCache.Purge() 689 bc.bodyRLPCache.Purge() 690 bc.receiptsCache.Purge() 691 bc.blockCache.Purge() 692 bc.txLookupCache.Purge() 693 bc.futureBlocks.Purge() 694 695 return rootNumber, bc.loadLastState() 696 } 697 698 // FastSyncCommitHead sets the current head block to the one defined by the hash 699 // irrelevant what the chain contents were prior. 700 func (bc *BlockChain) FastSyncCommitHead(hash common.Hash) error { 701 // Make sure that both the block as well at its state trie exists 702 block := bc.GetBlockByHash(hash) 703 if block == nil { 704 return fmt.Errorf("non existent block [%x..]", hash[:4]) 705 } 706 if _, err := trie.NewSecure(block.Root(), bc.stateCache.TrieDB()); err != nil { 707 return err 708 } 709 // If all checks out, manually set the head block 710 bc.chainmu.Lock() 711 bc.currentBlock.Store(block) 712 headBlockGauge.Update(int64(block.NumberU64())) 713 bc.chainmu.Unlock() 714 715 // Destroy any existing state snapshot and regenerate it in the background, 716 // also resuming the normal maintenance of any previously paused snapshot. 717 if bc.snaps != nil { 718 bc.snaps.Rebuild(block.Root()) 719 } 720 log.Info("Committed new head block", "number", block.Number(), "hash", hash) 721 return nil 722 } 723 724 // GasLimit returns the gas limit of the current HEAD block. 725 func (bc *BlockChain) GasLimit() uint64 { 726 bc.chainmu.RLock() 727 defer bc.chainmu.RUnlock() 728 729 return bc.CurrentBlock().GasLimit() 730 } 731 732 // CurrentBlock retrieves the current head block of the canonical chain. The 733 // block is retrieved from the blockchain's internal cache. 734 func (bc *BlockChain) CurrentBlock() *types.Block { 735 return bc.currentBlock.Load().(*types.Block) 736 } 737 738 // Snapshots returns the blockchain snapshot tree. 739 func (bc *BlockChain) Snapshots() *snapshot.Tree { 740 return bc.snaps 741 } 742 743 // CurrentFastBlock retrieves the current fast-sync head block of the canonical 744 // chain. The block is retrieved from the blockchain's internal cache. 745 func (bc *BlockChain) CurrentFastBlock() *types.Block { 746 return bc.currentFastBlock.Load().(*types.Block) 747 } 748 749 // Validator returns the current validator. 750 func (bc *BlockChain) Validator() Validator { 751 return bc.validator 752 } 753 754 // Processor returns the current processor. 755 func (bc *BlockChain) Processor() Processor { 756 return bc.processor 757 } 758 759 // State returns a new mutable state based on the current HEAD block. 760 func (bc *BlockChain) State() (*state.StateDB, mps.PrivateStateRepository, error) { 761 return bc.StateAt(bc.CurrentBlock().Root()) 762 } 763 764 // Quorum 765 // 766 // StatePSI returns a new mutable public state and a mutable private state for given PSI, 767 // based on the current HEAD block. 768 func (bc *BlockChain) StatePSI(psi types.PrivateStateIdentifier) (*state.StateDB, *state.StateDB, error) { 769 return bc.StateAtPSI(bc.CurrentBlock().Root(), psi) 770 } 771 772 // Quorum 773 // 774 // SetPrivateStateRootHashValidator allows injecting a private state root hash validator 775 func (bc *BlockChain) SetPrivateStateRootHashValidator(psrhv qlight.PrivateStateRootHashValidator) { 776 bc.privateStateRootHashValidator = psrhv 777 } 778 779 // StatePSI returns a new mutable public state and a mutable private state for the given PSI, 780 // based on a particular point in time. 781 func (bc *BlockChain) StateAtPSI(root common.Hash, psi types.PrivateStateIdentifier) (*state.StateDB, *state.StateDB, error) { 782 publicStateDb, privateStateRepo, err := bc.StateAt(root) 783 if err != nil { 784 return nil, nil, err 785 } 786 787 privateStateDb, privateStateDbErr := privateStateRepo.StatePSI(psi) 788 if privateStateDbErr != nil { 789 return nil, nil, privateStateDbErr 790 } 791 792 return publicStateDb, privateStateDb, nil 793 } 794 795 // StateAt returns a new mutable public state and a new mutable private state repo 796 // based on a particular point in time. The returned private state repo can be used 797 // to obtain a mutable private state for a given PSI 798 func (bc *BlockChain) StateAt(root common.Hash) (*state.StateDB, mps.PrivateStateRepository, error) { 799 publicStateDb, publicStateDbErr := state.New(root, bc.stateCache, bc.snaps) 800 if publicStateDbErr != nil { 801 return nil, nil, publicStateDbErr 802 } 803 804 privateStateRepo, privateStateRepoErr := bc.privateStateManager.StateRepository(root) 805 if privateStateRepoErr != nil { 806 return nil, nil, privateStateRepoErr 807 } 808 809 return publicStateDb, privateStateRepo, nil 810 } 811 812 // StateCache returns the caching database underpinning the blockchain instance. 813 func (bc *BlockChain) StateCache() state.Database { 814 return bc.stateCache 815 } 816 817 // Reset purges the entire blockchain, restoring it to its genesis state. 818 func (bc *BlockChain) Reset() error { 819 return bc.ResetWithGenesisBlock(bc.genesisBlock) 820 } 821 822 // ResetWithGenesisBlock purges the entire blockchain, restoring it to the 823 // specified genesis state. 824 func (bc *BlockChain) ResetWithGenesisBlock(genesis *types.Block) error { 825 // Dump the entire block chain and purge the caches 826 if err := bc.SetHead(0); err != nil { 827 return err 828 } 829 bc.chainmu.Lock() 830 defer bc.chainmu.Unlock() 831 832 // Prepare the genesis block and reinitialise the chain 833 batch := bc.db.NewBatch() 834 rawdb.WriteTd(batch, genesis.Hash(), genesis.NumberU64(), genesis.Difficulty()) 835 rawdb.WriteBlock(batch, genesis) 836 if err := batch.Write(); err != nil { 837 log.Crit("Failed to write genesis block", "err", err) 838 } 839 bc.writeHeadBlock(genesis) 840 841 // Last update all in-memory chain markers 842 bc.genesisBlock = genesis 843 bc.currentBlock.Store(bc.genesisBlock) 844 headBlockGauge.Update(int64(bc.genesisBlock.NumberU64())) 845 bc.hc.SetGenesis(bc.genesisBlock.Header()) 846 bc.hc.SetCurrentHeader(bc.genesisBlock.Header()) 847 bc.currentFastBlock.Store(bc.genesisBlock) 848 headFastBlockGauge.Update(int64(bc.genesisBlock.NumberU64())) 849 return nil 850 } 851 852 // Export writes the active chain to the given writer. 853 func (bc *BlockChain) Export(w io.Writer) error { 854 return bc.ExportN(w, uint64(0), bc.CurrentBlock().NumberU64()) 855 } 856 857 // ExportN writes a subset of the active chain to the given writer. 858 func (bc *BlockChain) ExportN(w io.Writer, first uint64, last uint64) error { 859 bc.chainmu.RLock() 860 defer bc.chainmu.RUnlock() 861 862 if first > last { 863 return fmt.Errorf("export failed: first (%d) is greater than last (%d)", first, last) 864 } 865 log.Info("Exporting batch of blocks", "count", last-first+1) 866 867 start, reported := time.Now(), time.Now() 868 for nr := first; nr <= last; nr++ { 869 block := bc.GetBlockByNumber(nr) 870 if block == nil { 871 return fmt.Errorf("export failed on #%d: not found", nr) 872 } 873 if err := block.EncodeRLP(w); err != nil { 874 return err 875 } 876 if time.Since(reported) >= statsReportLimit { 877 log.Info("Exporting blocks", "exported", block.NumberU64()-first, "elapsed", common.PrettyDuration(time.Since(start))) 878 reported = time.Now() 879 } 880 } 881 return nil 882 } 883 884 // writeHeadBlock injects a new head block into the current block chain. This method 885 // assumes that the block is indeed a true head. It will also reset the head 886 // header and the head fast sync block to this very same block if they are older 887 // or if they are on a different side chain. 888 // 889 // Note, this function assumes that the `mu` mutex is held! 890 func (bc *BlockChain) writeHeadBlock(block *types.Block) { 891 // If the block is on a side chain or an unknown one, force other heads onto it too 892 updateHeads := rawdb.ReadCanonicalHash(bc.db, block.NumberU64()) != block.Hash() 893 894 // Add the block to the canonical chain number scheme and mark as the head 895 batch := bc.db.NewBatch() 896 rawdb.WriteCanonicalHash(batch, block.Hash(), block.NumberU64()) 897 rawdb.WriteTxLookupEntriesByBlock(batch, block) 898 rawdb.WriteHeadBlockHash(batch, block.Hash()) 899 900 // If the block is better than our head or is on a different chain, force update heads 901 if updateHeads { 902 rawdb.WriteHeadHeaderHash(batch, block.Hash()) 903 rawdb.WriteHeadFastBlockHash(batch, block.Hash()) 904 } 905 // Flush the whole batch into the disk, exit the node if failed 906 if err := batch.Write(); err != nil { 907 log.Crit("Failed to update chain indexes and markers", "err", err) 908 } 909 // Update all in-memory chain markers in the last step 910 if updateHeads { 911 bc.hc.SetCurrentHeader(block.Header()) 912 bc.currentFastBlock.Store(block) 913 headFastBlockGauge.Update(int64(block.NumberU64())) 914 } 915 bc.currentBlock.Store(block) 916 headBlockGauge.Update(int64(block.NumberU64())) 917 } 918 919 // Genesis retrieves the chain's genesis block. 920 func (bc *BlockChain) Genesis() *types.Block { 921 return bc.genesisBlock 922 } 923 924 // GetBody retrieves a block body (transactions and uncles) from the database by 925 // hash, caching it if found. 926 func (bc *BlockChain) GetBody(hash common.Hash) *types.Body { 927 // Short circuit if the body's already in the cache, retrieve otherwise 928 if cached, ok := bc.bodyCache.Get(hash); ok { 929 body := cached.(*types.Body) 930 return body 931 } 932 number := bc.hc.GetBlockNumber(hash) 933 if number == nil { 934 return nil 935 } 936 body := rawdb.ReadBody(bc.db, hash, *number) 937 if body == nil { 938 return nil 939 } 940 // Cache the found body for next time and return 941 bc.bodyCache.Add(hash, body) 942 return body 943 } 944 945 // GetBodyRLP retrieves a block body in RLP encoding from the database by hash, 946 // caching it if found. 947 func (bc *BlockChain) GetBodyRLP(hash common.Hash) rlp.RawValue { 948 // Short circuit if the body's already in the cache, retrieve otherwise 949 if cached, ok := bc.bodyRLPCache.Get(hash); ok { 950 return cached.(rlp.RawValue) 951 } 952 number := bc.hc.GetBlockNumber(hash) 953 if number == nil { 954 return nil 955 } 956 body := rawdb.ReadBodyRLP(bc.db, hash, *number) 957 if len(body) == 0 { 958 return nil 959 } 960 // Cache the found body for next time and return 961 bc.bodyRLPCache.Add(hash, body) 962 return body 963 } 964 965 // HasBlock checks if a block is fully present in the database or not. 966 func (bc *BlockChain) HasBlock(hash common.Hash, number uint64) bool { 967 if bc.blockCache.Contains(hash) { 968 return true 969 } 970 return rawdb.HasBody(bc.db, hash, number) 971 } 972 973 // HasFastBlock checks if a fast block is fully present in the database or not. 974 func (bc *BlockChain) HasFastBlock(hash common.Hash, number uint64) bool { 975 if !bc.HasBlock(hash, number) { 976 return false 977 } 978 if bc.receiptsCache.Contains(hash) { 979 return true 980 } 981 return rawdb.HasReceipts(bc.db, hash, number) 982 } 983 984 // HasState checks if state trie is fully present in the database or not. 985 func (bc *BlockChain) HasState(hash common.Hash) bool { 986 _, err := bc.stateCache.OpenTrie(hash) 987 return err == nil 988 } 989 990 // HasBlockAndState checks if a block and associated state trie is fully present 991 // in the database or not, caching it if present. 992 func (bc *BlockChain) HasBlockAndState(hash common.Hash, number uint64) bool { 993 // Check first that the block itself is known 994 block := bc.GetBlock(hash, number) 995 if block == nil { 996 return false 997 } 998 return bc.HasState(block.Root()) 999 } 1000 1001 // GetBlock retrieves a block from the database by hash and number, 1002 // caching it if found. 1003 func (bc *BlockChain) GetBlock(hash common.Hash, number uint64) *types.Block { 1004 // Short circuit if the block's already in the cache, retrieve otherwise 1005 if block, ok := bc.blockCache.Get(hash); ok { 1006 return block.(*types.Block) 1007 } 1008 block := rawdb.ReadBlock(bc.db, hash, number) 1009 if block == nil { 1010 return nil 1011 } 1012 // Cache the found block for next time and return 1013 bc.blockCache.Add(block.Hash(), block) 1014 return block 1015 } 1016 1017 // GetBlockByHash retrieves a block from the database by hash, caching it if found. 1018 func (bc *BlockChain) GetBlockByHash(hash common.Hash) *types.Block { 1019 number := bc.hc.GetBlockNumber(hash) 1020 if number == nil { 1021 return nil 1022 } 1023 return bc.GetBlock(hash, *number) 1024 } 1025 1026 // GetBlockByNumber retrieves a block from the database by number, caching it 1027 // (associated with its hash) if found. 1028 func (bc *BlockChain) GetBlockByNumber(number uint64) *types.Block { 1029 hash := rawdb.ReadCanonicalHash(bc.db, number) 1030 if hash == (common.Hash{}) { 1031 return nil 1032 } 1033 return bc.GetBlock(hash, number) 1034 } 1035 1036 // GetReceiptsByHash retrieves the receipts for all transactions in a given block. 1037 func (bc *BlockChain) GetReceiptsByHash(hash common.Hash) types.Receipts { 1038 if receipts, ok := bc.receiptsCache.Get(hash); ok { 1039 return receipts.(types.Receipts) 1040 } 1041 number := rawdb.ReadHeaderNumber(bc.db, hash) 1042 if number == nil { 1043 return nil 1044 } 1045 receipts := rawdb.ReadReceipts(bc.db, hash, *number, bc.chainConfig) 1046 if receipts == nil { 1047 return nil 1048 } 1049 bc.receiptsCache.Add(hash, receipts) 1050 return receipts 1051 } 1052 1053 // (Quorum) GetPMTPrivateReceiptsByHash retrieves the receipts for all internal private transactions (i.e. the private 1054 // transaction for a privacy marker transaction) in a given block. 1055 func (bc *BlockChain) GetPMTPrivateReceiptsByHash(ctx context.Context, hash common.Hash) (types.Receipts, error) { 1056 psm, err := bc.privateStateManager.ResolveForUserContext(ctx) 1057 if err != nil { 1058 return nil, err 1059 } 1060 1061 allReceipts := bc.GetReceiptsByHash(hash) 1062 1063 block := bc.GetBlockByHash(hash) 1064 if block == nil { 1065 return types.Receipts{}, nil 1066 } 1067 1068 privateReceipts := make([]*types.Receipt, 0) 1069 for i, tx := range block.Transactions() { 1070 if tx.IsPrivacyMarker() { 1071 receipt := allReceipts[i] 1072 if receipt.PSReceipts != nil && receipt.PSReceipts[psm.ID] != nil { 1073 privateReceipts = append(privateReceipts, receipt.PSReceipts[psm.ID]) 1074 } else { 1075 return nil, errors.New("could not find receipt for private transaction") 1076 } 1077 } 1078 } 1079 return privateReceipts, nil 1080 } 1081 1082 // GetBlocksFromHash returns the block corresponding to hash and up to n-1 ancestors. 1083 // [deprecated by eth/62] 1084 func (bc *BlockChain) GetBlocksFromHash(hash common.Hash, n int) (blocks []*types.Block) { 1085 number := bc.hc.GetBlockNumber(hash) 1086 if number == nil { 1087 return nil 1088 } 1089 for i := 0; i < n; i++ { 1090 block := bc.GetBlock(hash, *number) 1091 if block == nil { 1092 break 1093 } 1094 blocks = append(blocks, block) 1095 hash = block.ParentHash() 1096 *number-- 1097 } 1098 return 1099 } 1100 1101 // GetUnclesInChain retrieves all the uncles from a given block backwards until 1102 // a specific distance is reached. 1103 func (bc *BlockChain) GetUnclesInChain(block *types.Block, length int) []*types.Header { 1104 uncles := []*types.Header{} 1105 for i := 0; block != nil && i < length; i++ { 1106 uncles = append(uncles, block.Uncles()...) 1107 block = bc.GetBlock(block.ParentHash(), block.NumberU64()-1) 1108 } 1109 return uncles 1110 } 1111 1112 // TrieNode retrieves a blob of data associated with a trie node 1113 // either from ephemeral in-memory cache, or from persistent storage. 1114 func (bc *BlockChain) TrieNode(hash common.Hash) ([]byte, error) { 1115 return bc.stateCache.TrieDB().Node(hash) 1116 } 1117 1118 // ContractCode retrieves a blob of data associated with a contract hash 1119 // either from ephemeral in-memory cache, or from persistent storage. 1120 func (bc *BlockChain) ContractCode(hash common.Hash) ([]byte, error) { 1121 return bc.stateCache.ContractCode(common.Hash{}, hash) 1122 } 1123 1124 // ContractCodeWithPrefix retrieves a blob of data associated with a contract 1125 // hash either from ephemeral in-memory cache, or from persistent storage. 1126 // 1127 // If the code doesn't exist in the in-memory cache, check the storage with 1128 // new code scheme. 1129 func (bc *BlockChain) ContractCodeWithPrefix(hash common.Hash) ([]byte, error) { 1130 type codeReader interface { 1131 ContractCodeWithPrefix(addrHash, codeHash common.Hash) ([]byte, error) 1132 } 1133 return bc.stateCache.(codeReader).ContractCodeWithPrefix(common.Hash{}, hash) 1134 } 1135 1136 // Stop stops the blockchain service. If any imports are currently in progress 1137 // it will abort them using the procInterrupt. 1138 func (bc *BlockChain) Stop() { 1139 if !atomic.CompareAndSwapInt32(&bc.running, 0, 1) { 1140 return 1141 } 1142 // Unsubscribe all subscriptions registered from blockchain 1143 bc.scope.Close() 1144 close(bc.quit) 1145 bc.StopInsert() 1146 bc.wg.Wait() 1147 1148 // Ensure that the entirety of the state snapshot is journalled to disk. 1149 var snapBase common.Hash 1150 if bc.snaps != nil { 1151 var err error 1152 if snapBase, err = bc.snaps.Journal(bc.CurrentBlock().Root()); err != nil { 1153 log.Error("Failed to journal state snapshot", "err", err) 1154 } 1155 } 1156 // Ensure the state of a recent block is also stored to disk before exiting. 1157 // We're writing three different states to catch different restart scenarios: 1158 // - HEAD: So we don't need to reprocess any blocks in the general case 1159 // - HEAD-1: So we don't do large reorgs if our HEAD becomes an uncle 1160 // - HEAD-127: So we have a hard limit on the number of blocks reexecuted 1161 if !bc.cacheConfig.TrieDirtyDisabled { 1162 triedb := bc.stateCache.TrieDB() 1163 1164 for _, offset := range []uint64{0, 1, TriesInMemory - 1} { 1165 if number := bc.CurrentBlock().NumberU64(); number > offset { 1166 recent := bc.GetBlockByNumber(number - offset) 1167 1168 log.Info("Writing cached state to disk", "block", recent.Number(), "hash", recent.Hash(), "root", recent.Root()) 1169 if err := triedb.Commit(recent.Root(), true, nil); err != nil { 1170 log.Error("Failed to commit recent state trie", "err", err) 1171 } 1172 } 1173 } 1174 if snapBase != (common.Hash{}) { 1175 log.Info("Writing snapshot state to disk", "root", snapBase) 1176 if err := triedb.Commit(snapBase, true, nil); err != nil { 1177 log.Error("Failed to commit recent state trie", "err", err) 1178 } 1179 } 1180 for !bc.triegc.Empty() { 1181 triedb.Dereference(bc.triegc.PopItem().(common.Hash)) 1182 } 1183 if size, _ := triedb.Size(); size != 0 { 1184 log.Error("Dangling trie nodes after full cleanup") 1185 } 1186 } 1187 // Ensure all live cached entries be saved into disk, so that we can skip 1188 // cache warmup when node restarts. 1189 if bc.cacheConfig.TrieCleanJournal != "" { 1190 triedb := bc.stateCache.TrieDB() 1191 triedb.SaveCache(bc.cacheConfig.TrieCleanJournal) 1192 } 1193 log.Info("Blockchain stopped") 1194 } 1195 1196 // StopInsert interrupts all insertion methods, causing them to return 1197 // errInsertionInterrupted as soon as possible. Insertion is permanently disabled after 1198 // calling this method. 1199 func (bc *BlockChain) StopInsert() { 1200 atomic.StoreInt32(&bc.procInterrupt, 1) 1201 } 1202 1203 // insertStopped returns true after StopInsert has been called. 1204 func (bc *BlockChain) insertStopped() bool { 1205 return atomic.LoadInt32(&bc.procInterrupt) == 1 1206 } 1207 1208 func (bc *BlockChain) procFutureBlocks() { 1209 blocks := make([]*types.Block, 0, bc.futureBlocks.Len()) 1210 for _, hash := range bc.futureBlocks.Keys() { 1211 if block, exist := bc.futureBlocks.Peek(hash); exist { 1212 blocks = append(blocks, block.(*types.Block)) 1213 } 1214 } 1215 if len(blocks) > 0 { 1216 sort.Slice(blocks, func(i, j int) bool { 1217 return blocks[i].NumberU64() < blocks[j].NumberU64() 1218 }) 1219 // Insert one by one as chain insertion needs contiguous ancestry between blocks 1220 for i := range blocks { 1221 bc.InsertChain(blocks[i : i+1]) 1222 } 1223 } 1224 } 1225 1226 // WriteStatus status of write 1227 type WriteStatus byte 1228 1229 const ( 1230 NonStatTy WriteStatus = iota 1231 CanonStatTy 1232 SideStatTy 1233 ) 1234 1235 // truncateAncient rewinds the blockchain to the specified header and deletes all 1236 // data in the ancient store that exceeds the specified header. 1237 func (bc *BlockChain) truncateAncient(head uint64) error { 1238 frozen, err := bc.db.Ancients() 1239 if err != nil { 1240 return err 1241 } 1242 // Short circuit if there is no data to truncate in ancient store. 1243 if frozen <= head+1 { 1244 return nil 1245 } 1246 // Truncate all the data in the freezer beyond the specified head 1247 if err := bc.db.TruncateAncients(head + 1); err != nil { 1248 return err 1249 } 1250 // Clear out any stale content from the caches 1251 bc.hc.headerCache.Purge() 1252 bc.hc.tdCache.Purge() 1253 bc.hc.numberCache.Purge() 1254 1255 // Clear out any stale content from the caches 1256 bc.bodyCache.Purge() 1257 bc.bodyRLPCache.Purge() 1258 bc.receiptsCache.Purge() 1259 bc.blockCache.Purge() 1260 bc.txLookupCache.Purge() 1261 bc.futureBlocks.Purge() 1262 1263 log.Info("Rewind ancient data", "number", head) 1264 return nil 1265 } 1266 1267 // numberHash is just a container for a number and a hash, to represent a block 1268 type numberHash struct { 1269 number uint64 1270 hash common.Hash 1271 } 1272 1273 // InsertReceiptChain attempts to complete an already existing header chain with 1274 // transaction and receipt data. 1275 func (bc *BlockChain) InsertReceiptChain(blockChain types.Blocks, receiptChain []types.Receipts, ancientLimit uint64) (int, error) { 1276 // We don't require the chainMu here since we want to maximize the 1277 // concurrency of header insertion and receipt insertion. 1278 bc.wg.Add(1) 1279 defer bc.wg.Done() 1280 1281 var ( 1282 ancientBlocks, liveBlocks types.Blocks 1283 ancientReceipts, liveReceipts []types.Receipts 1284 ) 1285 // Do a sanity check that the provided chain is actually ordered and linked 1286 for i := 0; i < len(blockChain); i++ { 1287 if i != 0 { 1288 if blockChain[i].NumberU64() != blockChain[i-1].NumberU64()+1 || blockChain[i].ParentHash() != blockChain[i-1].Hash() { 1289 log.Error("Non contiguous receipt insert", "number", blockChain[i].Number(), "hash", blockChain[i].Hash(), "parent", blockChain[i].ParentHash(), 1290 "prevnumber", blockChain[i-1].Number(), "prevhash", blockChain[i-1].Hash()) 1291 return 0, fmt.Errorf("non contiguous insert: item %d is #%d [%x..], item %d is #%d [%x..] (parent [%x..])", i-1, blockChain[i-1].NumberU64(), 1292 blockChain[i-1].Hash().Bytes()[:4], i, blockChain[i].NumberU64(), blockChain[i].Hash().Bytes()[:4], blockChain[i].ParentHash().Bytes()[:4]) 1293 } 1294 } 1295 if blockChain[i].NumberU64() <= ancientLimit { 1296 ancientBlocks, ancientReceipts = append(ancientBlocks, blockChain[i]), append(ancientReceipts, receiptChain[i]) 1297 } else { 1298 liveBlocks, liveReceipts = append(liveBlocks, blockChain[i]), append(liveReceipts, receiptChain[i]) 1299 } 1300 } 1301 1302 var ( 1303 stats = struct{ processed, ignored int32 }{} 1304 start = time.Now() 1305 size = 0 1306 ) 1307 // updateHead updates the head fast sync block if the inserted blocks are better 1308 // and returns an indicator whether the inserted blocks are canonical. 1309 updateHead := func(head *types.Block) bool { 1310 bc.chainmu.Lock() 1311 1312 // Rewind may have occurred, skip in that case. 1313 if bc.CurrentHeader().Number.Cmp(head.Number()) >= 0 { 1314 currentFastBlock, td := bc.CurrentFastBlock(), bc.GetTd(head.Hash(), head.NumberU64()) 1315 if bc.GetTd(currentFastBlock.Hash(), currentFastBlock.NumberU64()).Cmp(td) < 0 { 1316 rawdb.WriteHeadFastBlockHash(bc.db, head.Hash()) 1317 bc.currentFastBlock.Store(head) 1318 headFastBlockGauge.Update(int64(head.NumberU64())) 1319 bc.chainmu.Unlock() 1320 return true 1321 } 1322 } 1323 bc.chainmu.Unlock() 1324 return false 1325 } 1326 // writeAncient writes blockchain and corresponding receipt chain into ancient store. 1327 // 1328 // this function only accepts canonical chain data. All side chain will be reverted 1329 // eventually. 1330 writeAncient := func(blockChain types.Blocks, receiptChain []types.Receipts) (int, error) { 1331 var ( 1332 previous = bc.CurrentFastBlock() 1333 batch = bc.db.NewBatch() 1334 ) 1335 // If any error occurs before updating the head or we are inserting a side chain, 1336 // all the data written this time wll be rolled back. 1337 defer func() { 1338 if previous != nil { 1339 if err := bc.truncateAncient(previous.NumberU64()); err != nil { 1340 log.Crit("Truncate ancient store failed", "err", err) 1341 } 1342 } 1343 }() 1344 var deleted []*numberHash 1345 for i, block := range blockChain { 1346 // Short circuit insertion if shutting down or processing failed 1347 if bc.insertStopped() { 1348 return 0, errInsertionInterrupted 1349 } 1350 // Short circuit insertion if it is required(used in testing only) 1351 if bc.terminateInsert != nil && bc.terminateInsert(block.Hash(), block.NumberU64()) { 1352 return i, errors.New("insertion is terminated for testing purpose") 1353 } 1354 // Short circuit if the owner header is unknown 1355 if !bc.HasHeader(block.Hash(), block.NumberU64()) { 1356 return i, fmt.Errorf("containing header #%d [%x..] unknown", block.Number(), block.Hash().Bytes()[:4]) 1357 } 1358 if block.NumberU64() == 1 { 1359 // Make sure to write the genesis into the freezer 1360 if frozen, _ := bc.db.Ancients(); frozen == 0 { 1361 h := rawdb.ReadCanonicalHash(bc.db, 0) 1362 b := rawdb.ReadBlock(bc.db, h, 0) 1363 size += rawdb.WriteAncientBlock(bc.db, b, rawdb.ReadReceipts(bc.db, h, 0, bc.chainConfig), rawdb.ReadTd(bc.db, h, 0)) 1364 log.Info("Wrote genesis to ancients") 1365 } 1366 } 1367 // Flush data into ancient database. 1368 size += rawdb.WriteAncientBlock(bc.db, block, receiptChain[i], bc.GetTd(block.Hash(), block.NumberU64())) 1369 1370 // Write tx indices if any condition is satisfied: 1371 // * If user requires to reserve all tx indices(txlookuplimit=0) 1372 // * If all ancient tx indices are required to be reserved(txlookuplimit is even higher than ancientlimit) 1373 // * If block number is large enough to be regarded as a recent block 1374 // It means blocks below the ancientLimit-txlookupLimit won't be indexed. 1375 // 1376 // But if the `TxIndexTail` is not nil, e.g. Geth is initialized with 1377 // an external ancient database, during the setup, blockchain will start 1378 // a background routine to re-indexed all indices in [ancients - txlookupLimit, ancients) 1379 // range. In this case, all tx indices of newly imported blocks should be 1380 // generated. 1381 if bc.txLookupLimit == 0 || ancientLimit <= bc.txLookupLimit || block.NumberU64() >= ancientLimit-bc.txLookupLimit { 1382 rawdb.WriteTxLookupEntriesByBlock(batch, block) 1383 } else if rawdb.ReadTxIndexTail(bc.db) != nil { 1384 rawdb.WriteTxLookupEntriesByBlock(batch, block) 1385 } 1386 stats.processed++ 1387 } 1388 // Flush all tx-lookup index data. 1389 size += batch.ValueSize() 1390 if err := batch.Write(); err != nil { 1391 return 0, err 1392 } 1393 batch.Reset() 1394 1395 // Sync the ancient store explicitly to ensure all data has been flushed to disk. 1396 if err := bc.db.Sync(); err != nil { 1397 return 0, err 1398 } 1399 if !updateHead(blockChain[len(blockChain)-1]) { 1400 return 0, errors.New("side blocks can't be accepted as the ancient chain data") 1401 } 1402 previous = nil // disable rollback explicitly 1403 1404 // Wipe out canonical block data. 1405 for _, nh := range deleted { 1406 rawdb.DeleteBlockWithoutNumber(batch, nh.hash, nh.number) 1407 rawdb.DeleteCanonicalHash(batch, nh.number) 1408 } 1409 for _, block := range blockChain { 1410 // Always keep genesis block in active database. 1411 if block.NumberU64() != 0 { 1412 rawdb.DeleteBlockWithoutNumber(batch, block.Hash(), block.NumberU64()) 1413 rawdb.DeleteCanonicalHash(batch, block.NumberU64()) 1414 } 1415 } 1416 if err := batch.Write(); err != nil { 1417 return 0, err 1418 } 1419 batch.Reset() 1420 1421 // Wipe out side chain too. 1422 for _, nh := range deleted { 1423 for _, hash := range rawdb.ReadAllHashes(bc.db, nh.number) { 1424 rawdb.DeleteBlock(batch, hash, nh.number) 1425 } 1426 } 1427 for _, block := range blockChain { 1428 // Always keep genesis block in active database. 1429 if block.NumberU64() != 0 { 1430 for _, hash := range rawdb.ReadAllHashes(bc.db, block.NumberU64()) { 1431 rawdb.DeleteBlock(batch, hash, block.NumberU64()) 1432 } 1433 } 1434 } 1435 if err := batch.Write(); err != nil { 1436 return 0, err 1437 } 1438 return 0, nil 1439 } 1440 // writeLive writes blockchain and corresponding receipt chain into active store. 1441 writeLive := func(blockChain types.Blocks, receiptChain []types.Receipts) (int, error) { 1442 skipPresenceCheck := false 1443 batch := bc.db.NewBatch() 1444 for i, block := range blockChain { 1445 // Short circuit insertion if shutting down or processing failed 1446 if bc.insertStopped() { 1447 return 0, errInsertionInterrupted 1448 } 1449 // Short circuit if the owner header is unknown 1450 if !bc.HasHeader(block.Hash(), block.NumberU64()) { 1451 return i, fmt.Errorf("containing header #%d [%x..] unknown", block.Number(), block.Hash().Bytes()[:4]) 1452 } 1453 if !skipPresenceCheck { 1454 // Ignore if the entire data is already known 1455 if bc.HasBlock(block.Hash(), block.NumberU64()) { 1456 stats.ignored++ 1457 continue 1458 } else { 1459 // If block N is not present, neither are the later blocks. 1460 // This should be true, but if we are mistaken, the shortcut 1461 // here will only cause overwriting of some existing data 1462 skipPresenceCheck = true 1463 } 1464 } 1465 // Write all the data out into the database 1466 rawdb.WriteBody(batch, block.Hash(), block.NumberU64(), block.Body()) 1467 rawdb.WriteReceipts(batch, block.Hash(), block.NumberU64(), receiptChain[i]) 1468 rawdb.WriteTxLookupEntriesByBlock(batch, block) // Always write tx indices for live blocks, we assume they are needed 1469 1470 // Write everything belongs to the blocks into the database. So that 1471 // we can ensure all components of body is completed(body, receipts, 1472 // tx indexes) 1473 if batch.ValueSize() >= ethdb.IdealBatchSize { 1474 if err := batch.Write(); err != nil { 1475 return 0, err 1476 } 1477 size += batch.ValueSize() 1478 batch.Reset() 1479 } 1480 stats.processed++ 1481 } 1482 // Write everything belongs to the blocks into the database. So that 1483 // we can ensure all components of body is completed(body, receipts, 1484 // tx indexes) 1485 if batch.ValueSize() > 0 { 1486 size += batch.ValueSize() 1487 if err := batch.Write(); err != nil { 1488 return 0, err 1489 } 1490 } 1491 updateHead(blockChain[len(blockChain)-1]) 1492 return 0, nil 1493 } 1494 // Write downloaded chain data and corresponding receipt chain data 1495 if len(ancientBlocks) > 0 { 1496 if n, err := writeAncient(ancientBlocks, ancientReceipts); err != nil { 1497 if err == errInsertionInterrupted { 1498 return 0, nil 1499 } 1500 return n, err 1501 } 1502 } 1503 // Write the tx index tail (block number from where we index) before write any live blocks 1504 if len(liveBlocks) > 0 && liveBlocks[0].NumberU64() == ancientLimit+1 { 1505 // The tx index tail can only be one of the following two options: 1506 // * 0: all ancient blocks have been indexed 1507 // * ancient-limit: the indices of blocks before ancient-limit are ignored 1508 if tail := rawdb.ReadTxIndexTail(bc.db); tail == nil { 1509 if bc.txLookupLimit == 0 || ancientLimit <= bc.txLookupLimit { 1510 rawdb.WriteTxIndexTail(bc.db, 0) 1511 } else { 1512 rawdb.WriteTxIndexTail(bc.db, ancientLimit-bc.txLookupLimit) 1513 } 1514 } 1515 } 1516 if len(liveBlocks) > 0 { 1517 if n, err := writeLive(liveBlocks, liveReceipts); err != nil { 1518 if err == errInsertionInterrupted { 1519 return 0, nil 1520 } 1521 return n, err 1522 } 1523 } 1524 1525 head := blockChain[len(blockChain)-1] 1526 context := []interface{}{ 1527 "count", stats.processed, "elapsed", common.PrettyDuration(time.Since(start)), 1528 "number", head.Number(), "hash", head.Hash(), "age", common.PrettyAge(time.Unix(int64(head.Time()), 0)), 1529 "size", common.StorageSize(size), 1530 } 1531 if stats.ignored > 0 { 1532 context = append(context, []interface{}{"ignored", stats.ignored}...) 1533 } 1534 log.Info("Imported new block receipts", context...) 1535 1536 return 0, nil 1537 } 1538 1539 // SetTxLookupLimit is responsible for updating the txlookup limit to the 1540 // original one stored in db if the new mismatches with the old one. 1541 func (bc *BlockChain) SetTxLookupLimit(limit uint64) { 1542 bc.txLookupLimit = limit 1543 } 1544 1545 // TxLookupLimit retrieves the txlookup limit used by blockchain to prune 1546 // stale transaction indices. 1547 func (bc *BlockChain) TxLookupLimit() uint64 { 1548 return bc.txLookupLimit 1549 } 1550 1551 var lastWrite uint64 1552 1553 // writeBlockWithoutState writes only the block and its metadata to the database, 1554 // but does not write any state. This is used to construct competing side forks 1555 // up to the point where they exceed the canonical total difficulty. 1556 func (bc *BlockChain) writeBlockWithoutState(block *types.Block, td *big.Int) (err error) { 1557 bc.wg.Add(1) 1558 defer bc.wg.Done() 1559 1560 batch := bc.db.NewBatch() 1561 rawdb.WriteTd(batch, block.Hash(), block.NumberU64(), td) 1562 rawdb.WriteBlock(batch, block) 1563 if err := batch.Write(); err != nil { 1564 log.Crit("Failed to write block into disk", "err", err) 1565 } 1566 return nil 1567 } 1568 1569 // writeKnownBlock updates the head block flag with a known block 1570 // and introduces chain reorg if necessary. 1571 func (bc *BlockChain) writeKnownBlock(block *types.Block) error { 1572 bc.wg.Add(1) 1573 defer bc.wg.Done() 1574 1575 current := bc.CurrentBlock() 1576 if block.ParentHash() != current.Hash() { 1577 if err := bc.reorg(current, block); err != nil { 1578 return err 1579 } 1580 } 1581 bc.writeHeadBlock(block) 1582 return nil 1583 } 1584 1585 // WriteBlockWithState writes the block and all associated state to the database. 1586 func (bc *BlockChain) WriteBlockWithState(block *types.Block, receipts []*types.Receipt, logs []*types.Log, state *state.StateDB, psManager mps.PrivateStateRepository, emitHeadEvent bool) (status WriteStatus, err error) { 1587 bc.chainmu.Lock() 1588 defer bc.chainmu.Unlock() 1589 1590 return bc.writeBlockWithState(block, receipts, logs, state, psManager, emitHeadEvent) 1591 } 1592 1593 // QUORUM 1594 // checks if the consensus engine is Rfat 1595 func (bc *BlockChain) isRaft() bool { 1596 return bc.chainConfig.IsQuorum && bc.chainConfig.Istanbul == nil && bc.chainConfig.IBFT == nil && bc.chainConfig.QBFT == nil && bc.chainConfig.Clique == nil 1597 } 1598 1599 // function specifically added for Raft consensus. This is called from mintNewBlock 1600 // to commit public and private state using bc.chainmu lock 1601 // added to avoid concurrent map errors in high stress conditions 1602 func (bc *BlockChain) CommitBlockWithState(deleteEmptyObjects bool, state, privateState *state.StateDB) error { 1603 // check if consensus is not Raft 1604 if !bc.isRaft() { 1605 return errors.New("error function can be called only for Raft consensus") 1606 } 1607 bc.chainmu.Lock() 1608 defer bc.chainmu.Unlock() 1609 if _, err := state.Commit(deleteEmptyObjects); err != nil { 1610 return fmt.Errorf("error committing public state: %v", err) 1611 } 1612 if _, err := privateState.Commit(deleteEmptyObjects); err != nil { 1613 return fmt.Errorf("error committing private state: %v", err) 1614 } 1615 return nil 1616 } 1617 1618 // END QUORUM 1619 1620 // writeBlockWithState writes the block and all associated state to the database, 1621 // but is expects the chain mutex to be held. 1622 func (bc *BlockChain) writeBlockWithState(block *types.Block, receipts []*types.Receipt, logs []*types.Log, state *state.StateDB, psManager mps.PrivateStateRepository, emitHeadEvent bool) (status WriteStatus, err error) { 1623 bc.wg.Add(1) 1624 defer bc.wg.Done() 1625 1626 // Calculate the total difficulty of the block 1627 ptd := bc.GetTd(block.ParentHash(), block.NumberU64()-1) 1628 if ptd == nil { 1629 return NonStatTy, consensus.ErrUnknownAncestor 1630 } 1631 1632 currentBlock := bc.CurrentBlock() 1633 localTd := bc.GetTd(currentBlock.Hash(), currentBlock.NumberU64()) 1634 externTd := new(big.Int).Add(block.Difficulty(), ptd) 1635 1636 // Irrelevant of the canonical status, write the block itself to the database. 1637 // 1638 // Note all the components of block(td, hash->number map, header, body, receipts) 1639 // should be written atomically. BlockBatch is used for containing all components. 1640 blockBatch := bc.db.NewBatch() 1641 rawdb.WriteTd(blockBatch, block.Hash(), block.NumberU64(), externTd) 1642 rawdb.WriteBlock(blockBatch, block) 1643 rawdb.WriteReceipts(blockBatch, block.Hash(), block.NumberU64(), receipts) 1644 rawdb.WritePreimages(blockBatch, state.Preimages()) 1645 if err := blockBatch.Write(); err != nil { 1646 log.Crit("Failed to write block into disk", "err", err) 1647 } 1648 // Commit all cached state changes into underlying memory database. 1649 root, err := state.Commit(bc.chainConfig.IsEIP158(block.Number())) 1650 if err != nil { 1651 return NonStatTy, err 1652 } 1653 1654 // quorum - private state commit must come after public state commit. If the private state is being cached then the 1655 // private state root will reference the public state root, hence the need for public state trie to have already 1656 // been committed. 1657 1658 // Make sure no inconsistent state is leaked during insertion 1659 // Quorum 1660 // Write private state changes to database 1661 err = psManager.CommitAndWrite(bc.chainConfig.IsEIP158(block.Number()), block) 1662 if err != nil { 1663 return NonStatTy, err 1664 } 1665 if bc.privateStateRootHashValidator != nil { 1666 err = bc.privateStateRootHashValidator.ValidatePrivateStateRoot(block.Hash(), block.Root()) 1667 if err != nil { 1668 return NonStatTy, err 1669 } 1670 } 1671 // /Quorum 1672 1673 triedb := bc.stateCache.TrieDB() 1674 1675 // If we're running an archive node, always flush 1676 if bc.cacheConfig.TrieDirtyDisabled { 1677 if err := triedb.Commit(root, false, nil); err != nil { 1678 return NonStatTy, err 1679 } 1680 } else { 1681 // Full but not archive node, do proper garbage collection 1682 triedb.Reference(root, common.Hash{}) // metadata reference to keep trie alive 1683 bc.triegc.Push(root, -int64(block.NumberU64())) 1684 1685 if current := block.NumberU64(); current > TriesInMemory { 1686 // If we exceeded our memory allowance, flush matured singleton nodes to disk 1687 var ( 1688 nodes, imgs = triedb.Size() 1689 limit = common.StorageSize(bc.cacheConfig.TrieDirtyLimit) * 1024 * 1024 1690 ) 1691 if nodes > limit || imgs > 4*1024*1024 { 1692 triedb.Cap(limit - ethdb.IdealBatchSize) 1693 } 1694 // Find the next state trie we need to commit 1695 chosen := current - TriesInMemory 1696 1697 // If we exceeded out time allowance, flush an entire trie to disk 1698 if bc.gcproc > bc.cacheConfig.TrieTimeLimit { 1699 // If the header is missing (canonical chain behind), we're reorging a low 1700 // diff sidechain. Suspend committing until this operation is completed. 1701 header := bc.GetHeaderByNumber(chosen) 1702 if header == nil { 1703 log.Warn("Reorg in progress, trie commit postponed", "number", chosen) 1704 } else { 1705 // If we're exceeding limits but haven't reached a large enough memory gap, 1706 // warn the user that the system is becoming unstable. 1707 if chosen < lastWrite+TriesInMemory && bc.gcproc >= 2*bc.cacheConfig.TrieTimeLimit { 1708 log.Info("State in memory for too long, committing", "time", bc.gcproc, "allowance", bc.cacheConfig.TrieTimeLimit, "optimum", float64(chosen-lastWrite)/TriesInMemory) 1709 } 1710 // Flush an entire trie and restart the counters 1711 triedb.Commit(header.Root, true, nil) 1712 lastWrite = chosen 1713 bc.gcproc = 0 1714 } 1715 } 1716 // Garbage collect anything below our required write retention 1717 for !bc.triegc.Empty() { 1718 root, number := bc.triegc.Pop() 1719 if uint64(-number) > chosen { 1720 bc.triegc.Push(root, number) 1721 break 1722 } 1723 triedb.Dereference(root.(common.Hash)) 1724 } 1725 } 1726 } 1727 // If the total difficulty is higher than our known, add it to the canonical chain 1728 // Second clause in the if statement reduces the vulnerability to selfish mining. 1729 // Please refer to http://www.cs.cornell.edu/~ie53/publications/btcProcFC.pdf 1730 reorg := externTd.Cmp(localTd) > 0 1731 currentBlock = bc.CurrentBlock() 1732 if !reorg && externTd.Cmp(localTd) == 0 { 1733 // Split same-difficulty blocks by number, then preferentially select 1734 // the block generated by the local miner as the canonical block. 1735 if block.NumberU64() < currentBlock.NumberU64() { 1736 reorg = true 1737 } else if block.NumberU64() == currentBlock.NumberU64() { 1738 var currentPreserve, blockPreserve bool 1739 if bc.shouldPreserve != nil { 1740 currentPreserve, blockPreserve = bc.shouldPreserve(currentBlock), bc.shouldPreserve(block) 1741 } 1742 reorg = !currentPreserve && (blockPreserve || mrand.Float64() < 0.5) 1743 } 1744 } 1745 if reorg { 1746 // Reorganise the chain if the parent is not the head block 1747 if block.ParentHash() != currentBlock.Hash() { 1748 if err := bc.reorg(currentBlock, block); err != nil { 1749 return NonStatTy, err 1750 } 1751 } 1752 status = CanonStatTy 1753 } else { 1754 status = SideStatTy 1755 } 1756 // Set new head. 1757 if status == CanonStatTy { 1758 bc.writeHeadBlock(block) 1759 } 1760 bc.futureBlocks.Remove(block.Hash()) 1761 1762 if status == CanonStatTy { 1763 bc.chainFeed.Send(ChainEvent{Block: block, Hash: block.Hash(), Logs: logs}) 1764 if len(logs) > 0 { 1765 bc.logsFeed.Send(logs) 1766 } 1767 // In theory we should fire a ChainHeadEvent when we inject 1768 // a canonical block, but sometimes we can insert a batch of 1769 // canonicial blocks. Avoid firing too much ChainHeadEvents, 1770 // we will fire an accumulated ChainHeadEvent and disable fire 1771 // event here. 1772 if emitHeadEvent { 1773 bc.chainHeadFeed.Send(ChainHeadEvent{Block: block}) 1774 } 1775 } else { 1776 bc.chainSideFeed.Send(ChainSideEvent{Block: block}) 1777 } 1778 return status, nil 1779 } 1780 1781 // addFutureBlock checks if the block is within the max allowed window to get 1782 // accepted for future processing, and returns an error if the block is too far 1783 // ahead and was not added. 1784 func (bc *BlockChain) addFutureBlock(block *types.Block) error { 1785 max := uint64(time.Now().Unix() + maxTimeFutureBlocks) 1786 if block.Time() > max { 1787 return fmt.Errorf("future block timestamp %v > allowed %v", block.Time(), max) 1788 } 1789 bc.futureBlocks.Add(block.Hash(), block) 1790 return nil 1791 } 1792 1793 // InsertChain attempts to insert the given batch of blocks in to the canonical 1794 // chain or, otherwise, create a fork. If an error is returned it will return 1795 // the index number of the failing block as well an error describing what went 1796 // wrong. 1797 // 1798 // After insertion is done, all accumulated events will be fired. 1799 func (bc *BlockChain) InsertChain(chain types.Blocks) (int, error) { 1800 // Sanity check that we have something meaningful to import 1801 if len(chain) == 0 { 1802 return 0, nil 1803 } 1804 1805 bc.blockProcFeed.Send(true) 1806 defer bc.blockProcFeed.Send(false) 1807 1808 // Remove already known canon-blocks 1809 var ( 1810 block, prev *types.Block 1811 ) 1812 // Do a sanity check that the provided chain is actually ordered and linked 1813 for i := 1; i < len(chain); i++ { 1814 block = chain[i] 1815 prev = chain[i-1] 1816 if block.NumberU64() != prev.NumberU64()+1 || block.ParentHash() != prev.Hash() { 1817 // Chain broke ancestry, log a message (programming error) and skip insertion 1818 log.Error("Non contiguous block insert", "number", block.Number(), "hash", block.Hash(), 1819 "parent", block.ParentHash(), "prevnumber", prev.Number(), "prevhash", prev.Hash()) 1820 1821 return 0, fmt.Errorf("non contiguous insert: item %d is #%d [%x..], item %d is #%d [%x..] (parent [%x..])", i-1, prev.NumberU64(), 1822 prev.Hash().Bytes()[:4], i, block.NumberU64(), block.Hash().Bytes()[:4], block.ParentHash().Bytes()[:4]) 1823 } 1824 } 1825 // Pre-checks passed, start the full block imports 1826 bc.wg.Add(1) 1827 bc.chainmu.Lock() 1828 n, err := bc.insertChain(chain, true) 1829 bc.chainmu.Unlock() 1830 bc.wg.Done() 1831 1832 return n, err 1833 } 1834 1835 // InsertChainWithoutSealVerification works exactly the same 1836 // except for seal verification, seal verification is omitted 1837 func (bc *BlockChain) InsertChainWithoutSealVerification(block *types.Block) (int, error) { 1838 bc.blockProcFeed.Send(true) 1839 defer bc.blockProcFeed.Send(false) 1840 1841 // Pre-checks passed, start the full block imports 1842 bc.wg.Add(1) 1843 bc.chainmu.Lock() 1844 n, err := bc.insertChain(types.Blocks([]*types.Block{block}), false) 1845 bc.chainmu.Unlock() 1846 bc.wg.Done() 1847 1848 return n, err 1849 } 1850 1851 // insertChain is the internal implementation of InsertChain, which assumes that 1852 // 1) chains are contiguous, and 2) The chain mutex is held. 1853 // 1854 // This method is split out so that import batches that require re-injecting 1855 // historical blocks can do so without releasing the lock, which could lead to 1856 // racey behaviour. If a sidechain import is in progress, and the historic state 1857 // is imported, but then new canon-head is added before the actual sidechain 1858 // completes, then the historic state could be pruned again 1859 func (bc *BlockChain) insertChain(chain types.Blocks, verifySeals bool) (int, error) { 1860 // If the chain is terminating, don't even bother starting up 1861 if atomic.LoadInt32(&bc.procInterrupt) == 1 { 1862 log.Debug("Premature abort during blocks processing") 1863 // QUORUM 1864 if bc.isRaft() { 1865 // Only returns an error for raft mode 1866 return 0, ErrAbortBlocksProcessing 1867 } 1868 return 0, nil 1869 } 1870 // Start a parallel signature recovery (signer will fluke on fork transition, minimal perf loss) 1871 senderCacher.recoverFromBlocks(types.MakeSigner(bc.chainConfig, chain[0].Number()), chain) 1872 1873 var ( 1874 stats = insertStats{startTime: mclock.Now()} 1875 lastCanon *types.Block 1876 ) 1877 // Fire a single chain head event if we've progressed the chain 1878 defer func() { 1879 if lastCanon != nil && bc.CurrentBlock().Hash() == lastCanon.Hash() { 1880 bc.chainHeadFeed.Send(ChainHeadEvent{lastCanon}) 1881 } 1882 }() 1883 // Start the parallel header verifier 1884 headers := make([]*types.Header, len(chain)) 1885 seals := make([]bool, len(chain)) 1886 1887 for i, block := range chain { 1888 headers[i] = block.Header() 1889 seals[i] = verifySeals 1890 } 1891 abort, results := bc.engine.VerifyHeaders(bc, headers, seals) 1892 defer close(abort) 1893 1894 // Peek the error for the first block to decide the directing import logic 1895 it := newInsertIterator(chain, results, bc.validator) 1896 1897 block, err := it.next() 1898 1899 // Left-trim all the known blocks 1900 if err == ErrKnownBlock { 1901 // First block (and state) is known 1902 // 1. We did a roll-back, and should now do a re-import 1903 // 2. The block is stored as a sidechain, and is lying about it's stateroot, and passes a stateroot 1904 // from the canonical chain, which has not been verified. 1905 // Skip all known blocks that are behind us 1906 var ( 1907 current = bc.CurrentBlock() 1908 localTd = bc.GetTd(current.Hash(), current.NumberU64()) 1909 externTd = bc.GetTd(block.ParentHash(), block.NumberU64()-1) // The first block can't be nil 1910 ) 1911 for block != nil && err == ErrKnownBlock { 1912 externTd = new(big.Int).Add(externTd, block.Difficulty()) 1913 if localTd.Cmp(externTd) < 0 { 1914 break 1915 } 1916 log.Debug("Ignoring already known block", "number", block.Number(), "hash", block.Hash()) 1917 stats.ignored++ 1918 1919 block, err = it.next() 1920 } 1921 // The remaining blocks are still known blocks, the only scenario here is: 1922 // During the fast sync, the pivot point is already submitted but rollback 1923 // happens. Then node resets the head full block to a lower height via `rollback` 1924 // and leaves a few known blocks in the database. 1925 // 1926 // When node runs a fast sync again, it can re-import a batch of known blocks via 1927 // `insertChain` while a part of them have higher total difficulty than current 1928 // head full block(new pivot point). 1929 for block != nil && err == ErrKnownBlock { 1930 log.Debug("Writing previously known block", "number", block.Number(), "hash", block.Hash()) 1931 if err := bc.writeKnownBlock(block); err != nil { 1932 return it.index, err 1933 } 1934 lastCanon = block 1935 1936 block, err = it.next() 1937 } 1938 // Falls through to the block import 1939 } 1940 switch { 1941 // First block is pruned, insert as sidechain and reorg only if TD grows enough 1942 case errors.Is(err, consensus.ErrPrunedAncestor): 1943 log.Debug("Pruned ancestor, inserting as sidechain", "number", block.Number(), "hash", block.Hash()) 1944 return bc.insertSideChain(block, it) 1945 1946 // First block is future, shove it (and all children) to the future queue (unknown ancestor) 1947 case errors.Is(err, consensus.ErrFutureBlock) || (errors.Is(err, consensus.ErrUnknownAncestor) && bc.futureBlocks.Contains(it.first().ParentHash())): 1948 for block != nil && (it.index == 0 || errors.Is(err, consensus.ErrUnknownAncestor)) { 1949 log.Debug("Future block, postponing import", "number", block.Number(), "hash", block.Hash()) 1950 if err := bc.addFutureBlock(block); err != nil { 1951 return it.index, err 1952 } 1953 block, err = it.next() 1954 } 1955 stats.queued += it.processed() 1956 stats.ignored += it.remaining() 1957 1958 // If there are any still remaining, mark as ignored 1959 return it.index, err 1960 1961 // Some other error occurred, abort 1962 case err != nil: 1963 bc.futureBlocks.Remove(block.Hash()) 1964 stats.ignored += len(it.chain) 1965 bc.reportBlock(block, nil, err) 1966 return it.index, err 1967 } 1968 // No validation errors for the first block (or chain prefix skipped) 1969 var activeState *state.StateDB 1970 defer func() { 1971 // The chain importer is starting and stopping trie prefetchers. If a bad 1972 // block or other error is hit however, an early return may not properly 1973 // terminate the background threads. This defer ensures that we clean up 1974 // and dangling prefetcher, without defering each and holding on live refs. 1975 if activeState != nil { 1976 activeState.StopPrefetcher() 1977 } 1978 }() 1979 1980 for ; block != nil && err == nil || err == ErrKnownBlock; block, err = it.next() { 1981 // If the chain is terminating, stop processing blocks 1982 if bc.insertStopped() { 1983 log.Debug("Abort during block processing") 1984 // QUORUM 1985 if bc.isRaft() { 1986 // Only returns an error for raft mode 1987 return it.index, ErrAbortBlocksProcessing 1988 } 1989 // END QUORUM 1990 break 1991 } 1992 // If the header is a banned one, straight out abort 1993 if BadHashes[block.Hash()] { 1994 bc.reportBlock(block, nil, ErrBlacklistedHash) 1995 return it.index, ErrBlacklistedHash 1996 } 1997 // If the block is known (in the middle of the chain), it's a special case for 1998 // Clique blocks where they can share state among each other, so importing an 1999 // older block might complete the state of the subsequent one. In this case, 2000 // just skip the block (we already validated it once fully (and crashed), since 2001 // its header and body was already in the database). 2002 if err == ErrKnownBlock { 2003 logger := log.Debug 2004 if bc.chainConfig.Clique == nil { 2005 logger = log.Warn 2006 } 2007 logger("Inserted known block", "number", block.Number(), "hash", block.Hash(), 2008 "uncles", len(block.Uncles()), "txs", len(block.Transactions()), "gas", block.GasUsed(), 2009 "root", block.Root()) 2010 2011 // Special case. Commit the empty receipt slice if we meet the known 2012 // block in the middle. It can only happen in the clique chain. Whenever 2013 // we insert blocks via `insertSideChain`, we only commit `td`, `header` 2014 // and `body` if it's non-existent. Since we don't have receipts without 2015 // reexecution, so nothing to commit. But if the sidechain will be adpoted 2016 // as the canonical chain eventually, it needs to be reexecuted for missing 2017 // state, but if it's this special case here(skip reexecution) we will lose 2018 // the empty receipt entry. 2019 if len(block.Transactions()) == 0 { 2020 rawdb.WriteReceipts(bc.db, block.Hash(), block.NumberU64(), nil) 2021 } else { 2022 log.Error("Please file an issue, skip known block execution without receipt", 2023 "hash", block.Hash(), "number", block.NumberU64()) 2024 } 2025 if err := bc.writeKnownBlock(block); err != nil { 2026 return it.index, err 2027 } 2028 stats.processed++ 2029 2030 // We can assume that logs are empty here, since the only way for consecutive 2031 // Clique blocks to have the same state is if there are no transactions. 2032 lastCanon = block 2033 continue 2034 } 2035 // Retrieve the parent block and it's state to execute on top 2036 start := time.Now() 2037 2038 parent := it.previous() 2039 if parent == nil { 2040 parent = bc.GetHeader(block.ParentHash(), block.NumberU64()-1) 2041 } 2042 statedb, err := state.New(parent.Root, bc.stateCache, bc.snaps) 2043 if err != nil { 2044 return it.index, err 2045 } 2046 // Quorum 2047 privateStateRepo, err := bc.privateStateManager.StateRepository(parent.Root) 2048 if err != nil { 2049 return it.index, err 2050 } 2051 // End Quorum 2052 2053 // Enable prefetching to pull in trie node paths while processing transactions 2054 statedb.StartPrefetcher("chain") 2055 activeState = statedb 2056 2057 // If we have a followup block, run that against the current state to pre-cache 2058 // transactions and probabilistically some of the account/storage trie nodes. 2059 var followupInterrupt uint32 2060 if !bc.cacheConfig.TrieCleanNoPrefetch { 2061 if followup, err := it.peek(); followup != nil && err == nil { 2062 throwaway, _ := state.New(parent.Root, bc.stateCache, bc.snaps) 2063 2064 // Quorum 2065 privateStateRepo, stateRepoErr := bc.privateStateManager.StateRepository(parent.Root) 2066 if stateRepoErr == nil && privateStateRepo != nil { 2067 throwawayPrivateStateRepo := privateStateRepo.Copy() 2068 2069 // Quorum: add privateStateThrowaway argument 2070 go func(start time.Time, followup *types.Block, throwaway *state.StateDB, privateStateThrowaway mps.PrivateStateRepository, interrupt *uint32) { 2071 bc.prefetcher.Prefetch(followup, throwaway, throwawayPrivateStateRepo, bc.vmConfig, &followupInterrupt) 2072 2073 blockPrefetchExecuteTimer.Update(time.Since(start)) 2074 if atomic.LoadUint32(interrupt) == 1 { 2075 blockPrefetchInterruptMeter.Mark(1) 2076 } 2077 }(time.Now(), followup, throwaway, throwawayPrivateStateRepo, &followupInterrupt) 2078 } else { 2079 log.Warn("Unable to load the private state repository for pre-fetching", "stateRepoErr", stateRepoErr) 2080 } 2081 // End Quorum 2082 } 2083 } 2084 // Process block using the parent state as reference point 2085 substart := time.Now() 2086 2087 receipts, privateReceipts, logs, usedGas, err := bc.processor.Process(block, statedb, privateStateRepo, bc.vmConfig) 2088 if err != nil { 2089 bc.reportBlock(block, receipts, err) 2090 atomic.StoreUint32(&followupInterrupt, 1) 2091 return it.index, err 2092 } 2093 // Update the metrics touched during block processing 2094 accountReadTimer.Update(statedb.AccountReads) // Account reads are complete, we can mark them 2095 storageReadTimer.Update(statedb.StorageReads) // Storage reads are complete, we can mark them 2096 accountUpdateTimer.Update(statedb.AccountUpdates) // Account updates are complete, we can mark them 2097 storageUpdateTimer.Update(statedb.StorageUpdates) // Storage updates are complete, we can mark them 2098 snapshotAccountReadTimer.Update(statedb.SnapshotAccountReads) // Account reads are complete, we can mark them 2099 snapshotStorageReadTimer.Update(statedb.SnapshotStorageReads) // Storage reads are complete, we can mark them 2100 triehash := statedb.AccountHashes + statedb.StorageHashes // Save to not double count in validation 2101 trieproc := statedb.SnapshotAccountReads + statedb.AccountReads + statedb.AccountUpdates 2102 trieproc += statedb.SnapshotStorageReads + statedb.StorageReads + statedb.StorageUpdates 2103 2104 blockExecutionTimer.Update(time.Since(substart) - trieproc - triehash) 2105 2106 // Validate the state using the default validator 2107 substart = time.Now() 2108 if err := bc.validator.ValidateState(block, statedb, receipts, usedGas); err != nil { 2109 bc.reportBlock(block, receipts, err) 2110 atomic.StoreUint32(&followupInterrupt, 1) 2111 return it.index, err 2112 } 2113 2114 allReceipts := privateStateRepo.MergeReceipts(receipts, privateReceipts) 2115 proctime := time.Since(start) 2116 2117 // Update the metrics touched during block validation 2118 accountHashTimer.Update(statedb.AccountHashes) // Account hashes are complete, we can mark them 2119 storageHashTimer.Update(statedb.StorageHashes) // Storage hashes are complete, we can mark them 2120 2121 blockValidationTimer.Update(time.Since(substart) - (statedb.AccountHashes + statedb.StorageHashes - triehash)) 2122 2123 // Write the block to the chain and get the status. 2124 substart = time.Now() 2125 status, err := bc.writeBlockWithState(block, allReceipts, logs, statedb, privateStateRepo, false) 2126 atomic.StoreUint32(&followupInterrupt, 1) 2127 if err != nil { 2128 return it.index, err 2129 } 2130 2131 // Quorum 2132 if err := rawdb.WritePrivateBlockBloom(bc.db, block.NumberU64(), privateReceipts); err != nil { 2133 return it.index, err 2134 } 2135 // End Quorum 2136 2137 // Update the metrics touched during block commit 2138 accountCommitTimer.Update(statedb.AccountCommits) // Account commits are complete, we can mark them 2139 storageCommitTimer.Update(statedb.StorageCommits) // Storage commits are complete, we can mark them 2140 snapshotCommitTimer.Update(statedb.SnapshotCommits) // Snapshot commits are complete, we can mark them 2141 2142 blockWriteTimer.Update(time.Since(substart) - statedb.AccountCommits - statedb.StorageCommits - statedb.SnapshotCommits) 2143 blockInsertTimer.UpdateSince(start) 2144 2145 switch status { 2146 case CanonStatTy: 2147 log.Debug("Inserted new block", "number", block.Number(), "hash", block.Hash(), 2148 "uncles", len(block.Uncles()), "txs", len(block.Transactions()), "gas", block.GasUsed(), 2149 "elapsed", common.PrettyDuration(time.Since(start)), 2150 "root", block.Root()) 2151 2152 lastCanon = block 2153 2154 // Only count canonical blocks for GC processing time 2155 bc.gcproc += proctime 2156 2157 case SideStatTy: 2158 log.Debug("Inserted forked block", "number", block.Number(), "hash", block.Hash(), 2159 "diff", block.Difficulty(), "elapsed", common.PrettyDuration(time.Since(start)), 2160 "txs", len(block.Transactions()), "gas", block.GasUsed(), "uncles", len(block.Uncles()), 2161 "root", block.Root()) 2162 2163 default: 2164 // This in theory is impossible, but lets be nice to our future selves and leave 2165 // a log, instead of trying to track down blocks imports that don't emit logs. 2166 log.Warn("Inserted block with unknown status", "number", block.Number(), "hash", block.Hash(), 2167 "diff", block.Difficulty(), "elapsed", common.PrettyDuration(time.Since(start)), 2168 "txs", len(block.Transactions()), "gas", block.GasUsed(), "uncles", len(block.Uncles()), 2169 "root", block.Root()) 2170 } 2171 stats.processed++ 2172 stats.usedGas += usedGas 2173 2174 dirty, _ := bc.stateCache.TrieDB().Size() 2175 stats.report(chain, it.index, dirty) 2176 } 2177 // Any blocks remaining here? The only ones we care about are the future ones 2178 if block != nil && errors.Is(err, consensus.ErrFutureBlock) { 2179 if err := bc.addFutureBlock(block); err != nil { 2180 return it.index, err 2181 } 2182 block, err = it.next() 2183 2184 for ; block != nil && errors.Is(err, consensus.ErrUnknownAncestor); block, err = it.next() { 2185 if err := bc.addFutureBlock(block); err != nil { 2186 return it.index, err 2187 } 2188 stats.queued++ 2189 } 2190 } 2191 stats.ignored += it.remaining() 2192 2193 return it.index, err 2194 } 2195 2196 // insertSideChain is called when an import batch hits upon a pruned ancestor 2197 // error, which happens when a sidechain with a sufficiently old fork-block is 2198 // found. 2199 // 2200 // The method writes all (header-and-body-valid) blocks to disk, then tries to 2201 // switch over to the new chain if the TD exceeded the current chain. 2202 func (bc *BlockChain) insertSideChain(block *types.Block, it *insertIterator) (int, error) { 2203 var ( 2204 externTd *big.Int 2205 current = bc.CurrentBlock() 2206 ) 2207 // The first sidechain block error is already verified to be ErrPrunedAncestor. 2208 // Since we don't import them here, we expect ErrUnknownAncestor for the remaining 2209 // ones. Any other errors means that the block is invalid, and should not be written 2210 // to disk. 2211 err := consensus.ErrPrunedAncestor 2212 for ; block != nil && errors.Is(err, consensus.ErrPrunedAncestor); block, err = it.next() { 2213 // Check the canonical state root for that number 2214 if number := block.NumberU64(); current.NumberU64() >= number { 2215 canonical := bc.GetBlockByNumber(number) 2216 if canonical != nil && canonical.Hash() == block.Hash() { 2217 // Not a sidechain block, this is a re-import of a canon block which has it's state pruned 2218 2219 // Collect the TD of the block. Since we know it's a canon one, 2220 // we can get it directly, and not (like further below) use 2221 // the parent and then add the block on top 2222 externTd = bc.GetTd(block.Hash(), block.NumberU64()) 2223 continue 2224 } 2225 if canonical != nil && canonical.Root() == block.Root() { 2226 // This is most likely a shadow-state attack. When a fork is imported into the 2227 // database, and it eventually reaches a block height which is not pruned, we 2228 // just found that the state already exist! This means that the sidechain block 2229 // refers to a state which already exists in our canon chain. 2230 // 2231 // If left unchecked, we would now proceed importing the blocks, without actually 2232 // having verified the state of the previous blocks. 2233 log.Warn("Sidechain ghost-state attack detected", "number", block.NumberU64(), "sideroot", block.Root(), "canonroot", canonical.Root()) 2234 2235 // If someone legitimately side-mines blocks, they would still be imported as usual. However, 2236 // we cannot risk writing unverified blocks to disk when they obviously target the pruning 2237 // mechanism. 2238 return it.index, errors.New("sidechain ghost-state attack") 2239 } 2240 } 2241 if externTd == nil { 2242 externTd = bc.GetTd(block.ParentHash(), block.NumberU64()-1) 2243 } 2244 externTd = new(big.Int).Add(externTd, block.Difficulty()) 2245 2246 if !bc.HasBlock(block.Hash(), block.NumberU64()) { 2247 start := time.Now() 2248 if err := bc.writeBlockWithoutState(block, externTd); err != nil { 2249 return it.index, err 2250 } 2251 log.Debug("Injected sidechain block", "number", block.Number(), "hash", block.Hash(), 2252 "diff", block.Difficulty(), "elapsed", common.PrettyDuration(time.Since(start)), 2253 "txs", len(block.Transactions()), "gas", block.GasUsed(), "uncles", len(block.Uncles()), 2254 "root", block.Root()) 2255 } 2256 } 2257 // At this point, we've written all sidechain blocks to database. Loop ended 2258 // either on some other error or all were processed. If there was some other 2259 // error, we can ignore the rest of those blocks. 2260 // 2261 // If the externTd was larger than our local TD, we now need to reimport the previous 2262 // blocks to regenerate the required state 2263 localTd := bc.GetTd(current.Hash(), current.NumberU64()) 2264 if localTd.Cmp(externTd) > 0 { 2265 log.Info("Sidechain written to disk", "start", it.first().NumberU64(), "end", it.previous().Number, "sidetd", externTd, "localtd", localTd) 2266 return it.index, err 2267 } 2268 // Gather all the sidechain hashes (full blocks may be memory heavy) 2269 var ( 2270 hashes []common.Hash 2271 numbers []uint64 2272 ) 2273 parent := it.previous() 2274 for parent != nil && !bc.HasState(parent.Root) { 2275 hashes = append(hashes, parent.Hash()) 2276 numbers = append(numbers, parent.Number.Uint64()) 2277 2278 parent = bc.GetHeader(parent.ParentHash, parent.Number.Uint64()-1) 2279 } 2280 if parent == nil { 2281 return it.index, errors.New("missing parent") 2282 } 2283 // Import all the pruned blocks to make the state available 2284 var ( 2285 blocks []*types.Block 2286 memory common.StorageSize 2287 ) 2288 for i := len(hashes) - 1; i >= 0; i-- { 2289 // Append the next block to our batch 2290 block := bc.GetBlock(hashes[i], numbers[i]) 2291 2292 blocks = append(blocks, block) 2293 memory += block.Size() 2294 2295 // If memory use grew too large, import and continue. Sadly we need to discard 2296 // all raised events and logs from notifications since we're too heavy on the 2297 // memory here. 2298 if len(blocks) >= 2048 || memory > 64*1024*1024 { 2299 log.Info("Importing heavy sidechain segment", "blocks", len(blocks), "start", blocks[0].NumberU64(), "end", block.NumberU64()) 2300 if _, err := bc.insertChain(blocks, false); err != nil { 2301 return 0, err 2302 } 2303 blocks, memory = blocks[:0], 0 2304 2305 // If the chain is terminating, stop processing blocks 2306 if bc.insertStopped() { 2307 log.Debug("Abort during blocks processing") 2308 return 0, nil 2309 } 2310 } 2311 } 2312 if len(blocks) > 0 { 2313 log.Info("Importing sidechain segment", "start", blocks[0].NumberU64(), "end", blocks[len(blocks)-1].NumberU64()) 2314 return bc.insertChain(blocks, false) 2315 } 2316 return 0, nil 2317 } 2318 2319 // reorg takes two blocks, an old chain and a new chain and will reconstruct the 2320 // blocks and inserts them to be part of the new canonical chain and accumulates 2321 // potential missing transactions and post an event about them. 2322 func (bc *BlockChain) reorg(oldBlock, newBlock *types.Block) error { 2323 var ( 2324 newChain types.Blocks 2325 oldChain types.Blocks 2326 commonBlock *types.Block 2327 2328 deletedTxs types.Transactions 2329 addedTxs types.Transactions 2330 2331 deletedLogs [][]*types.Log 2332 rebirthLogs [][]*types.Log 2333 2334 // collectLogs collects the logs that were generated or removed during 2335 // the processing of the block that corresponds with the given hash. 2336 // These logs are later announced as deleted or reborn 2337 collectLogs = func(hash common.Hash, removed bool) { 2338 number := bc.hc.GetBlockNumber(hash) 2339 if number == nil { 2340 return 2341 } 2342 receipts := rawdb.ReadReceipts(bc.db, hash, *number, bc.chainConfig) 2343 2344 var logs []*types.Log 2345 for _, receipt := range receipts { 2346 for _, log := range receipt.Logs { 2347 l := *log 2348 if removed { 2349 l.Removed = true 2350 } 2351 logs = append(logs, &l) 2352 } 2353 } 2354 if len(logs) > 0 { 2355 if removed { 2356 deletedLogs = append(deletedLogs, logs) 2357 } else { 2358 rebirthLogs = append(rebirthLogs, logs) 2359 } 2360 } 2361 } 2362 // mergeLogs returns a merged log slice with specified sort order. 2363 mergeLogs = func(logs [][]*types.Log, reverse bool) []*types.Log { 2364 var ret []*types.Log 2365 if reverse { 2366 for i := len(logs) - 1; i >= 0; i-- { 2367 ret = append(ret, logs[i]...) 2368 } 2369 } else { 2370 for i := 0; i < len(logs); i++ { 2371 ret = append(ret, logs[i]...) 2372 } 2373 } 2374 return ret 2375 } 2376 ) 2377 // Reduce the longer chain to the same number as the shorter one 2378 if oldBlock.NumberU64() > newBlock.NumberU64() { 2379 // Old chain is longer, gather all transactions and logs as deleted ones 2380 for ; oldBlock != nil && oldBlock.NumberU64() != newBlock.NumberU64(); oldBlock = bc.GetBlock(oldBlock.ParentHash(), oldBlock.NumberU64()-1) { 2381 oldChain = append(oldChain, oldBlock) 2382 deletedTxs = append(deletedTxs, oldBlock.Transactions()...) 2383 collectLogs(oldBlock.Hash(), true) 2384 } 2385 } else { 2386 // New chain is longer, stash all blocks away for subsequent insertion 2387 for ; newBlock != nil && newBlock.NumberU64() != oldBlock.NumberU64(); newBlock = bc.GetBlock(newBlock.ParentHash(), newBlock.NumberU64()-1) { 2388 newChain = append(newChain, newBlock) 2389 } 2390 } 2391 if oldBlock == nil { 2392 return fmt.Errorf("invalid old chain") 2393 } 2394 if newBlock == nil { 2395 return fmt.Errorf("invalid new chain") 2396 } 2397 // Both sides of the reorg are at the same number, reduce both until the common 2398 // ancestor is found 2399 for { 2400 // If the common ancestor was found, bail out 2401 if oldBlock.Hash() == newBlock.Hash() { 2402 commonBlock = oldBlock 2403 break 2404 } 2405 // Remove an old block as well as stash away a new block 2406 oldChain = append(oldChain, oldBlock) 2407 deletedTxs = append(deletedTxs, oldBlock.Transactions()...) 2408 collectLogs(oldBlock.Hash(), true) 2409 2410 newChain = append(newChain, newBlock) 2411 2412 // Step back with both chains 2413 oldBlock = bc.GetBlock(oldBlock.ParentHash(), oldBlock.NumberU64()-1) 2414 if oldBlock == nil { 2415 return fmt.Errorf("invalid old chain") 2416 } 2417 newBlock = bc.GetBlock(newBlock.ParentHash(), newBlock.NumberU64()-1) 2418 if newBlock == nil { 2419 return fmt.Errorf("invalid new chain") 2420 } 2421 } 2422 // Ensure the user sees large reorgs 2423 if len(oldChain) > 0 && len(newChain) > 0 { 2424 logFn := log.Info 2425 msg := "Chain reorg detected" 2426 if len(oldChain) > 63 { 2427 msg = "Large chain reorg detected" 2428 logFn = log.Warn 2429 } 2430 logFn(msg, "number", commonBlock.Number(), "hash", commonBlock.Hash(), 2431 "drop", len(oldChain), "dropfrom", oldChain[0].Hash(), "add", len(newChain), "addfrom", newChain[0].Hash()) 2432 blockReorgAddMeter.Mark(int64(len(newChain))) 2433 blockReorgDropMeter.Mark(int64(len(oldChain))) 2434 blockReorgMeter.Mark(1) 2435 } else { 2436 log.Error("Impossible reorg, please file an issue", "oldnum", oldBlock.Number(), "oldhash", oldBlock.Hash(), "newnum", newBlock.Number(), "newhash", newBlock.Hash()) 2437 } 2438 // Insert the new chain(except the head block(reverse order)), 2439 // taking care of the proper incremental order. 2440 for i := len(newChain) - 1; i >= 1; i-- { 2441 // Insert the block in the canonical way, re-writing history 2442 bc.writeHeadBlock(newChain[i]) 2443 2444 // Collect reborn logs due to chain reorg 2445 collectLogs(newChain[i].Hash(), false) 2446 2447 // Collect the new added transactions. 2448 addedTxs = append(addedTxs, newChain[i].Transactions()...) 2449 } 2450 // Delete useless indexes right now which includes the non-canonical 2451 // transaction indexes, canonical chain indexes which above the head. 2452 indexesBatch := bc.db.NewBatch() 2453 for _, tx := range types.TxDifference(deletedTxs, addedTxs) { 2454 rawdb.DeleteTxLookupEntry(indexesBatch, tx.Hash()) 2455 } 2456 // Delete any canonical number assignments above the new head 2457 number := bc.CurrentBlock().NumberU64() 2458 for i := number + 1; ; i++ { 2459 hash := rawdb.ReadCanonicalHash(bc.db, i) 2460 if hash == (common.Hash{}) { 2461 break 2462 } 2463 rawdb.DeleteCanonicalHash(indexesBatch, i) 2464 } 2465 if err := indexesBatch.Write(); err != nil { 2466 log.Crit("Failed to delete useless indexes", "err", err) 2467 } 2468 // If any logs need to be fired, do it now. In theory we could avoid creating 2469 // this goroutine if there are no events to fire, but realistcally that only 2470 // ever happens if we're reorging empty blocks, which will only happen on idle 2471 // networks where performance is not an issue either way. 2472 if len(deletedLogs) > 0 { 2473 bc.rmLogsFeed.Send(RemovedLogsEvent{mergeLogs(deletedLogs, true)}) 2474 } 2475 if len(rebirthLogs) > 0 { 2476 bc.logsFeed.Send(mergeLogs(rebirthLogs, false)) 2477 } 2478 if len(oldChain) > 0 { 2479 for i := len(oldChain) - 1; i >= 0; i-- { 2480 bc.chainSideFeed.Send(ChainSideEvent{Block: oldChain[i]}) 2481 } 2482 } 2483 return nil 2484 } 2485 2486 func (bc *BlockChain) update() { 2487 futureTimer := time.NewTicker(5 * time.Second) 2488 defer futureTimer.Stop() 2489 for { 2490 select { 2491 case <-futureTimer.C: 2492 bc.procFutureBlocks() 2493 case <-bc.quit: 2494 return 2495 } 2496 } 2497 } 2498 2499 // maintainTxIndex is responsible for the construction and deletion of the 2500 // transaction index. 2501 // 2502 // User can use flag `txlookuplimit` to specify a "recentness" block, below 2503 // which ancient tx indices get deleted. If `txlookuplimit` is 0, it means 2504 // all tx indices will be reserved. 2505 // 2506 // The user can adjust the txlookuplimit value for each launch after fast 2507 // sync, Geth will automatically construct the missing indices and delete 2508 // the extra indices. 2509 func (bc *BlockChain) maintainTxIndex(ancients uint64) { 2510 defer bc.wg.Done() 2511 2512 // Before starting the actual maintenance, we need to handle a special case, 2513 // where user might init Geth with an external ancient database. If so, we 2514 // need to reindex all necessary transactions before starting to process any 2515 // pruning requests. 2516 if ancients > 0 { 2517 var from = uint64(0) 2518 if bc.txLookupLimit != 0 && ancients > bc.txLookupLimit { 2519 from = ancients - bc.txLookupLimit 2520 } 2521 rawdb.IndexTransactions(bc.db, from, ancients, bc.quit) 2522 } 2523 // indexBlocks reindexes or unindexes transactions depending on user configuration 2524 indexBlocks := func(tail *uint64, head uint64, done chan struct{}) { 2525 defer func() { done <- struct{}{} }() 2526 2527 // If the user just upgraded Geth to a new version which supports transaction 2528 // index pruning, write the new tail and remove anything older. 2529 if tail == nil { 2530 if bc.txLookupLimit == 0 || head < bc.txLookupLimit { 2531 // Nothing to delete, write the tail and return 2532 rawdb.WriteTxIndexTail(bc.db, 0) 2533 } else { 2534 // Prune all stale tx indices and record the tx index tail 2535 rawdb.UnindexTransactions(bc.db, 0, head-bc.txLookupLimit+1, bc.quit) 2536 } 2537 return 2538 } 2539 // If a previous indexing existed, make sure that we fill in any missing entries 2540 if bc.txLookupLimit == 0 || head < bc.txLookupLimit { 2541 if *tail > 0 { 2542 rawdb.IndexTransactions(bc.db, 0, *tail, bc.quit) 2543 } 2544 return 2545 } 2546 // Update the transaction index to the new chain state 2547 if head-bc.txLookupLimit+1 < *tail { 2548 // Reindex a part of missing indices and rewind index tail to HEAD-limit 2549 rawdb.IndexTransactions(bc.db, head-bc.txLookupLimit+1, *tail, bc.quit) 2550 } else { 2551 // Unindex a part of stale indices and forward index tail to HEAD-limit 2552 rawdb.UnindexTransactions(bc.db, *tail, head-bc.txLookupLimit+1, bc.quit) 2553 } 2554 } 2555 // Any reindexing done, start listening to chain events and moving the index window 2556 var ( 2557 done chan struct{} // Non-nil if background unindexing or reindexing routine is active. 2558 headCh = make(chan ChainHeadEvent, 1) // Buffered to avoid locking up the event feed 2559 ) 2560 sub := bc.SubscribeChainHeadEvent(headCh) 2561 if sub == nil { 2562 return 2563 } 2564 defer sub.Unsubscribe() 2565 2566 for { 2567 select { 2568 case head := <-headCh: 2569 if done == nil { 2570 done = make(chan struct{}) 2571 go indexBlocks(rawdb.ReadTxIndexTail(bc.db), head.Block.NumberU64(), done) 2572 } 2573 case <-done: 2574 done = nil 2575 case <-bc.quit: 2576 if done != nil { 2577 log.Info("Waiting background transaction indexer to exit") 2578 <-done 2579 } 2580 return 2581 } 2582 } 2583 } 2584 2585 // reportBlock logs a bad block error. 2586 func (bc *BlockChain) reportBlock(block *types.Block, receipts types.Receipts, err error) { 2587 rawdb.WriteBadBlock(bc.db, block) 2588 2589 var receiptString string 2590 for i, receipt := range receipts { 2591 receiptString += fmt.Sprintf("\t %d: cumulative: %v gas: %v contract: %v status: %v tx: %v logs: %v bloom: %x state: %x\n", 2592 i, receipt.CumulativeGasUsed, receipt.GasUsed, receipt.ContractAddress.Hex(), 2593 receipt.Status, receipt.TxHash.Hex(), receipt.Logs, receipt.Bloom, receipt.PostState) 2594 } 2595 log.Error(fmt.Sprintf(` 2596 ########## BAD BLOCK ######### 2597 Chain config: %v 2598 2599 Number: %v 2600 Hash: 0x%x 2601 %v 2602 2603 Error: %v 2604 ############################## 2605 `, bc.chainConfig, block.Number(), block.Hash(), receiptString, err)) 2606 } 2607 2608 // InsertHeaderChain attempts to insert the given header chain in to the local 2609 // chain, possibly creating a reorg. If an error is returned, it will return the 2610 // index number of the failing header as well an error describing what went wrong. 2611 // 2612 // The verify parameter can be used to fine tune whether nonce verification 2613 // should be done or not. The reason behind the optional check is because some 2614 // of the header retrieval mechanisms already need to verify nonces, as well as 2615 // because nonces can be verified sparsely, not needing to check each. 2616 func (bc *BlockChain) InsertHeaderChain(chain []*types.Header, checkFreq int) (int, error) { 2617 start := time.Now() 2618 if i, err := bc.hc.ValidateHeaderChain(chain, checkFreq); err != nil { 2619 return i, err 2620 } 2621 2622 // Make sure only one thread manipulates the chain at once 2623 bc.chainmu.Lock() 2624 defer bc.chainmu.Unlock() 2625 2626 bc.wg.Add(1) 2627 defer bc.wg.Done() 2628 _, err := bc.hc.InsertHeaderChain(chain, start) 2629 return 0, err 2630 } 2631 2632 // CurrentHeader retrieves the current head header of the canonical chain. The 2633 // header is retrieved from the HeaderChain's internal cache. 2634 func (bc *BlockChain) CurrentHeader() *types.Header { 2635 return bc.hc.CurrentHeader() 2636 } 2637 2638 // GetTd retrieves a block's total difficulty in the canonical chain from the 2639 // database by hash and number, caching it if found. 2640 func (bc *BlockChain) GetTd(hash common.Hash, number uint64) *big.Int { 2641 return bc.hc.GetTd(hash, number) 2642 } 2643 2644 // GetTdByHash retrieves a block's total difficulty in the canonical chain from the 2645 // database by hash, caching it if found. 2646 func (bc *BlockChain) GetTdByHash(hash common.Hash) *big.Int { 2647 return bc.hc.GetTdByHash(hash) 2648 } 2649 2650 // GetHeader retrieves a block header from the database by hash and number, 2651 // caching it if found. 2652 func (bc *BlockChain) GetHeader(hash common.Hash, number uint64) *types.Header { 2653 return bc.hc.GetHeader(hash, number) 2654 } 2655 2656 // GetHeaderByHash retrieves a block header from the database by hash, caching it if 2657 // found. 2658 func (bc *BlockChain) GetHeaderByHash(hash common.Hash) *types.Header { 2659 return bc.hc.GetHeaderByHash(hash) 2660 } 2661 2662 // HasHeader checks if a block header is present in the database or not, caching 2663 // it if present. 2664 func (bc *BlockChain) HasHeader(hash common.Hash, number uint64) bool { 2665 return bc.hc.HasHeader(hash, number) 2666 } 2667 2668 // GetCanonicalHash returns the canonical hash for a given block number 2669 func (bc *BlockChain) GetCanonicalHash(number uint64) common.Hash { 2670 return bc.hc.GetCanonicalHash(number) 2671 } 2672 2673 // GetBlockHashesFromHash retrieves a number of block hashes starting at a given 2674 // hash, fetching towards the genesis block. 2675 func (bc *BlockChain) GetBlockHashesFromHash(hash common.Hash, max uint64) []common.Hash { 2676 return bc.hc.GetBlockHashesFromHash(hash, max) 2677 } 2678 2679 // GetAncestor retrieves the Nth ancestor of a given block. It assumes that either the given block or 2680 // a close ancestor of it is canonical. maxNonCanonical points to a downwards counter limiting the 2681 // number of blocks to be individually checked before we reach the canonical chain. 2682 // 2683 // Note: ancestor == 0 returns the same block, 1 returns its parent and so on. 2684 func (bc *BlockChain) GetAncestor(hash common.Hash, number, ancestor uint64, maxNonCanonical *uint64) (common.Hash, uint64) { 2685 return bc.hc.GetAncestor(hash, number, ancestor, maxNonCanonical) 2686 } 2687 2688 // GetHeaderByNumber retrieves a block header from the database by number, 2689 // caching it (associated with its hash) if found. 2690 func (bc *BlockChain) GetHeaderByNumber(number uint64) *types.Header { 2691 return bc.hc.GetHeaderByNumber(number) 2692 } 2693 2694 // GetTransactionLookup retrieves the lookup associate with the given transaction 2695 // hash from the cache or database. 2696 func (bc *BlockChain) GetTransactionLookup(hash common.Hash) *rawdb.LegacyTxLookupEntry { 2697 // Short circuit if the txlookup already in the cache, retrieve otherwise 2698 if lookup, exist := bc.txLookupCache.Get(hash); exist { 2699 return lookup.(*rawdb.LegacyTxLookupEntry) 2700 } 2701 tx, blockHash, blockNumber, txIndex := rawdb.ReadTransaction(bc.db, hash) 2702 if tx == nil { 2703 return nil 2704 } 2705 lookup := &rawdb.LegacyTxLookupEntry{BlockHash: blockHash, BlockIndex: blockNumber, Index: txIndex} 2706 bc.txLookupCache.Add(hash, lookup) 2707 return lookup 2708 } 2709 2710 // Config retrieves the chain's fork configuration. 2711 func (bc *BlockChain) Config() *params.ChainConfig { return bc.chainConfig } 2712 2713 // QuorumConfig retrieves the Quorum chain's configuration 2714 func (bc *BlockChain) QuorumConfig() *QuorumChainConfig { return bc.quorumConfig } 2715 2716 // Engine retrieves the blockchain's consensus engine. 2717 func (bc *BlockChain) Engine() consensus.Engine { return bc.engine } 2718 2719 // SubscribeRemovedLogsEvent registers a subscription of RemovedLogsEvent. 2720 func (bc *BlockChain) SubscribeRemovedLogsEvent(ch chan<- RemovedLogsEvent) event.Subscription { 2721 return bc.scope.Track(bc.rmLogsFeed.Subscribe(ch)) 2722 } 2723 2724 // SubscribeChainEvent registers a subscription of ChainEvent. 2725 func (bc *BlockChain) SubscribeChainEvent(ch chan<- ChainEvent) event.Subscription { 2726 return bc.scope.Track(bc.chainFeed.Subscribe(ch)) 2727 } 2728 2729 // SubscribeChainHeadEvent registers a subscription of ChainHeadEvent. 2730 func (bc *BlockChain) SubscribeChainHeadEvent(ch chan<- ChainHeadEvent) event.Subscription { 2731 return bc.scope.Track(bc.chainHeadFeed.Subscribe(ch)) 2732 } 2733 2734 // SubscribeChainSideEvent registers a subscription of ChainSideEvent. 2735 func (bc *BlockChain) SubscribeChainSideEvent(ch chan<- ChainSideEvent) event.Subscription { 2736 return bc.scope.Track(bc.chainSideFeed.Subscribe(ch)) 2737 } 2738 2739 // SubscribeLogsEvent registers a subscription of []*types.Log. 2740 func (bc *BlockChain) SubscribeLogsEvent(ch chan<- []*types.Log) event.Subscription { 2741 return bc.scope.Track(bc.logsFeed.Subscribe(ch)) 2742 } 2743 2744 // SubscribeBlockProcessingEvent registers a subscription of bool where true means 2745 // block processing has started while false means it has stopped. 2746 func (bc *BlockChain) SubscribeBlockProcessingEvent(ch chan<- bool) event.Subscription { 2747 return bc.scope.Track(bc.blockProcFeed.Subscribe(ch)) 2748 } 2749 2750 // Quorum 2751 func (bc *BlockChain) SupportsMultitenancy(context.Context) bool { 2752 return bc.quorumConfig.MultiTenantEnabled() 2753 } 2754 2755 // PopulateSetPrivateState function pointer for updating private state 2756 // Quorum 2757 func (bc *BlockChain) PopulateSetPrivateState(ps func([]*types.Log, *state.StateDB, types.PrivateStateIdentifier)) { 2758 bc.setPrivateState = ps 2759 } 2760 2761 // CheckAndSetPrivateState function to update the private state as a part contract state extension 2762 // Quorum 2763 func (bc *BlockChain) CheckAndSetPrivateState(txLogs []*types.Log, privateState *state.StateDB, psi types.PrivateStateIdentifier) { 2764 if bc.setPrivateState != nil { 2765 bc.setPrivateState(txLogs, privateState, psi) 2766 } 2767 }