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