github.com/tuotoo/go-ethereum@v1.7.4-0.20171121184211-049797d40a24/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 "errors" 22 "fmt" 23 "io" 24 "math/big" 25 mrand "math/rand" 26 "sync" 27 "sync/atomic" 28 "time" 29 30 "github.com/ethereum/go-ethereum/common" 31 "github.com/ethereum/go-ethereum/common/mclock" 32 "github.com/ethereum/go-ethereum/consensus" 33 "github.com/ethereum/go-ethereum/core/state" 34 "github.com/ethereum/go-ethereum/core/types" 35 "github.com/ethereum/go-ethereum/core/vm" 36 "github.com/ethereum/go-ethereum/crypto" 37 "github.com/ethereum/go-ethereum/ethdb" 38 "github.com/ethereum/go-ethereum/event" 39 "github.com/ethereum/go-ethereum/log" 40 "github.com/ethereum/go-ethereum/metrics" 41 "github.com/ethereum/go-ethereum/params" 42 "github.com/ethereum/go-ethereum/rlp" 43 "github.com/ethereum/go-ethereum/trie" 44 "github.com/hashicorp/golang-lru" 45 ) 46 47 var ( 48 blockInsertTimer = metrics.NewTimer("chain/inserts") 49 50 ErrNoGenesis = errors.New("Genesis not found in chain") 51 ) 52 53 const ( 54 bodyCacheLimit = 256 55 blockCacheLimit = 256 56 maxFutureBlocks = 256 57 maxTimeFutureBlocks = 30 58 badBlockLimit = 10 59 60 // BlockChainVersion ensures that an incompatible database forces a resync from scratch. 61 BlockChainVersion = 3 62 ) 63 64 // BlockChain represents the canonical chain given a database with a genesis 65 // block. The Blockchain manages chain imports, reverts, chain reorganisations. 66 // 67 // Importing blocks in to the block chain happens according to the set of rules 68 // defined by the two stage Validator. Processing of blocks is done using the 69 // Processor which processes the included transaction. The validation of the state 70 // is done in the second part of the Validator. Failing results in aborting of 71 // the import. 72 // 73 // The BlockChain also helps in returning blocks from **any** chain included 74 // in the database as well as blocks that represents the canonical chain. It's 75 // important to note that GetBlock can return any block and does not need to be 76 // included in the canonical one where as GetBlockByNumber always represents the 77 // canonical chain. 78 type BlockChain struct { 79 config *params.ChainConfig // chain & network configuration 80 81 hc *HeaderChain 82 chainDb ethdb.Database 83 rmLogsFeed event.Feed 84 chainFeed event.Feed 85 chainSideFeed event.Feed 86 chainHeadFeed event.Feed 87 logsFeed event.Feed 88 scope event.SubscriptionScope 89 genesisBlock *types.Block 90 91 mu sync.RWMutex // global mutex for locking chain operations 92 chainmu sync.RWMutex // blockchain insertion lock 93 procmu sync.RWMutex // block processor lock 94 95 checkpoint int // checkpoint counts towards the new checkpoint 96 currentBlock *types.Block // Current head of the block chain 97 currentFastBlock *types.Block // Current head of the fast-sync chain (may be above the block chain!) 98 99 stateCache state.Database // State database to reuse between imports (contains state cache) 100 bodyCache *lru.Cache // Cache for the most recent block bodies 101 bodyRLPCache *lru.Cache // Cache for the most recent block bodies in RLP encoded format 102 blockCache *lru.Cache // Cache for the most recent entire blocks 103 futureBlocks *lru.Cache // future blocks are blocks added for later processing 104 105 quit chan struct{} // blockchain quit channel 106 running int32 // running must be called atomically 107 // procInterrupt must be atomically called 108 procInterrupt int32 // interrupt signaler for block processing 109 wg sync.WaitGroup // chain processing wait group for shutting down 110 111 engine consensus.Engine 112 processor Processor // block processor interface 113 validator Validator // block and state validator interface 114 vmConfig vm.Config 115 116 badBlocks *lru.Cache // Bad block cache 117 } 118 119 // NewBlockChain returns a fully initialised block chain using information 120 // available in the database. It initialises the default Ethereum Validator and 121 // Processor. 122 func NewBlockChain(chainDb ethdb.Database, config *params.ChainConfig, engine consensus.Engine, vmConfig vm.Config) (*BlockChain, error) { 123 bodyCache, _ := lru.New(bodyCacheLimit) 124 bodyRLPCache, _ := lru.New(bodyCacheLimit) 125 blockCache, _ := lru.New(blockCacheLimit) 126 futureBlocks, _ := lru.New(maxFutureBlocks) 127 badBlocks, _ := lru.New(badBlockLimit) 128 129 bc := &BlockChain{ 130 config: config, 131 chainDb: chainDb, 132 stateCache: state.NewDatabase(chainDb), 133 quit: make(chan struct{}), 134 bodyCache: bodyCache, 135 bodyRLPCache: bodyRLPCache, 136 blockCache: blockCache, 137 futureBlocks: futureBlocks, 138 engine: engine, 139 vmConfig: vmConfig, 140 badBlocks: badBlocks, 141 } 142 bc.SetValidator(NewBlockValidator(config, bc, engine)) 143 bc.SetProcessor(NewStateProcessor(config, bc, engine)) 144 145 var err error 146 bc.hc, err = NewHeaderChain(chainDb, config, engine, bc.getProcInterrupt) 147 if err != nil { 148 return nil, err 149 } 150 bc.genesisBlock = bc.GetBlockByNumber(0) 151 if bc.genesisBlock == nil { 152 return nil, ErrNoGenesis 153 } 154 if err := bc.loadLastState(); err != nil { 155 return nil, err 156 } 157 // Check the current state of the block hashes and make sure that we do not have any of the bad blocks in our chain 158 for hash := range BadHashes { 159 if header := bc.GetHeaderByHash(hash); header != nil { 160 // get the canonical block corresponding to the offending header's number 161 headerByNumber := bc.GetHeaderByNumber(header.Number.Uint64()) 162 // make sure the headerByNumber (if present) is in our current canonical chain 163 if headerByNumber != nil && headerByNumber.Hash() == header.Hash() { 164 log.Error("Found bad hash, rewinding chain", "number", header.Number, "hash", header.ParentHash) 165 bc.SetHead(header.Number.Uint64() - 1) 166 log.Error("Chain rewind was successful, resuming normal operation") 167 } 168 } 169 } 170 // Take ownership of this particular state 171 go bc.update() 172 return bc, nil 173 } 174 175 func (bc *BlockChain) getProcInterrupt() bool { 176 return atomic.LoadInt32(&bc.procInterrupt) == 1 177 } 178 179 // loadLastState loads the last known chain state from the database. This method 180 // assumes that the chain manager mutex is held. 181 func (bc *BlockChain) loadLastState() error { 182 // Restore the last known head block 183 head := GetHeadBlockHash(bc.chainDb) 184 if head == (common.Hash{}) { 185 // Corrupt or empty database, init from scratch 186 log.Warn("Empty database, resetting chain") 187 return bc.Reset() 188 } 189 // Make sure the entire head block is available 190 currentBlock := bc.GetBlockByHash(head) 191 if currentBlock == nil { 192 // Corrupt or empty database, init from scratch 193 log.Warn("Head block missing, resetting chain", "hash", head) 194 return bc.Reset() 195 } 196 // Make sure the state associated with the block is available 197 if _, err := state.New(currentBlock.Root(), bc.stateCache); err != nil { 198 // Dangling block without a state associated, init from scratch 199 log.Warn("Head state missing, resetting chain", "number", currentBlock.Number(), "hash", currentBlock.Hash()) 200 return bc.Reset() 201 } 202 // Everything seems to be fine, set as the head block 203 bc.currentBlock = currentBlock 204 205 // Restore the last known head header 206 currentHeader := bc.currentBlock.Header() 207 if head := GetHeadHeaderHash(bc.chainDb); head != (common.Hash{}) { 208 if header := bc.GetHeaderByHash(head); header != nil { 209 currentHeader = header 210 } 211 } 212 bc.hc.SetCurrentHeader(currentHeader) 213 214 // Restore the last known head fast block 215 bc.currentFastBlock = bc.currentBlock 216 if head := GetHeadFastBlockHash(bc.chainDb); head != (common.Hash{}) { 217 if block := bc.GetBlockByHash(head); block != nil { 218 bc.currentFastBlock = block 219 } 220 } 221 222 // Issue a status log for the user 223 headerTd := bc.GetTd(currentHeader.Hash(), currentHeader.Number.Uint64()) 224 blockTd := bc.GetTd(bc.currentBlock.Hash(), bc.currentBlock.NumberU64()) 225 fastTd := bc.GetTd(bc.currentFastBlock.Hash(), bc.currentFastBlock.NumberU64()) 226 227 log.Info("Loaded most recent local header", "number", currentHeader.Number, "hash", currentHeader.Hash(), "td", headerTd) 228 log.Info("Loaded most recent local full block", "number", bc.currentBlock.Number(), "hash", bc.currentBlock.Hash(), "td", blockTd) 229 log.Info("Loaded most recent local fast block", "number", bc.currentFastBlock.Number(), "hash", bc.currentFastBlock.Hash(), "td", fastTd) 230 231 return nil 232 } 233 234 // SetHead rewinds the local chain to a new head. In the case of headers, everything 235 // above the new head will be deleted and the new one set. In the case of blocks 236 // though, the head may be further rewound if block bodies are missing (non-archive 237 // nodes after a fast sync). 238 func (bc *BlockChain) SetHead(head uint64) error { 239 log.Warn("Rewinding blockchain", "target", head) 240 241 bc.mu.Lock() 242 defer bc.mu.Unlock() 243 244 // Rewind the header chain, deleting all block bodies until then 245 delFn := func(hash common.Hash, num uint64) { 246 DeleteBody(bc.chainDb, hash, num) 247 } 248 bc.hc.SetHead(head, delFn) 249 currentHeader := bc.hc.CurrentHeader() 250 251 // Clear out any stale content from the caches 252 bc.bodyCache.Purge() 253 bc.bodyRLPCache.Purge() 254 bc.blockCache.Purge() 255 bc.futureBlocks.Purge() 256 257 // Rewind the block chain, ensuring we don't end up with a stateless head block 258 if bc.currentBlock != nil && currentHeader.Number.Uint64() < bc.currentBlock.NumberU64() { 259 bc.currentBlock = bc.GetBlock(currentHeader.Hash(), currentHeader.Number.Uint64()) 260 } 261 if bc.currentBlock != nil { 262 if _, err := state.New(bc.currentBlock.Root(), bc.stateCache); err != nil { 263 // Rewound state missing, rolled back to before pivot, reset to genesis 264 bc.currentBlock = nil 265 } 266 } 267 // Rewind the fast block in a simpleton way to the target head 268 if bc.currentFastBlock != nil && currentHeader.Number.Uint64() < bc.currentFastBlock.NumberU64() { 269 bc.currentFastBlock = bc.GetBlock(currentHeader.Hash(), currentHeader.Number.Uint64()) 270 } 271 // If either blocks reached nil, reset to the genesis state 272 if bc.currentBlock == nil { 273 bc.currentBlock = bc.genesisBlock 274 } 275 if bc.currentFastBlock == nil { 276 bc.currentFastBlock = bc.genesisBlock 277 } 278 if err := WriteHeadBlockHash(bc.chainDb, bc.currentBlock.Hash()); err != nil { 279 log.Crit("Failed to reset head full block", "err", err) 280 } 281 if err := WriteHeadFastBlockHash(bc.chainDb, bc.currentFastBlock.Hash()); err != nil { 282 log.Crit("Failed to reset head fast block", "err", err) 283 } 284 return bc.loadLastState() 285 } 286 287 // FastSyncCommitHead sets the current head block to the one defined by the hash 288 // irrelevant what the chain contents were prior. 289 func (bc *BlockChain) FastSyncCommitHead(hash common.Hash) error { 290 // Make sure that both the block as well at its state trie exists 291 block := bc.GetBlockByHash(hash) 292 if block == nil { 293 return fmt.Errorf("non existent block [%x…]", hash[:4]) 294 } 295 if _, err := trie.NewSecure(block.Root(), bc.chainDb, 0); err != nil { 296 return err 297 } 298 // If all checks out, manually set the head block 299 bc.mu.Lock() 300 bc.currentBlock = block 301 bc.mu.Unlock() 302 303 log.Info("Committed new head block", "number", block.Number(), "hash", hash) 304 return nil 305 } 306 307 // GasLimit returns the gas limit of the current HEAD block. 308 func (bc *BlockChain) GasLimit() *big.Int { 309 bc.mu.RLock() 310 defer bc.mu.RUnlock() 311 312 return bc.currentBlock.GasLimit() 313 } 314 315 // LastBlockHash return the hash of the HEAD block. 316 func (bc *BlockChain) LastBlockHash() common.Hash { 317 bc.mu.RLock() 318 defer bc.mu.RUnlock() 319 320 return bc.currentBlock.Hash() 321 } 322 323 // CurrentBlock retrieves the current head block of the canonical chain. The 324 // block is retrieved from the blockchain's internal cache. 325 func (bc *BlockChain) CurrentBlock() *types.Block { 326 bc.mu.RLock() 327 defer bc.mu.RUnlock() 328 329 return bc.currentBlock 330 } 331 332 // CurrentFastBlock retrieves the current fast-sync head block of the canonical 333 // chain. The block is retrieved from the blockchain's internal cache. 334 func (bc *BlockChain) CurrentFastBlock() *types.Block { 335 bc.mu.RLock() 336 defer bc.mu.RUnlock() 337 338 return bc.currentFastBlock 339 } 340 341 // Status returns status information about the current chain such as the HEAD Td, 342 // the HEAD hash and the hash of the genesis block. 343 func (bc *BlockChain) Status() (td *big.Int, currentBlock common.Hash, genesisBlock common.Hash) { 344 bc.mu.RLock() 345 defer bc.mu.RUnlock() 346 347 return bc.GetTd(bc.currentBlock.Hash(), bc.currentBlock.NumberU64()), bc.currentBlock.Hash(), bc.genesisBlock.Hash() 348 } 349 350 // SetProcessor sets the processor required for making state modifications. 351 func (bc *BlockChain) SetProcessor(processor Processor) { 352 bc.procmu.Lock() 353 defer bc.procmu.Unlock() 354 bc.processor = processor 355 } 356 357 // SetValidator sets the validator which is used to validate incoming blocks. 358 func (bc *BlockChain) SetValidator(validator Validator) { 359 bc.procmu.Lock() 360 defer bc.procmu.Unlock() 361 bc.validator = validator 362 } 363 364 // Validator returns the current validator. 365 func (bc *BlockChain) Validator() Validator { 366 bc.procmu.RLock() 367 defer bc.procmu.RUnlock() 368 return bc.validator 369 } 370 371 // Processor returns the current processor. 372 func (bc *BlockChain) Processor() Processor { 373 bc.procmu.RLock() 374 defer bc.procmu.RUnlock() 375 return bc.processor 376 } 377 378 // State returns a new mutable state based on the current HEAD block. 379 func (bc *BlockChain) State() (*state.StateDB, error) { 380 return bc.StateAt(bc.CurrentBlock().Root()) 381 } 382 383 // StateAt returns a new mutable state based on a particular point in time. 384 func (bc *BlockChain) StateAt(root common.Hash) (*state.StateDB, error) { 385 return state.New(root, bc.stateCache) 386 } 387 388 // Reset purges the entire blockchain, restoring it to its genesis state. 389 func (bc *BlockChain) Reset() error { 390 return bc.ResetWithGenesisBlock(bc.genesisBlock) 391 } 392 393 // ResetWithGenesisBlock purges the entire blockchain, restoring it to the 394 // specified genesis state. 395 func (bc *BlockChain) ResetWithGenesisBlock(genesis *types.Block) error { 396 // Dump the entire block chain and purge the caches 397 if err := bc.SetHead(0); err != nil { 398 return err 399 } 400 bc.mu.Lock() 401 defer bc.mu.Unlock() 402 403 // Prepare the genesis block and reinitialise the chain 404 if err := bc.hc.WriteTd(genesis.Hash(), genesis.NumberU64(), genesis.Difficulty()); err != nil { 405 log.Crit("Failed to write genesis block TD", "err", err) 406 } 407 if err := WriteBlock(bc.chainDb, genesis); err != nil { 408 log.Crit("Failed to write genesis block", "err", err) 409 } 410 bc.genesisBlock = genesis 411 bc.insert(bc.genesisBlock) 412 bc.currentBlock = bc.genesisBlock 413 bc.hc.SetGenesis(bc.genesisBlock.Header()) 414 bc.hc.SetCurrentHeader(bc.genesisBlock.Header()) 415 bc.currentFastBlock = bc.genesisBlock 416 417 return nil 418 } 419 420 // Export writes the active chain to the given writer. 421 func (bc *BlockChain) Export(w io.Writer) error { 422 return bc.ExportN(w, uint64(0), bc.currentBlock.NumberU64()) 423 } 424 425 // ExportN writes a subset of the active chain to the given writer. 426 func (bc *BlockChain) ExportN(w io.Writer, first uint64, last uint64) error { 427 bc.mu.RLock() 428 defer bc.mu.RUnlock() 429 430 if first > last { 431 return fmt.Errorf("export failed: first (%d) is greater than last (%d)", first, last) 432 } 433 log.Info("Exporting batch of blocks", "count", last-first+1) 434 435 for nr := first; nr <= last; nr++ { 436 block := bc.GetBlockByNumber(nr) 437 if block == nil { 438 return fmt.Errorf("export failed on #%d: not found", nr) 439 } 440 441 if err := block.EncodeRLP(w); err != nil { 442 return err 443 } 444 } 445 446 return nil 447 } 448 449 // insert injects a new head block into the current block chain. This method 450 // assumes that the block is indeed a true head. It will also reset the head 451 // header and the head fast sync block to this very same block if they are older 452 // or if they are on a different side chain. 453 // 454 // Note, this function assumes that the `mu` mutex is held! 455 func (bc *BlockChain) insert(block *types.Block) { 456 // If the block is on a side chain or an unknown one, force other heads onto it too 457 updateHeads := GetCanonicalHash(bc.chainDb, block.NumberU64()) != block.Hash() 458 459 // Add the block to the canonical chain number scheme and mark as the head 460 if err := WriteCanonicalHash(bc.chainDb, block.Hash(), block.NumberU64()); err != nil { 461 log.Crit("Failed to insert block number", "err", err) 462 } 463 if err := WriteHeadBlockHash(bc.chainDb, block.Hash()); err != nil { 464 log.Crit("Failed to insert head block hash", "err", err) 465 } 466 bc.currentBlock = block 467 468 // If the block is better than out head or is on a different chain, force update heads 469 if updateHeads { 470 bc.hc.SetCurrentHeader(block.Header()) 471 472 if err := WriteHeadFastBlockHash(bc.chainDb, block.Hash()); err != nil { 473 log.Crit("Failed to insert head fast block hash", "err", err) 474 } 475 bc.currentFastBlock = block 476 } 477 } 478 479 // Genesis retrieves the chain's genesis block. 480 func (bc *BlockChain) Genesis() *types.Block { 481 return bc.genesisBlock 482 } 483 484 // GetBody retrieves a block body (transactions and uncles) from the database by 485 // hash, caching it if found. 486 func (bc *BlockChain) GetBody(hash common.Hash) *types.Body { 487 // Short circuit if the body's already in the cache, retrieve otherwise 488 if cached, ok := bc.bodyCache.Get(hash); ok { 489 body := cached.(*types.Body) 490 return body 491 } 492 body := GetBody(bc.chainDb, hash, bc.hc.GetBlockNumber(hash)) 493 if body == nil { 494 return nil 495 } 496 // Cache the found body for next time and return 497 bc.bodyCache.Add(hash, body) 498 return body 499 } 500 501 // GetBodyRLP retrieves a block body in RLP encoding from the database by hash, 502 // caching it if found. 503 func (bc *BlockChain) GetBodyRLP(hash common.Hash) rlp.RawValue { 504 // Short circuit if the body's already in the cache, retrieve otherwise 505 if cached, ok := bc.bodyRLPCache.Get(hash); ok { 506 return cached.(rlp.RawValue) 507 } 508 body := GetBodyRLP(bc.chainDb, hash, bc.hc.GetBlockNumber(hash)) 509 if len(body) == 0 { 510 return nil 511 } 512 // Cache the found body for next time and return 513 bc.bodyRLPCache.Add(hash, body) 514 return body 515 } 516 517 // HasBlock checks if a block is fully present in the database or not. 518 func (bc *BlockChain) HasBlock(hash common.Hash, number uint64) bool { 519 if bc.blockCache.Contains(hash) { 520 return true 521 } 522 ok, _ := bc.chainDb.Has(blockBodyKey(hash, number)) 523 return ok 524 } 525 526 // HasBlockAndState checks if a block and associated state trie is fully present 527 // in the database or not, caching it if present. 528 func (bc *BlockChain) HasBlockAndState(hash common.Hash) bool { 529 // Check first that the block itself is known 530 block := bc.GetBlockByHash(hash) 531 if block == nil { 532 return false 533 } 534 // Ensure the associated state is also present 535 _, err := bc.stateCache.OpenTrie(block.Root()) 536 return err == nil 537 } 538 539 // GetBlock retrieves a block from the database by hash and number, 540 // caching it if found. 541 func (bc *BlockChain) GetBlock(hash common.Hash, number uint64) *types.Block { 542 // Short circuit if the block's already in the cache, retrieve otherwise 543 if block, ok := bc.blockCache.Get(hash); ok { 544 return block.(*types.Block) 545 } 546 block := GetBlock(bc.chainDb, hash, number) 547 if block == nil { 548 return nil 549 } 550 // Cache the found block for next time and return 551 bc.blockCache.Add(block.Hash(), block) 552 return block 553 } 554 555 // GetBlockByHash retrieves a block from the database by hash, caching it if found. 556 func (bc *BlockChain) GetBlockByHash(hash common.Hash) *types.Block { 557 return bc.GetBlock(hash, bc.hc.GetBlockNumber(hash)) 558 } 559 560 // GetBlockByNumber retrieves a block from the database by number, caching it 561 // (associated with its hash) if found. 562 func (bc *BlockChain) GetBlockByNumber(number uint64) *types.Block { 563 hash := GetCanonicalHash(bc.chainDb, number) 564 if hash == (common.Hash{}) { 565 return nil 566 } 567 return bc.GetBlock(hash, number) 568 } 569 570 // GetBlocksFromHash returns the block corresponding to hash and up to n-1 ancestors. 571 // [deprecated by eth/62] 572 func (bc *BlockChain) GetBlocksFromHash(hash common.Hash, n int) (blocks []*types.Block) { 573 number := bc.hc.GetBlockNumber(hash) 574 for i := 0; i < n; i++ { 575 block := bc.GetBlock(hash, number) 576 if block == nil { 577 break 578 } 579 blocks = append(blocks, block) 580 hash = block.ParentHash() 581 number-- 582 } 583 return 584 } 585 586 // GetUnclesInChain retrieves all the uncles from a given block backwards until 587 // a specific distance is reached. 588 func (bc *BlockChain) GetUnclesInChain(block *types.Block, length int) []*types.Header { 589 uncles := []*types.Header{} 590 for i := 0; block != nil && i < length; i++ { 591 uncles = append(uncles, block.Uncles()...) 592 block = bc.GetBlock(block.ParentHash(), block.NumberU64()-1) 593 } 594 return uncles 595 } 596 597 // Stop stops the blockchain service. If any imports are currently in progress 598 // it will abort them using the procInterrupt. 599 func (bc *BlockChain) Stop() { 600 if !atomic.CompareAndSwapInt32(&bc.running, 0, 1) { 601 return 602 } 603 // Unsubscribe all subscriptions registered from blockchain 604 bc.scope.Close() 605 close(bc.quit) 606 atomic.StoreInt32(&bc.procInterrupt, 1) 607 608 bc.wg.Wait() 609 log.Info("Blockchain manager stopped") 610 } 611 612 func (bc *BlockChain) procFutureBlocks() { 613 blocks := make([]*types.Block, 0, bc.futureBlocks.Len()) 614 for _, hash := range bc.futureBlocks.Keys() { 615 if block, exist := bc.futureBlocks.Peek(hash); exist { 616 blocks = append(blocks, block.(*types.Block)) 617 } 618 } 619 if len(blocks) > 0 { 620 types.BlockBy(types.Number).Sort(blocks) 621 622 // Insert one by one as chain insertion needs contiguous ancestry between blocks 623 for i := range blocks { 624 bc.InsertChain(blocks[i : i+1]) 625 } 626 } 627 } 628 629 // WriteStatus status of write 630 type WriteStatus byte 631 632 const ( 633 NonStatTy WriteStatus = iota 634 CanonStatTy 635 SideStatTy 636 ) 637 638 // Rollback is designed to remove a chain of links from the database that aren't 639 // certain enough to be valid. 640 func (bc *BlockChain) Rollback(chain []common.Hash) { 641 bc.mu.Lock() 642 defer bc.mu.Unlock() 643 644 for i := len(chain) - 1; i >= 0; i-- { 645 hash := chain[i] 646 647 currentHeader := bc.hc.CurrentHeader() 648 if currentHeader.Hash() == hash { 649 bc.hc.SetCurrentHeader(bc.GetHeader(currentHeader.ParentHash, currentHeader.Number.Uint64()-1)) 650 } 651 if bc.currentFastBlock.Hash() == hash { 652 bc.currentFastBlock = bc.GetBlock(bc.currentFastBlock.ParentHash(), bc.currentFastBlock.NumberU64()-1) 653 WriteHeadFastBlockHash(bc.chainDb, bc.currentFastBlock.Hash()) 654 } 655 if bc.currentBlock.Hash() == hash { 656 bc.currentBlock = bc.GetBlock(bc.currentBlock.ParentHash(), bc.currentBlock.NumberU64()-1) 657 WriteHeadBlockHash(bc.chainDb, bc.currentBlock.Hash()) 658 } 659 } 660 } 661 662 // SetReceiptsData computes all the non-consensus fields of the receipts 663 func SetReceiptsData(config *params.ChainConfig, block *types.Block, receipts types.Receipts) { 664 signer := types.MakeSigner(config, block.Number()) 665 666 transactions, logIndex := block.Transactions(), uint(0) 667 668 for j := 0; j < len(receipts); j++ { 669 // The transaction hash can be retrieved from the transaction itself 670 receipts[j].TxHash = transactions[j].Hash() 671 672 // The contract address can be derived from the transaction itself 673 if transactions[j].To() == nil { 674 // Deriving the signer is expensive, only do if it's actually needed 675 from, _ := types.Sender(signer, transactions[j]) 676 receipts[j].ContractAddress = crypto.CreateAddress(from, transactions[j].Nonce()) 677 } 678 // The used gas can be calculated based on previous receipts 679 if j == 0 { 680 receipts[j].GasUsed = new(big.Int).Set(receipts[j].CumulativeGasUsed) 681 } else { 682 receipts[j].GasUsed = new(big.Int).Sub(receipts[j].CumulativeGasUsed, receipts[j-1].CumulativeGasUsed) 683 } 684 // The derived log fields can simply be set from the block and transaction 685 for k := 0; k < len(receipts[j].Logs); k++ { 686 receipts[j].Logs[k].BlockNumber = block.NumberU64() 687 receipts[j].Logs[k].BlockHash = block.Hash() 688 receipts[j].Logs[k].TxHash = receipts[j].TxHash 689 receipts[j].Logs[k].TxIndex = uint(j) 690 receipts[j].Logs[k].Index = logIndex 691 logIndex++ 692 } 693 } 694 } 695 696 // InsertReceiptChain attempts to complete an already existing header chain with 697 // transaction and receipt data. 698 func (bc *BlockChain) InsertReceiptChain(blockChain types.Blocks, receiptChain []types.Receipts) (int, error) { 699 bc.wg.Add(1) 700 defer bc.wg.Done() 701 702 // Do a sanity check that the provided chain is actually ordered and linked 703 for i := 1; i < len(blockChain); i++ { 704 if blockChain[i].NumberU64() != blockChain[i-1].NumberU64()+1 || blockChain[i].ParentHash() != blockChain[i-1].Hash() { 705 log.Error("Non contiguous receipt insert", "number", blockChain[i].Number(), "hash", blockChain[i].Hash(), "parent", blockChain[i].ParentHash(), 706 "prevnumber", blockChain[i-1].Number(), "prevhash", blockChain[i-1].Hash()) 707 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(), 708 blockChain[i-1].Hash().Bytes()[:4], i, blockChain[i].NumberU64(), blockChain[i].Hash().Bytes()[:4], blockChain[i].ParentHash().Bytes()[:4]) 709 } 710 } 711 712 var ( 713 stats = struct{ processed, ignored int32 }{} 714 start = time.Now() 715 bytes = 0 716 batch = bc.chainDb.NewBatch() 717 ) 718 for i, block := range blockChain { 719 receipts := receiptChain[i] 720 // Short circuit insertion if shutting down or processing failed 721 if atomic.LoadInt32(&bc.procInterrupt) == 1 { 722 return 0, nil 723 } 724 // Short circuit if the owner header is unknown 725 if !bc.HasHeader(block.Hash(), block.NumberU64()) { 726 return i, fmt.Errorf("containing header #%d [%x…] unknown", block.Number(), block.Hash().Bytes()[:4]) 727 } 728 // Skip if the entire data is already known 729 if bc.HasBlock(block.Hash(), block.NumberU64()) { 730 stats.ignored++ 731 continue 732 } 733 // Compute all the non-consensus fields of the receipts 734 SetReceiptsData(bc.config, block, receipts) 735 // Write all the data out into the database 736 if err := WriteBody(batch, block.Hash(), block.NumberU64(), block.Body()); err != nil { 737 return i, fmt.Errorf("failed to write block body: %v", err) 738 } 739 if err := WriteBlockReceipts(batch, block.Hash(), block.NumberU64(), receipts); err != nil { 740 return i, fmt.Errorf("failed to write block receipts: %v", err) 741 } 742 if err := WriteTxLookupEntries(batch, block); err != nil { 743 return i, fmt.Errorf("failed to write lookup metadata: %v", err) 744 } 745 stats.processed++ 746 747 if batch.ValueSize() >= ethdb.IdealBatchSize { 748 if err := batch.Write(); err != nil { 749 return 0, err 750 } 751 bytes += batch.ValueSize() 752 batch = bc.chainDb.NewBatch() 753 } 754 } 755 if batch.ValueSize() > 0 { 756 bytes += batch.ValueSize() 757 if err := batch.Write(); err != nil { 758 return 0, err 759 } 760 } 761 762 // Update the head fast sync block if better 763 bc.mu.Lock() 764 head := blockChain[len(blockChain)-1] 765 if td := bc.GetTd(head.Hash(), head.NumberU64()); td != nil { // Rewind may have occurred, skip in that case 766 if bc.GetTd(bc.currentFastBlock.Hash(), bc.currentFastBlock.NumberU64()).Cmp(td) < 0 { 767 if err := WriteHeadFastBlockHash(bc.chainDb, head.Hash()); err != nil { 768 log.Crit("Failed to update head fast block hash", "err", err) 769 } 770 bc.currentFastBlock = head 771 } 772 } 773 bc.mu.Unlock() 774 775 log.Info("Imported new block receipts", 776 "count", stats.processed, 777 "elapsed", common.PrettyDuration(time.Since(start)), 778 "bytes", bytes, 779 "number", head.Number(), 780 "hash", head.Hash(), 781 "ignored", stats.ignored) 782 return 0, nil 783 } 784 785 // WriteBlock writes the block to the chain. 786 func (bc *BlockChain) WriteBlockAndState(block *types.Block, receipts []*types.Receipt, state *state.StateDB) (status WriteStatus, err error) { 787 bc.wg.Add(1) 788 defer bc.wg.Done() 789 790 // Calculate the total difficulty of the block 791 ptd := bc.GetTd(block.ParentHash(), block.NumberU64()-1) 792 if ptd == nil { 793 return NonStatTy, consensus.ErrUnknownAncestor 794 } 795 // Make sure no inconsistent state is leaked during insertion 796 bc.mu.Lock() 797 defer bc.mu.Unlock() 798 799 localTd := bc.GetTd(bc.currentBlock.Hash(), bc.currentBlock.NumberU64()) 800 externTd := new(big.Int).Add(block.Difficulty(), ptd) 801 802 // Irrelevant of the canonical status, write the block itself to the database 803 if err := bc.hc.WriteTd(block.Hash(), block.NumberU64(), externTd); err != nil { 804 return NonStatTy, err 805 } 806 // Write other block data using a batch. 807 batch := bc.chainDb.NewBatch() 808 if err := WriteBlock(batch, block); err != nil { 809 return NonStatTy, err 810 } 811 if _, err := state.CommitTo(batch, bc.config.IsEIP158(block.Number())); err != nil { 812 return NonStatTy, err 813 } 814 if err := WriteBlockReceipts(batch, block.Hash(), block.NumberU64(), receipts); err != nil { 815 return NonStatTy, err 816 } 817 818 // If the total difficulty is higher than our known, add it to the canonical chain 819 // Second clause in the if statement reduces the vulnerability to selfish mining. 820 // Please refer to http://www.cs.cornell.edu/~ie53/publications/btcProcFC.pdf 821 reorg := externTd.Cmp(localTd) > 0 822 if !reorg && externTd.Cmp(localTd) == 0 { 823 // Split same-difficulty blocks by number, then at random 824 reorg = block.NumberU64() < bc.currentBlock.NumberU64() || (block.NumberU64() == bc.currentBlock.NumberU64() && mrand.Float64() < 0.5) 825 } 826 if reorg { 827 // Reorganise the chain if the parent is not the head block 828 if block.ParentHash() != bc.currentBlock.Hash() { 829 if err := bc.reorg(bc.currentBlock, block); err != nil { 830 return NonStatTy, err 831 } 832 } 833 // Write the positional metadata for transaction and receipt lookups 834 if err := WriteTxLookupEntries(batch, block); err != nil { 835 return NonStatTy, err 836 } 837 // Write hash preimages 838 if err := WritePreimages(bc.chainDb, block.NumberU64(), state.Preimages()); err != nil { 839 return NonStatTy, err 840 } 841 status = CanonStatTy 842 } else { 843 status = SideStatTy 844 } 845 if err := batch.Write(); err != nil { 846 return NonStatTy, err 847 } 848 849 // Set new head. 850 if status == CanonStatTy { 851 bc.insert(block) 852 } 853 bc.futureBlocks.Remove(block.Hash()) 854 return status, nil 855 } 856 857 // InsertChain attempts to insert the given batch of blocks in to the canonical 858 // chain or, otherwise, create a fork. If an error is returned it will return 859 // the index number of the failing block as well an error describing what went 860 // wrong. 861 // 862 // After insertion is done, all accumulated events will be fired. 863 func (bc *BlockChain) InsertChain(chain types.Blocks) (int, error) { 864 n, events, logs, err := bc.insertChain(chain) 865 bc.PostChainEvents(events, logs) 866 return n, err 867 } 868 869 // insertChain will execute the actual chain insertion and event aggregation. The 870 // only reason this method exists as a separate one is to make locking cleaner 871 // with deferred statements. 872 func (bc *BlockChain) insertChain(chain types.Blocks) (int, []interface{}, []*types.Log, error) { 873 // Do a sanity check that the provided chain is actually ordered and linked 874 for i := 1; i < len(chain); i++ { 875 if chain[i].NumberU64() != chain[i-1].NumberU64()+1 || chain[i].ParentHash() != chain[i-1].Hash() { 876 // Chain broke ancestry, log a messge (programming error) and skip insertion 877 log.Error("Non contiguous block insert", "number", chain[i].Number(), "hash", chain[i].Hash(), 878 "parent", chain[i].ParentHash(), "prevnumber", chain[i-1].Number(), "prevhash", chain[i-1].Hash()) 879 880 return 0, nil, nil, fmt.Errorf("non contiguous insert: item %d is #%d [%x…], item %d is #%d [%x…] (parent [%x…])", i-1, chain[i-1].NumberU64(), 881 chain[i-1].Hash().Bytes()[:4], i, chain[i].NumberU64(), chain[i].Hash().Bytes()[:4], chain[i].ParentHash().Bytes()[:4]) 882 } 883 } 884 // Pre-checks passed, start the full block imports 885 bc.wg.Add(1) 886 defer bc.wg.Done() 887 888 bc.chainmu.Lock() 889 defer bc.chainmu.Unlock() 890 891 // A queued approach to delivering events. This is generally 892 // faster than direct delivery and requires much less mutex 893 // acquiring. 894 var ( 895 stats = insertStats{startTime: mclock.Now()} 896 events = make([]interface{}, 0, len(chain)) 897 lastCanon *types.Block 898 coalescedLogs []*types.Log 899 ) 900 // Start the parallel header verifier 901 headers := make([]*types.Header, len(chain)) 902 seals := make([]bool, len(chain)) 903 904 for i, block := range chain { 905 headers[i] = block.Header() 906 seals[i] = true 907 } 908 abort, results := bc.engine.VerifyHeaders(bc, headers, seals) 909 defer close(abort) 910 911 // Iterate over the blocks and insert when the verifier permits 912 for i, block := range chain { 913 // If the chain is terminating, stop processing blocks 914 if atomic.LoadInt32(&bc.procInterrupt) == 1 { 915 log.Debug("Premature abort during blocks processing") 916 break 917 } 918 // If the header is a banned one, straight out abort 919 if BadHashes[block.Hash()] { 920 bc.reportBlock(block, nil, ErrBlacklistedHash) 921 return i, events, coalescedLogs, ErrBlacklistedHash 922 } 923 // Wait for the block's verification to complete 924 bstart := time.Now() 925 926 err := <-results 927 if err == nil { 928 err = bc.Validator().ValidateBody(block) 929 } 930 if err != nil { 931 if err == ErrKnownBlock { 932 stats.ignored++ 933 continue 934 } 935 936 if err == consensus.ErrFutureBlock { 937 // Allow up to MaxFuture second in the future blocks. If this limit 938 // is exceeded the chain is discarded and processed at a later time 939 // if given. 940 max := big.NewInt(time.Now().Unix() + maxTimeFutureBlocks) 941 if block.Time().Cmp(max) > 0 { 942 return i, events, coalescedLogs, fmt.Errorf("future block: %v > %v", block.Time(), max) 943 } 944 bc.futureBlocks.Add(block.Hash(), block) 945 stats.queued++ 946 continue 947 } 948 949 if err == consensus.ErrUnknownAncestor && bc.futureBlocks.Contains(block.ParentHash()) { 950 bc.futureBlocks.Add(block.Hash(), block) 951 stats.queued++ 952 continue 953 } 954 955 bc.reportBlock(block, nil, err) 956 return i, events, coalescedLogs, err 957 } 958 // Create a new statedb using the parent block and report an 959 // error if it fails. 960 var parent *types.Block 961 if i == 0 { 962 parent = bc.GetBlock(block.ParentHash(), block.NumberU64()-1) 963 } else { 964 parent = chain[i-1] 965 } 966 state, err := state.New(parent.Root(), bc.stateCache) 967 if err != nil { 968 return i, events, coalescedLogs, err 969 } 970 // Process block using the parent state as reference point. 971 receipts, logs, usedGas, err := bc.processor.Process(block, state, bc.vmConfig) 972 if err != nil { 973 bc.reportBlock(block, receipts, err) 974 return i, events, coalescedLogs, err 975 } 976 // Validate the state using the default validator 977 err = bc.Validator().ValidateState(block, parent, state, receipts, usedGas) 978 if err != nil { 979 bc.reportBlock(block, receipts, err) 980 return i, events, coalescedLogs, err 981 } 982 // Write the block to the chain and get the status. 983 status, err := bc.WriteBlockAndState(block, receipts, state) 984 if err != nil { 985 return i, events, coalescedLogs, err 986 } 987 switch status { 988 case CanonStatTy: 989 log.Debug("Inserted new block", "number", block.Number(), "hash", block.Hash(), "uncles", len(block.Uncles()), 990 "txs", len(block.Transactions()), "gas", block.GasUsed(), "elapsed", common.PrettyDuration(time.Since(bstart))) 991 992 coalescedLogs = append(coalescedLogs, logs...) 993 blockInsertTimer.UpdateSince(bstart) 994 events = append(events, ChainEvent{block, block.Hash(), logs}) 995 lastCanon = block 996 997 case SideStatTy: 998 log.Debug("Inserted forked block", "number", block.Number(), "hash", block.Hash(), "diff", block.Difficulty(), "elapsed", 999 common.PrettyDuration(time.Since(bstart)), "txs", len(block.Transactions()), "gas", block.GasUsed(), "uncles", len(block.Uncles())) 1000 1001 blockInsertTimer.UpdateSince(bstart) 1002 events = append(events, ChainSideEvent{block}) 1003 } 1004 stats.processed++ 1005 stats.usedGas += usedGas.Uint64() 1006 stats.report(chain, i) 1007 } 1008 // Append a single chain head event if we've progressed the chain 1009 if lastCanon != nil && bc.LastBlockHash() == lastCanon.Hash() { 1010 events = append(events, ChainHeadEvent{lastCanon}) 1011 } 1012 return 0, events, coalescedLogs, nil 1013 } 1014 1015 // insertStats tracks and reports on block insertion. 1016 type insertStats struct { 1017 queued, processed, ignored int 1018 usedGas uint64 1019 lastIndex int 1020 startTime mclock.AbsTime 1021 } 1022 1023 // statsReportLimit is the time limit during import after which we always print 1024 // out progress. This avoids the user wondering what's going on. 1025 const statsReportLimit = 8 * time.Second 1026 1027 // report prints statistics if some number of blocks have been processed 1028 // or more than a few seconds have passed since the last message. 1029 func (st *insertStats) report(chain []*types.Block, index int) { 1030 // Fetch the timings for the batch 1031 var ( 1032 now = mclock.Now() 1033 elapsed = time.Duration(now) - time.Duration(st.startTime) 1034 ) 1035 // If we're at the last block of the batch or report period reached, log 1036 if index == len(chain)-1 || elapsed >= statsReportLimit { 1037 var ( 1038 end = chain[index] 1039 txs = countTransactions(chain[st.lastIndex : index+1]) 1040 ) 1041 context := []interface{}{ 1042 "blocks", st.processed, "txs", txs, "mgas", float64(st.usedGas) / 1000000, 1043 "elapsed", common.PrettyDuration(elapsed), "mgasps", float64(st.usedGas) * 1000 / float64(elapsed), 1044 "number", end.Number(), "hash", end.Hash(), 1045 } 1046 if st.queued > 0 { 1047 context = append(context, []interface{}{"queued", st.queued}...) 1048 } 1049 if st.ignored > 0 { 1050 context = append(context, []interface{}{"ignored", st.ignored}...) 1051 } 1052 log.Info("Imported new chain segment", context...) 1053 1054 *st = insertStats{startTime: now, lastIndex: index + 1} 1055 } 1056 } 1057 1058 func countTransactions(chain []*types.Block) (c int) { 1059 for _, b := range chain { 1060 c += len(b.Transactions()) 1061 } 1062 return c 1063 } 1064 1065 // reorgs takes two blocks, an old chain and a new chain and will reconstruct the blocks and inserts them 1066 // to be part of the new canonical chain and accumulates potential missing transactions and post an 1067 // event about them 1068 func (bc *BlockChain) reorg(oldBlock, newBlock *types.Block) error { 1069 var ( 1070 newChain types.Blocks 1071 oldChain types.Blocks 1072 commonBlock *types.Block 1073 deletedTxs types.Transactions 1074 deletedLogs []*types.Log 1075 // collectLogs collects the logs that were generated during the 1076 // processing of the block that corresponds with the given hash. 1077 // These logs are later announced as deleted. 1078 collectLogs = func(h common.Hash) { 1079 // Coalesce logs and set 'Removed'. 1080 receipts := GetBlockReceipts(bc.chainDb, h, bc.hc.GetBlockNumber(h)) 1081 for _, receipt := range receipts { 1082 for _, log := range receipt.Logs { 1083 del := *log 1084 del.Removed = true 1085 deletedLogs = append(deletedLogs, &del) 1086 } 1087 } 1088 } 1089 ) 1090 1091 // first reduce whoever is higher bound 1092 if oldBlock.NumberU64() > newBlock.NumberU64() { 1093 // reduce old chain 1094 for ; oldBlock != nil && oldBlock.NumberU64() != newBlock.NumberU64(); oldBlock = bc.GetBlock(oldBlock.ParentHash(), oldBlock.NumberU64()-1) { 1095 oldChain = append(oldChain, oldBlock) 1096 deletedTxs = append(deletedTxs, oldBlock.Transactions()...) 1097 1098 collectLogs(oldBlock.Hash()) 1099 } 1100 } else { 1101 // reduce new chain and append new chain blocks for inserting later on 1102 for ; newBlock != nil && newBlock.NumberU64() != oldBlock.NumberU64(); newBlock = bc.GetBlock(newBlock.ParentHash(), newBlock.NumberU64()-1) { 1103 newChain = append(newChain, newBlock) 1104 } 1105 } 1106 if oldBlock == nil { 1107 return fmt.Errorf("Invalid old chain") 1108 } 1109 if newBlock == nil { 1110 return fmt.Errorf("Invalid new chain") 1111 } 1112 1113 for { 1114 if oldBlock.Hash() == newBlock.Hash() { 1115 commonBlock = oldBlock 1116 break 1117 } 1118 1119 oldChain = append(oldChain, oldBlock) 1120 newChain = append(newChain, newBlock) 1121 deletedTxs = append(deletedTxs, oldBlock.Transactions()...) 1122 collectLogs(oldBlock.Hash()) 1123 1124 oldBlock, newBlock = bc.GetBlock(oldBlock.ParentHash(), oldBlock.NumberU64()-1), bc.GetBlock(newBlock.ParentHash(), newBlock.NumberU64()-1) 1125 if oldBlock == nil { 1126 return fmt.Errorf("Invalid old chain") 1127 } 1128 if newBlock == nil { 1129 return fmt.Errorf("Invalid new chain") 1130 } 1131 } 1132 // Ensure the user sees large reorgs 1133 if len(oldChain) > 0 && len(newChain) > 0 { 1134 logFn := log.Debug 1135 if len(oldChain) > 63 { 1136 logFn = log.Warn 1137 } 1138 logFn("Chain split detected", "number", commonBlock.Number(), "hash", commonBlock.Hash(), 1139 "drop", len(oldChain), "dropfrom", oldChain[0].Hash(), "add", len(newChain), "addfrom", newChain[0].Hash()) 1140 } else { 1141 log.Error("Impossible reorg, please file an issue", "oldnum", oldBlock.Number(), "oldhash", oldBlock.Hash(), "newnum", newBlock.Number(), "newhash", newBlock.Hash()) 1142 } 1143 var addedTxs types.Transactions 1144 // insert blocks. Order does not matter. Last block will be written in ImportChain itself which creates the new head properly 1145 for _, block := range newChain { 1146 // insert the block in the canonical way, re-writing history 1147 bc.insert(block) 1148 // write lookup entries for hash based transaction/receipt searches 1149 if err := WriteTxLookupEntries(bc.chainDb, block); err != nil { 1150 return err 1151 } 1152 addedTxs = append(addedTxs, block.Transactions()...) 1153 } 1154 1155 // calculate the difference between deleted and added transactions 1156 diff := types.TxDifference(deletedTxs, addedTxs) 1157 // When transactions get deleted from the database that means the 1158 // receipts that were created in the fork must also be deleted 1159 for _, tx := range diff { 1160 DeleteTxLookupEntry(bc.chainDb, tx.Hash()) 1161 } 1162 if len(deletedLogs) > 0 { 1163 go bc.rmLogsFeed.Send(RemovedLogsEvent{deletedLogs}) 1164 } 1165 if len(oldChain) > 0 { 1166 go func() { 1167 for _, block := range oldChain { 1168 bc.chainSideFeed.Send(ChainSideEvent{Block: block}) 1169 } 1170 }() 1171 } 1172 1173 return nil 1174 } 1175 1176 // PostChainEvents iterates over the events generated by a chain insertion and 1177 // posts them into the event feed. 1178 // TODO: Should not expose PostChainEvents. The chain events should be posted in WriteBlock. 1179 func (bc *BlockChain) PostChainEvents(events []interface{}, logs []*types.Log) { 1180 // post event logs for further processing 1181 if logs != nil { 1182 bc.logsFeed.Send(logs) 1183 } 1184 for _, event := range events { 1185 switch ev := event.(type) { 1186 case ChainEvent: 1187 bc.chainFeed.Send(ev) 1188 1189 case ChainHeadEvent: 1190 bc.chainHeadFeed.Send(ev) 1191 1192 case ChainSideEvent: 1193 bc.chainSideFeed.Send(ev) 1194 } 1195 } 1196 } 1197 1198 func (bc *BlockChain) update() { 1199 futureTimer := time.Tick(5 * time.Second) 1200 for { 1201 select { 1202 case <-futureTimer: 1203 bc.procFutureBlocks() 1204 case <-bc.quit: 1205 return 1206 } 1207 } 1208 } 1209 1210 // BadBlockArgs represents the entries in the list returned when bad blocks are queried. 1211 type BadBlockArgs struct { 1212 Hash common.Hash `json:"hash"` 1213 Header *types.Header `json:"header"` 1214 } 1215 1216 // BadBlocks returns a list of the last 'bad blocks' that the client has seen on the network 1217 func (bc *BlockChain) BadBlocks() ([]BadBlockArgs, error) { 1218 headers := make([]BadBlockArgs, 0, bc.badBlocks.Len()) 1219 for _, hash := range bc.badBlocks.Keys() { 1220 if hdr, exist := bc.badBlocks.Peek(hash); exist { 1221 header := hdr.(*types.Header) 1222 headers = append(headers, BadBlockArgs{header.Hash(), header}) 1223 } 1224 } 1225 return headers, nil 1226 } 1227 1228 // addBadBlock adds a bad block to the bad-block LRU cache 1229 func (bc *BlockChain) addBadBlock(block *types.Block) { 1230 bc.badBlocks.Add(block.Header().Hash(), block.Header()) 1231 } 1232 1233 // reportBlock logs a bad block error. 1234 func (bc *BlockChain) reportBlock(block *types.Block, receipts types.Receipts, err error) { 1235 bc.addBadBlock(block) 1236 1237 var receiptString string 1238 for _, receipt := range receipts { 1239 receiptString += fmt.Sprintf("\t%v\n", receipt) 1240 } 1241 log.Error(fmt.Sprintf(` 1242 ########## BAD BLOCK ######### 1243 Chain config: %v 1244 1245 Number: %v 1246 Hash: 0x%x 1247 %v 1248 1249 Error: %v 1250 ############################## 1251 `, bc.config, block.Number(), block.Hash(), receiptString, err)) 1252 } 1253 1254 // InsertHeaderChain attempts to insert the given header chain in to the local 1255 // chain, possibly creating a reorg. If an error is returned, it will return the 1256 // index number of the failing header as well an error describing what went wrong. 1257 // 1258 // The verify parameter can be used to fine tune whether nonce verification 1259 // should be done or not. The reason behind the optional check is because some 1260 // of the header retrieval mechanisms already need to verify nonces, as well as 1261 // because nonces can be verified sparsely, not needing to check each. 1262 func (bc *BlockChain) InsertHeaderChain(chain []*types.Header, checkFreq int) (int, error) { 1263 start := time.Now() 1264 if i, err := bc.hc.ValidateHeaderChain(chain, checkFreq); err != nil { 1265 return i, err 1266 } 1267 1268 // Make sure only one thread manipulates the chain at once 1269 bc.chainmu.Lock() 1270 defer bc.chainmu.Unlock() 1271 1272 bc.wg.Add(1) 1273 defer bc.wg.Done() 1274 1275 whFunc := func(header *types.Header) error { 1276 bc.mu.Lock() 1277 defer bc.mu.Unlock() 1278 1279 _, err := bc.hc.WriteHeader(header) 1280 return err 1281 } 1282 1283 return bc.hc.InsertHeaderChain(chain, whFunc, start) 1284 } 1285 1286 // writeHeader writes a header into the local chain, given that its parent is 1287 // already known. If the total difficulty of the newly inserted header becomes 1288 // greater than the current known TD, the canonical chain is re-routed. 1289 // 1290 // Note: This method is not concurrent-safe with inserting blocks simultaneously 1291 // into the chain, as side effects caused by reorganisations cannot be emulated 1292 // without the real blocks. Hence, writing headers directly should only be done 1293 // in two scenarios: pure-header mode of operation (light clients), or properly 1294 // separated header/block phases (non-archive clients). 1295 func (bc *BlockChain) writeHeader(header *types.Header) error { 1296 bc.wg.Add(1) 1297 defer bc.wg.Done() 1298 1299 bc.mu.Lock() 1300 defer bc.mu.Unlock() 1301 1302 _, err := bc.hc.WriteHeader(header) 1303 return err 1304 } 1305 1306 // CurrentHeader retrieves the current head header of the canonical chain. The 1307 // header is retrieved from the HeaderChain's internal cache. 1308 func (bc *BlockChain) CurrentHeader() *types.Header { 1309 bc.mu.RLock() 1310 defer bc.mu.RUnlock() 1311 1312 return bc.hc.CurrentHeader() 1313 } 1314 1315 // GetTd retrieves a block's total difficulty in the canonical chain from the 1316 // database by hash and number, caching it if found. 1317 func (bc *BlockChain) GetTd(hash common.Hash, number uint64) *big.Int { 1318 return bc.hc.GetTd(hash, number) 1319 } 1320 1321 // GetTdByHash retrieves a block's total difficulty in the canonical chain from the 1322 // database by hash, caching it if found. 1323 func (bc *BlockChain) GetTdByHash(hash common.Hash) *big.Int { 1324 return bc.hc.GetTdByHash(hash) 1325 } 1326 1327 // GetHeader retrieves a block header from the database by hash and number, 1328 // caching it if found. 1329 func (bc *BlockChain) GetHeader(hash common.Hash, number uint64) *types.Header { 1330 return bc.hc.GetHeader(hash, number) 1331 } 1332 1333 // GetHeaderByHash retrieves a block header from the database by hash, caching it if 1334 // found. 1335 func (bc *BlockChain) GetHeaderByHash(hash common.Hash) *types.Header { 1336 return bc.hc.GetHeaderByHash(hash) 1337 } 1338 1339 // HasHeader checks if a block header is present in the database or not, caching 1340 // it if present. 1341 func (bc *BlockChain) HasHeader(hash common.Hash, number uint64) bool { 1342 return bc.hc.HasHeader(hash, number) 1343 } 1344 1345 // GetBlockHashesFromHash retrieves a number of block hashes starting at a given 1346 // hash, fetching towards the genesis block. 1347 func (bc *BlockChain) GetBlockHashesFromHash(hash common.Hash, max uint64) []common.Hash { 1348 return bc.hc.GetBlockHashesFromHash(hash, max) 1349 } 1350 1351 // GetHeaderByNumber retrieves a block header from the database by number, 1352 // caching it (associated with its hash) if found. 1353 func (bc *BlockChain) GetHeaderByNumber(number uint64) *types.Header { 1354 return bc.hc.GetHeaderByNumber(number) 1355 } 1356 1357 // Config retrieves the blockchain's chain configuration. 1358 func (bc *BlockChain) Config() *params.ChainConfig { return bc.config } 1359 1360 // Engine retrieves the blockchain's consensus engine. 1361 func (bc *BlockChain) Engine() consensus.Engine { return bc.engine } 1362 1363 // SubscribeRemovedLogsEvent registers a subscription of RemovedLogsEvent. 1364 func (bc *BlockChain) SubscribeRemovedLogsEvent(ch chan<- RemovedLogsEvent) event.Subscription { 1365 return bc.scope.Track(bc.rmLogsFeed.Subscribe(ch)) 1366 } 1367 1368 // SubscribeChainEvent registers a subscription of ChainEvent. 1369 func (bc *BlockChain) SubscribeChainEvent(ch chan<- ChainEvent) event.Subscription { 1370 return bc.scope.Track(bc.chainFeed.Subscribe(ch)) 1371 } 1372 1373 // SubscribeChainHeadEvent registers a subscription of ChainHeadEvent. 1374 func (bc *BlockChain) SubscribeChainHeadEvent(ch chan<- ChainHeadEvent) event.Subscription { 1375 return bc.scope.Track(bc.chainHeadFeed.Subscribe(ch)) 1376 } 1377 1378 // SubscribeChainSideEvent registers a subscription of ChainSideEvent. 1379 func (bc *BlockChain) SubscribeChainSideEvent(ch chan<- ChainSideEvent) event.Subscription { 1380 return bc.scope.Track(bc.chainSideFeed.Subscribe(ch)) 1381 } 1382 1383 // SubscribeLogsEvent registers a subscription of []*types.Log. 1384 func (bc *BlockChain) SubscribeLogsEvent(ch chan<- []*types.Log) event.Subscription { 1385 return bc.scope.Track(bc.logsFeed.Subscribe(ch)) 1386 }