blockchain.go 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329
  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. // Package core implements the Ethereum consensus protocol.
  17. package core
  18. import (
  19. "errors"
  20. "fmt"
  21. "io"
  22. "math/big"
  23. mrand "math/rand"
  24. "runtime"
  25. "sync"
  26. "sync/atomic"
  27. "time"
  28. "github.com/ethereum/go-ethereum/common"
  29. "github.com/ethereum/go-ethereum/core/state"
  30. "github.com/ethereum/go-ethereum/core/types"
  31. "github.com/ethereum/go-ethereum/core/vm"
  32. "github.com/ethereum/go-ethereum/crypto"
  33. "github.com/ethereum/go-ethereum/ethdb"
  34. "github.com/ethereum/go-ethereum/event"
  35. "github.com/ethereum/go-ethereum/logger"
  36. "github.com/ethereum/go-ethereum/logger/glog"
  37. "github.com/ethereum/go-ethereum/metrics"
  38. "github.com/ethereum/go-ethereum/params"
  39. "github.com/ethereum/go-ethereum/pow"
  40. "github.com/ethereum/go-ethereum/rlp"
  41. "github.com/ethereum/go-ethereum/trie"
  42. "github.com/hashicorp/golang-lru"
  43. )
  44. var (
  45. chainlogger = logger.NewLogger("CHAIN")
  46. jsonlogger = logger.NewJsonLogger()
  47. blockInsertTimer = metrics.NewTimer("chain/inserts")
  48. ErrNoGenesis = errors.New("Genesis not found in chain")
  49. )
  50. const (
  51. bodyCacheLimit = 256
  52. blockCacheLimit = 256
  53. maxFutureBlocks = 256
  54. maxTimeFutureBlocks = 30
  55. // must be bumped when consensus algorithm is changed, this forces the upgradedb
  56. // command to be run (forces the blocks to be imported again using the new algorithm)
  57. BlockChainVersion = 3
  58. )
  59. // BlockChain represents the canonical chain given a database with a genesis
  60. // block. The Blockchain manages chain imports, reverts, chain reorganisations.
  61. //
  62. // Importing blocks in to the block chain happens according to the set of rules
  63. // defined by the two stage Validator. Processing of blocks is done using the
  64. // Processor which processes the included transaction. The validation of the state
  65. // is done in the second part of the Validator. Failing results in aborting of
  66. // the import.
  67. //
  68. // The BlockChain also helps in returning blocks from **any** chain included
  69. // in the database as well as blocks that represents the canonical chain. It's
  70. // important to note that GetBlock can return any block and does not need to be
  71. // included in the canonical one where as GetBlockByNumber always represents the
  72. // canonical chain.
  73. type BlockChain struct {
  74. config *params.ChainConfig // chain & network configuration
  75. hc *HeaderChain
  76. chainDb ethdb.Database
  77. eventMux *event.TypeMux
  78. genesisBlock *types.Block
  79. mu sync.RWMutex // global mutex for locking chain operations
  80. chainmu sync.RWMutex // blockchain insertion lock
  81. procmu sync.RWMutex // block processor lock
  82. checkpoint int // checkpoint counts towards the new checkpoint
  83. currentBlock *types.Block // Current head of the block chain
  84. currentFastBlock *types.Block // Current head of the fast-sync chain (may be above the block chain!)
  85. stateCache *state.StateDB // State database to reuse between imports (contains state cache)
  86. bodyCache *lru.Cache // Cache for the most recent block bodies
  87. bodyRLPCache *lru.Cache // Cache for the most recent block bodies in RLP encoded format
  88. blockCache *lru.Cache // Cache for the most recent entire blocks
  89. futureBlocks *lru.Cache // future blocks are blocks added for later processing
  90. quit chan struct{} // blockchain quit channel
  91. running int32 // running must be called atomically
  92. // procInterrupt must be atomically called
  93. procInterrupt int32 // interrupt signaler for block processing
  94. wg sync.WaitGroup // chain processing wait group for shutting down
  95. pow pow.PoW
  96. processor Processor // block processor interface
  97. validator Validator // block and state validator interface
  98. }
  99. // NewBlockChain returns a fully initialised block chain using information
  100. // available in the database. It initialiser the default Ethereum Validator and
  101. // Processor.
  102. func NewBlockChain(chainDb ethdb.Database, config *params.ChainConfig, pow pow.PoW, mux *event.TypeMux) (*BlockChain, error) {
  103. bodyCache, _ := lru.New(bodyCacheLimit)
  104. bodyRLPCache, _ := lru.New(bodyCacheLimit)
  105. blockCache, _ := lru.New(blockCacheLimit)
  106. futureBlocks, _ := lru.New(maxFutureBlocks)
  107. bc := &BlockChain{
  108. config: config,
  109. chainDb: chainDb,
  110. eventMux: mux,
  111. quit: make(chan struct{}),
  112. bodyCache: bodyCache,
  113. bodyRLPCache: bodyRLPCache,
  114. blockCache: blockCache,
  115. futureBlocks: futureBlocks,
  116. pow: pow,
  117. }
  118. bc.SetValidator(NewBlockValidator(config, bc, pow))
  119. bc.SetProcessor(NewStateProcessor(config, bc))
  120. gv := func() HeaderValidator { return bc.Validator() }
  121. var err error
  122. bc.hc, err = NewHeaderChain(chainDb, config, gv, bc.getProcInterrupt)
  123. if err != nil {
  124. return nil, err
  125. }
  126. bc.genesisBlock = bc.GetBlockByNumber(0)
  127. if bc.genesisBlock == nil {
  128. return nil, ErrNoGenesis
  129. }
  130. if err := bc.loadLastState(); err != nil {
  131. return nil, err
  132. }
  133. // Check the current state of the block hashes and make sure that we do not have any of the bad blocks in our chain
  134. for hash, _ := range BadHashes {
  135. if header := bc.GetHeaderByHash(hash); header != nil {
  136. glog.V(logger.Error).Infof("Found bad hash, rewinding chain to block #%d [%x…]", header.Number, header.ParentHash[:4])
  137. bc.SetHead(header.Number.Uint64() - 1)
  138. glog.V(logger.Error).Infoln("Chain rewind was successful, resuming normal operation")
  139. }
  140. }
  141. // Take ownership of this particular state
  142. go bc.update()
  143. return bc, nil
  144. }
  145. func (self *BlockChain) getProcInterrupt() bool {
  146. return atomic.LoadInt32(&self.procInterrupt) == 1
  147. }
  148. // loadLastState loads the last known chain state from the database. This method
  149. // assumes that the chain manager mutex is held.
  150. func (self *BlockChain) loadLastState() error {
  151. // Restore the last known head block
  152. head := GetHeadBlockHash(self.chainDb)
  153. if head == (common.Hash{}) {
  154. // Corrupt or empty database, init from scratch
  155. self.Reset()
  156. } else {
  157. if block := self.GetBlockByHash(head); block != nil {
  158. // Block found, set as the current head
  159. self.currentBlock = block
  160. } else {
  161. // Corrupt or empty database, init from scratch
  162. self.Reset()
  163. }
  164. }
  165. // Restore the last known head header
  166. currentHeader := self.currentBlock.Header()
  167. if head := GetHeadHeaderHash(self.chainDb); head != (common.Hash{}) {
  168. if header := self.GetHeaderByHash(head); header != nil {
  169. currentHeader = header
  170. }
  171. }
  172. self.hc.SetCurrentHeader(currentHeader)
  173. // Restore the last known head fast block
  174. self.currentFastBlock = self.currentBlock
  175. if head := GetHeadFastBlockHash(self.chainDb); head != (common.Hash{}) {
  176. if block := self.GetBlockByHash(head); block != nil {
  177. self.currentFastBlock = block
  178. }
  179. }
  180. // Initialize a statedb cache to ensure singleton account bloom filter generation
  181. statedb, err := state.New(self.currentBlock.Root(), self.chainDb)
  182. if err != nil {
  183. return err
  184. }
  185. self.stateCache = statedb
  186. self.stateCache.GetAccount(common.Address{})
  187. // Issue a status log for the user
  188. headerTd := self.GetTd(currentHeader.Hash(), currentHeader.Number.Uint64())
  189. blockTd := self.GetTd(self.currentBlock.Hash(), self.currentBlock.NumberU64())
  190. fastTd := self.GetTd(self.currentFastBlock.Hash(), self.currentFastBlock.NumberU64())
  191. glog.V(logger.Info).Infof("Last header: #%d [%x…] TD=%v", currentHeader.Number, currentHeader.Hash().Bytes()[:4], headerTd)
  192. glog.V(logger.Info).Infof("Last block: #%d [%x…] TD=%v", self.currentBlock.Number(), self.currentBlock.Hash().Bytes()[:4], blockTd)
  193. glog.V(logger.Info).Infof("Fast block: #%d [%x…] TD=%v", self.currentFastBlock.Number(), self.currentFastBlock.Hash().Bytes()[:4], fastTd)
  194. return nil
  195. }
  196. // SetHead rewinds the local chain to a new head. In the case of headers, everything
  197. // above the new head will be deleted and the new one set. In the case of blocks
  198. // though, the head may be further rewound if block bodies are missing (non-archive
  199. // nodes after a fast sync).
  200. func (bc *BlockChain) SetHead(head uint64) {
  201. bc.mu.Lock()
  202. defer bc.mu.Unlock()
  203. delFn := func(hash common.Hash, num uint64) {
  204. DeleteBody(bc.chainDb, hash, num)
  205. }
  206. bc.hc.SetHead(head, delFn)
  207. // Clear out any stale content from the caches
  208. bc.bodyCache.Purge()
  209. bc.bodyRLPCache.Purge()
  210. bc.blockCache.Purge()
  211. bc.futureBlocks.Purge()
  212. // Update all computed fields to the new head
  213. currentHeader := bc.hc.CurrentHeader()
  214. if bc.currentBlock != nil && currentHeader.Number.Uint64() < bc.currentBlock.NumberU64() {
  215. bc.currentBlock = bc.GetBlock(currentHeader.Hash(), currentHeader.Number.Uint64())
  216. }
  217. if bc.currentFastBlock != nil && currentHeader.Number.Uint64() < bc.currentFastBlock.NumberU64() {
  218. bc.currentFastBlock = bc.GetBlock(currentHeader.Hash(), currentHeader.Number.Uint64())
  219. }
  220. if bc.currentBlock == nil {
  221. bc.currentBlock = bc.genesisBlock
  222. }
  223. if bc.currentFastBlock == nil {
  224. bc.currentFastBlock = bc.genesisBlock
  225. }
  226. if err := WriteHeadBlockHash(bc.chainDb, bc.currentBlock.Hash()); err != nil {
  227. glog.Fatalf("failed to reset head block hash: %v", err)
  228. }
  229. if err := WriteHeadFastBlockHash(bc.chainDb, bc.currentFastBlock.Hash()); err != nil {
  230. glog.Fatalf("failed to reset head fast block hash: %v", err)
  231. }
  232. bc.loadLastState()
  233. }
  234. // FastSyncCommitHead sets the current head block to the one defined by the hash
  235. // irrelevant what the chain contents were prior.
  236. func (self *BlockChain) FastSyncCommitHead(hash common.Hash) error {
  237. // Make sure that both the block as well at its state trie exists
  238. block := self.GetBlockByHash(hash)
  239. if block == nil {
  240. return fmt.Errorf("non existent block [%x…]", hash[:4])
  241. }
  242. if _, err := trie.NewSecure(block.Root(), self.chainDb, 0); err != nil {
  243. return err
  244. }
  245. // If all checks out, manually set the head block
  246. self.mu.Lock()
  247. self.currentBlock = block
  248. self.mu.Unlock()
  249. glog.V(logger.Info).Infof("committed block #%d [%x…] as new head", block.Number(), hash[:4])
  250. return nil
  251. }
  252. // GasLimit returns the gas limit of the current HEAD block.
  253. func (self *BlockChain) GasLimit() *big.Int {
  254. self.mu.RLock()
  255. defer self.mu.RUnlock()
  256. return self.currentBlock.GasLimit()
  257. }
  258. // LastBlockHash return the hash of the HEAD block.
  259. func (self *BlockChain) LastBlockHash() common.Hash {
  260. self.mu.RLock()
  261. defer self.mu.RUnlock()
  262. return self.currentBlock.Hash()
  263. }
  264. // CurrentBlock retrieves the current head block of the canonical chain. The
  265. // block is retrieved from the blockchain's internal cache.
  266. func (self *BlockChain) CurrentBlock() *types.Block {
  267. self.mu.RLock()
  268. defer self.mu.RUnlock()
  269. return self.currentBlock
  270. }
  271. // CurrentFastBlock retrieves the current fast-sync head block of the canonical
  272. // chain. The block is retrieved from the blockchain's internal cache.
  273. func (self *BlockChain) CurrentFastBlock() *types.Block {
  274. self.mu.RLock()
  275. defer self.mu.RUnlock()
  276. return self.currentFastBlock
  277. }
  278. // Status returns status information about the current chain such as the HEAD Td,
  279. // the HEAD hash and the hash of the genesis block.
  280. func (self *BlockChain) Status() (td *big.Int, currentBlock common.Hash, genesisBlock common.Hash) {
  281. self.mu.RLock()
  282. defer self.mu.RUnlock()
  283. return self.GetTd(self.currentBlock.Hash(), self.currentBlock.NumberU64()), self.currentBlock.Hash(), self.genesisBlock.Hash()
  284. }
  285. // SetProcessor sets the processor required for making state modifications.
  286. func (self *BlockChain) SetProcessor(processor Processor) {
  287. self.procmu.Lock()
  288. defer self.procmu.Unlock()
  289. self.processor = processor
  290. }
  291. // SetValidator sets the validator which is used to validate incoming blocks.
  292. func (self *BlockChain) SetValidator(validator Validator) {
  293. self.procmu.Lock()
  294. defer self.procmu.Unlock()
  295. self.validator = validator
  296. }
  297. // Validator returns the current validator.
  298. func (self *BlockChain) Validator() Validator {
  299. self.procmu.RLock()
  300. defer self.procmu.RUnlock()
  301. return self.validator
  302. }
  303. // Processor returns the current processor.
  304. func (self *BlockChain) Processor() Processor {
  305. self.procmu.RLock()
  306. defer self.procmu.RUnlock()
  307. return self.processor
  308. }
  309. // AuxValidator returns the auxiliary validator (Proof of work atm)
  310. func (self *BlockChain) AuxValidator() pow.PoW { return self.pow }
  311. // State returns a new mutable state based on the current HEAD block.
  312. func (self *BlockChain) State() (*state.StateDB, error) {
  313. return self.StateAt(self.CurrentBlock().Root())
  314. }
  315. // StateAt returns a new mutable state based on a particular point in time.
  316. func (self *BlockChain) StateAt(root common.Hash) (*state.StateDB, error) {
  317. return self.stateCache.New(root)
  318. }
  319. // Reset purges the entire blockchain, restoring it to its genesis state.
  320. func (bc *BlockChain) Reset() {
  321. bc.ResetWithGenesisBlock(bc.genesisBlock)
  322. }
  323. // ResetWithGenesisBlock purges the entire blockchain, restoring it to the
  324. // specified genesis state.
  325. func (bc *BlockChain) ResetWithGenesisBlock(genesis *types.Block) {
  326. // Dump the entire block chain and purge the caches
  327. bc.SetHead(0)
  328. bc.mu.Lock()
  329. defer bc.mu.Unlock()
  330. // Prepare the genesis block and reinitialise the chain
  331. if err := bc.hc.WriteTd(genesis.Hash(), genesis.NumberU64(), genesis.Difficulty()); err != nil {
  332. glog.Fatalf("failed to write genesis block TD: %v", err)
  333. }
  334. if err := WriteBlock(bc.chainDb, genesis); err != nil {
  335. glog.Fatalf("failed to write genesis block: %v", err)
  336. }
  337. bc.genesisBlock = genesis
  338. bc.insert(bc.genesisBlock)
  339. bc.currentBlock = bc.genesisBlock
  340. bc.hc.SetGenesis(bc.genesisBlock.Header())
  341. bc.hc.SetCurrentHeader(bc.genesisBlock.Header())
  342. bc.currentFastBlock = bc.genesisBlock
  343. }
  344. // Export writes the active chain to the given writer.
  345. func (self *BlockChain) Export(w io.Writer) error {
  346. if err := self.ExportN(w, uint64(0), self.currentBlock.NumberU64()); err != nil {
  347. return err
  348. }
  349. return nil
  350. }
  351. // ExportN writes a subset of the active chain to the given writer.
  352. func (self *BlockChain) ExportN(w io.Writer, first uint64, last uint64) error {
  353. self.mu.RLock()
  354. defer self.mu.RUnlock()
  355. if first > last {
  356. return fmt.Errorf("export failed: first (%d) is greater than last (%d)", first, last)
  357. }
  358. glog.V(logger.Info).Infof("exporting %d blocks...\n", last-first+1)
  359. for nr := first; nr <= last; nr++ {
  360. block := self.GetBlockByNumber(nr)
  361. if block == nil {
  362. return fmt.Errorf("export failed on #%d: not found", nr)
  363. }
  364. if err := block.EncodeRLP(w); err != nil {
  365. return err
  366. }
  367. }
  368. return nil
  369. }
  370. // insert injects a new head block into the current block chain. This method
  371. // assumes that the block is indeed a true head. It will also reset the head
  372. // header and the head fast sync block to this very same block if they are older
  373. // or if they are on a different side chain.
  374. //
  375. // Note, this function assumes that the `mu` mutex is held!
  376. func (bc *BlockChain) insert(block *types.Block) {
  377. // If the block is on a side chain or an unknown one, force other heads onto it too
  378. updateHeads := GetCanonicalHash(bc.chainDb, block.NumberU64()) != block.Hash()
  379. // Add the block to the canonical chain number scheme and mark as the head
  380. if err := WriteCanonicalHash(bc.chainDb, block.Hash(), block.NumberU64()); err != nil {
  381. glog.Fatalf("failed to insert block number: %v", err)
  382. }
  383. if err := WriteHeadBlockHash(bc.chainDb, block.Hash()); err != nil {
  384. glog.Fatalf("failed to insert head block hash: %v", err)
  385. }
  386. bc.currentBlock = block
  387. // If the block is better than out head or is on a different chain, force update heads
  388. if updateHeads {
  389. bc.hc.SetCurrentHeader(block.Header())
  390. if err := WriteHeadFastBlockHash(bc.chainDb, block.Hash()); err != nil {
  391. glog.Fatalf("failed to insert head fast block hash: %v", err)
  392. }
  393. bc.currentFastBlock = block
  394. }
  395. }
  396. // Accessors
  397. func (bc *BlockChain) Genesis() *types.Block {
  398. return bc.genesisBlock
  399. }
  400. // GetBody retrieves a block body (transactions and uncles) from the database by
  401. // hash, caching it if found.
  402. func (self *BlockChain) GetBody(hash common.Hash) *types.Body {
  403. // Short circuit if the body's already in the cache, retrieve otherwise
  404. if cached, ok := self.bodyCache.Get(hash); ok {
  405. body := cached.(*types.Body)
  406. return body
  407. }
  408. body := GetBody(self.chainDb, hash, self.hc.GetBlockNumber(hash))
  409. if body == nil {
  410. return nil
  411. }
  412. // Cache the found body for next time and return
  413. self.bodyCache.Add(hash, body)
  414. return body
  415. }
  416. // GetBodyRLP retrieves a block body in RLP encoding from the database by hash,
  417. // caching it if found.
  418. func (self *BlockChain) GetBodyRLP(hash common.Hash) rlp.RawValue {
  419. // Short circuit if the body's already in the cache, retrieve otherwise
  420. if cached, ok := self.bodyRLPCache.Get(hash); ok {
  421. return cached.(rlp.RawValue)
  422. }
  423. body := GetBodyRLP(self.chainDb, hash, self.hc.GetBlockNumber(hash))
  424. if len(body) == 0 {
  425. return nil
  426. }
  427. // Cache the found body for next time and return
  428. self.bodyRLPCache.Add(hash, body)
  429. return body
  430. }
  431. // HasBlock checks if a block is fully present in the database or not, caching
  432. // it if present.
  433. func (bc *BlockChain) HasBlock(hash common.Hash) bool {
  434. return bc.GetBlockByHash(hash) != nil
  435. }
  436. // HasBlockAndState checks if a block and associated state trie is fully present
  437. // in the database or not, caching it if present.
  438. func (bc *BlockChain) HasBlockAndState(hash common.Hash) bool {
  439. // Check first that the block itself is known
  440. block := bc.GetBlockByHash(hash)
  441. if block == nil {
  442. return false
  443. }
  444. // Ensure the associated state is also present
  445. _, err := state.New(block.Root(), bc.chainDb)
  446. return err == nil
  447. }
  448. // GetBlock retrieves a block from the database by hash and number,
  449. // caching it if found.
  450. func (self *BlockChain) GetBlock(hash common.Hash, number uint64) *types.Block {
  451. // Short circuit if the block's already in the cache, retrieve otherwise
  452. if block, ok := self.blockCache.Get(hash); ok {
  453. return block.(*types.Block)
  454. }
  455. block := GetBlock(self.chainDb, hash, number)
  456. if block == nil {
  457. return nil
  458. }
  459. // Cache the found block for next time and return
  460. self.blockCache.Add(block.Hash(), block)
  461. return block
  462. }
  463. // GetBlockByHash retrieves a block from the database by hash, caching it if found.
  464. func (self *BlockChain) GetBlockByHash(hash common.Hash) *types.Block {
  465. return self.GetBlock(hash, self.hc.GetBlockNumber(hash))
  466. }
  467. // GetBlockByNumber retrieves a block from the database by number, caching it
  468. // (associated with its hash) if found.
  469. func (self *BlockChain) GetBlockByNumber(number uint64) *types.Block {
  470. hash := GetCanonicalHash(self.chainDb, number)
  471. if hash == (common.Hash{}) {
  472. return nil
  473. }
  474. return self.GetBlock(hash, number)
  475. }
  476. // [deprecated by eth/62]
  477. // GetBlocksFromHash returns the block corresponding to hash and up to n-1 ancestors.
  478. func (self *BlockChain) GetBlocksFromHash(hash common.Hash, n int) (blocks []*types.Block) {
  479. number := self.hc.GetBlockNumber(hash)
  480. for i := 0; i < n; i++ {
  481. block := self.GetBlock(hash, number)
  482. if block == nil {
  483. break
  484. }
  485. blocks = append(blocks, block)
  486. hash = block.ParentHash()
  487. number--
  488. }
  489. return
  490. }
  491. // GetUnclesInChain retrieves all the uncles from a given block backwards until
  492. // a specific distance is reached.
  493. func (self *BlockChain) GetUnclesInChain(block *types.Block, length int) []*types.Header {
  494. uncles := []*types.Header{}
  495. for i := 0; block != nil && i < length; i++ {
  496. uncles = append(uncles, block.Uncles()...)
  497. block = self.GetBlock(block.ParentHash(), block.NumberU64()-1)
  498. }
  499. return uncles
  500. }
  501. // Stop stops the blockchain service. If any imports are currently in progress
  502. // it will abort them using the procInterrupt.
  503. func (bc *BlockChain) Stop() {
  504. if !atomic.CompareAndSwapInt32(&bc.running, 0, 1) {
  505. return
  506. }
  507. close(bc.quit)
  508. atomic.StoreInt32(&bc.procInterrupt, 1)
  509. bc.wg.Wait()
  510. glog.V(logger.Info).Infoln("Chain manager stopped")
  511. }
  512. func (self *BlockChain) procFutureBlocks() {
  513. blocks := make([]*types.Block, 0, self.futureBlocks.Len())
  514. for _, hash := range self.futureBlocks.Keys() {
  515. if block, exist := self.futureBlocks.Get(hash); exist {
  516. blocks = append(blocks, block.(*types.Block))
  517. }
  518. }
  519. if len(blocks) > 0 {
  520. types.BlockBy(types.Number).Sort(blocks)
  521. self.InsertChain(blocks)
  522. }
  523. }
  524. type WriteStatus byte
  525. const (
  526. NonStatTy WriteStatus = iota
  527. CanonStatTy
  528. SplitStatTy
  529. SideStatTy
  530. )
  531. // Rollback is designed to remove a chain of links from the database that aren't
  532. // certain enough to be valid.
  533. func (self *BlockChain) Rollback(chain []common.Hash) {
  534. self.mu.Lock()
  535. defer self.mu.Unlock()
  536. for i := len(chain) - 1; i >= 0; i-- {
  537. hash := chain[i]
  538. currentHeader := self.hc.CurrentHeader()
  539. if currentHeader.Hash() == hash {
  540. self.hc.SetCurrentHeader(self.GetHeader(currentHeader.ParentHash, currentHeader.Number.Uint64()-1))
  541. }
  542. if self.currentFastBlock.Hash() == hash {
  543. self.currentFastBlock = self.GetBlock(self.currentFastBlock.ParentHash(), self.currentFastBlock.NumberU64()-1)
  544. WriteHeadFastBlockHash(self.chainDb, self.currentFastBlock.Hash())
  545. }
  546. if self.currentBlock.Hash() == hash {
  547. self.currentBlock = self.GetBlock(self.currentBlock.ParentHash(), self.currentBlock.NumberU64()-1)
  548. WriteHeadBlockHash(self.chainDb, self.currentBlock.Hash())
  549. }
  550. }
  551. }
  552. // SetReceiptsData computes all the non-consensus fields of the receipts
  553. func SetReceiptsData(config *params.ChainConfig, block *types.Block, receipts types.Receipts) {
  554. signer := types.MakeSigner(config, block.Number())
  555. transactions, logIndex := block.Transactions(), uint(0)
  556. for j := 0; j < len(receipts); j++ {
  557. // The transaction hash can be retrieved from the transaction itself
  558. receipts[j].TxHash = transactions[j].Hash()
  559. tx, _ := transactions[j].AsMessage(signer)
  560. // The contract address can be derived from the transaction itself
  561. if MessageCreatesContract(tx) {
  562. receipts[j].ContractAddress = crypto.CreateAddress(tx.From(), tx.Nonce())
  563. }
  564. // The used gas can be calculated based on previous receipts
  565. if j == 0 {
  566. receipts[j].GasUsed = new(big.Int).Set(receipts[j].CumulativeGasUsed)
  567. } else {
  568. receipts[j].GasUsed = new(big.Int).Sub(receipts[j].CumulativeGasUsed, receipts[j-1].CumulativeGasUsed)
  569. }
  570. // The derived log fields can simply be set from the block and transaction
  571. for k := 0; k < len(receipts[j].Logs); k++ {
  572. receipts[j].Logs[k].BlockNumber = block.NumberU64()
  573. receipts[j].Logs[k].BlockHash = block.Hash()
  574. receipts[j].Logs[k].TxHash = receipts[j].TxHash
  575. receipts[j].Logs[k].TxIndex = uint(j)
  576. receipts[j].Logs[k].Index = logIndex
  577. logIndex++
  578. }
  579. }
  580. }
  581. // InsertReceiptChain attempts to complete an already existing header chain with
  582. // transaction and receipt data.
  583. // XXX should this be moved to the test?
  584. func (self *BlockChain) InsertReceiptChain(blockChain types.Blocks, receiptChain []types.Receipts) (int, error) {
  585. self.wg.Add(1)
  586. defer self.wg.Done()
  587. // Collect some import statistics to report on
  588. stats := struct{ processed, ignored int32 }{}
  589. start := time.Now()
  590. // Create the block importing task queue and worker functions
  591. tasks := make(chan int, len(blockChain))
  592. for i := 0; i < len(blockChain) && i < len(receiptChain); i++ {
  593. tasks <- i
  594. }
  595. close(tasks)
  596. errs, failed := make([]error, len(tasks)), int32(0)
  597. process := func(worker int) {
  598. for index := range tasks {
  599. block, receipts := blockChain[index], receiptChain[index]
  600. // Short circuit insertion if shutting down or processing failed
  601. if atomic.LoadInt32(&self.procInterrupt) == 1 {
  602. return
  603. }
  604. if atomic.LoadInt32(&failed) > 0 {
  605. return
  606. }
  607. // Short circuit if the owner header is unknown
  608. if !self.HasHeader(block.Hash()) {
  609. errs[index] = fmt.Errorf("containing header #%d [%x…] unknown", block.Number(), block.Hash().Bytes()[:4])
  610. atomic.AddInt32(&failed, 1)
  611. return
  612. }
  613. // Skip if the entire data is already known
  614. if self.HasBlock(block.Hash()) {
  615. atomic.AddInt32(&stats.ignored, 1)
  616. continue
  617. }
  618. // Compute all the non-consensus fields of the receipts
  619. SetReceiptsData(self.config, block, receipts)
  620. // Write all the data out into the database
  621. if err := WriteBody(self.chainDb, block.Hash(), block.NumberU64(), block.Body()); err != nil {
  622. errs[index] = fmt.Errorf("failed to write block body: %v", err)
  623. atomic.AddInt32(&failed, 1)
  624. glog.Fatal(errs[index])
  625. return
  626. }
  627. if err := WriteBlockReceipts(self.chainDb, block.Hash(), block.NumberU64(), receipts); err != nil {
  628. errs[index] = fmt.Errorf("failed to write block receipts: %v", err)
  629. atomic.AddInt32(&failed, 1)
  630. glog.Fatal(errs[index])
  631. return
  632. }
  633. if err := WriteMipmapBloom(self.chainDb, block.NumberU64(), receipts); err != nil {
  634. errs[index] = fmt.Errorf("failed to write log blooms: %v", err)
  635. atomic.AddInt32(&failed, 1)
  636. glog.Fatal(errs[index])
  637. return
  638. }
  639. if err := WriteTransactions(self.chainDb, block); err != nil {
  640. errs[index] = fmt.Errorf("failed to write individual transactions: %v", err)
  641. atomic.AddInt32(&failed, 1)
  642. glog.Fatal(errs[index])
  643. return
  644. }
  645. if err := WriteReceipts(self.chainDb, receipts); err != nil {
  646. errs[index] = fmt.Errorf("failed to write individual receipts: %v", err)
  647. atomic.AddInt32(&failed, 1)
  648. glog.Fatal(errs[index])
  649. return
  650. }
  651. atomic.AddInt32(&stats.processed, 1)
  652. }
  653. }
  654. // Start as many worker threads as goroutines allowed
  655. pending := new(sync.WaitGroup)
  656. for i := 0; i < runtime.GOMAXPROCS(0); i++ {
  657. pending.Add(1)
  658. go func(id int) {
  659. defer pending.Done()
  660. process(id)
  661. }(i)
  662. }
  663. pending.Wait()
  664. // If anything failed, report
  665. if failed > 0 {
  666. for i, err := range errs {
  667. if err != nil {
  668. return i, err
  669. }
  670. }
  671. }
  672. if atomic.LoadInt32(&self.procInterrupt) == 1 {
  673. glog.V(logger.Debug).Infoln("premature abort during receipt chain processing")
  674. return 0, nil
  675. }
  676. // Update the head fast sync block if better
  677. self.mu.Lock()
  678. head := blockChain[len(errs)-1]
  679. if self.GetTd(self.currentFastBlock.Hash(), self.currentFastBlock.NumberU64()).Cmp(self.GetTd(head.Hash(), head.NumberU64())) < 0 {
  680. if err := WriteHeadFastBlockHash(self.chainDb, head.Hash()); err != nil {
  681. glog.Fatalf("failed to update head fast block hash: %v", err)
  682. }
  683. self.currentFastBlock = head
  684. }
  685. self.mu.Unlock()
  686. // Report some public statistics so the user has a clue what's going on
  687. first, last := blockChain[0], blockChain[len(blockChain)-1]
  688. ignored := ""
  689. if stats.ignored > 0 {
  690. ignored = fmt.Sprintf(" (%d ignored)", stats.ignored)
  691. }
  692. glog.V(logger.Info).Infof("imported %d receipts in %9v. #%d [%x… / %x…]%s", stats.processed, common.PrettyDuration(time.Since(start)), last.Number(), first.Hash().Bytes()[:4], last.Hash().Bytes()[:4], ignored)
  693. return 0, nil
  694. }
  695. // WriteBlock writes the block to the chain.
  696. func (self *BlockChain) WriteBlock(block *types.Block) (status WriteStatus, err error) {
  697. self.wg.Add(1)
  698. defer self.wg.Done()
  699. // Calculate the total difficulty of the block
  700. ptd := self.GetTd(block.ParentHash(), block.NumberU64()-1)
  701. if ptd == nil {
  702. return NonStatTy, ParentError(block.ParentHash())
  703. }
  704. // Make sure no inconsistent state is leaked during insertion
  705. self.mu.Lock()
  706. defer self.mu.Unlock()
  707. localTd := self.GetTd(self.currentBlock.Hash(), self.currentBlock.NumberU64())
  708. externTd := new(big.Int).Add(block.Difficulty(), ptd)
  709. // Irrelevant of the canonical status, write the block itself to the database
  710. if err := self.hc.WriteTd(block.Hash(), block.NumberU64(), externTd); err != nil {
  711. glog.Fatalf("failed to write block total difficulty: %v", err)
  712. }
  713. if err := WriteBlock(self.chainDb, block); err != nil {
  714. glog.Fatalf("failed to write block contents: %v", err)
  715. }
  716. // If the total difficulty is higher than our known, add it to the canonical chain
  717. // Second clause in the if statement reduces the vulnerability to selfish mining.
  718. // Please refer to http://www.cs.cornell.edu/~ie53/publications/btcProcFC.pdf
  719. if externTd.Cmp(localTd) > 0 || (externTd.Cmp(localTd) == 0 && mrand.Float64() < 0.5) {
  720. // Reorganise the chain if the parent is not the head block
  721. if block.ParentHash() != self.currentBlock.Hash() {
  722. if err := self.reorg(self.currentBlock, block); err != nil {
  723. return NonStatTy, err
  724. }
  725. }
  726. self.insert(block) // Insert the block as the new head of the chain
  727. status = CanonStatTy
  728. } else {
  729. status = SideStatTy
  730. }
  731. self.futureBlocks.Remove(block.Hash())
  732. return
  733. }
  734. // InsertChain will attempt to insert the given chain in to the canonical chain or, otherwise, create a fork. It an error is returned
  735. // it will return the index number of the failing block as well an error describing what went wrong (for possible errors see core/errors.go).
  736. func (self *BlockChain) InsertChain(chain types.Blocks) (int, error) {
  737. self.wg.Add(1)
  738. defer self.wg.Done()
  739. self.chainmu.Lock()
  740. defer self.chainmu.Unlock()
  741. // A queued approach to delivering events. This is generally
  742. // faster than direct delivery and requires much less mutex
  743. // acquiring.
  744. var (
  745. stats = insertStats{startTime: time.Now()}
  746. events = make([]interface{}, 0, len(chain))
  747. coalescedLogs vm.Logs
  748. nonceChecked = make([]bool, len(chain))
  749. )
  750. // Start the parallel nonce verifier.
  751. nonceAbort, nonceResults := verifyNoncesFromBlocks(self.pow, chain)
  752. defer close(nonceAbort)
  753. for i, block := range chain {
  754. if atomic.LoadInt32(&self.procInterrupt) == 1 {
  755. glog.V(logger.Debug).Infoln("Premature abort during block chain processing")
  756. break
  757. }
  758. bstart := time.Now()
  759. // Wait for block i's nonce to be verified before processing
  760. // its state transition.
  761. for !nonceChecked[i] {
  762. r := <-nonceResults
  763. nonceChecked[r.index] = true
  764. if !r.valid {
  765. block := chain[r.index]
  766. return r.index, &BlockNonceErr{Hash: block.Hash(), Number: block.Number(), Nonce: block.Nonce()}
  767. }
  768. }
  769. if BadHashes[block.Hash()] {
  770. err := BadHashError(block.Hash())
  771. self.reportBlock(block, nil, err)
  772. return i, err
  773. }
  774. // Stage 1 validation of the block using the chain's validator
  775. // interface.
  776. err := self.Validator().ValidateBlock(block)
  777. if err != nil {
  778. if IsKnownBlockErr(err) {
  779. stats.ignored++
  780. continue
  781. }
  782. if err == BlockFutureErr {
  783. // Allow up to MaxFuture second in the future blocks. If this limit
  784. // is exceeded the chain is discarded and processed at a later time
  785. // if given.
  786. max := big.NewInt(time.Now().Unix() + maxTimeFutureBlocks)
  787. if block.Time().Cmp(max) == 1 {
  788. return i, fmt.Errorf("%v: BlockFutureErr, %v > %v", BlockFutureErr, block.Time(), max)
  789. }
  790. self.futureBlocks.Add(block.Hash(), block)
  791. stats.queued++
  792. continue
  793. }
  794. if IsParentErr(err) && self.futureBlocks.Contains(block.ParentHash()) {
  795. self.futureBlocks.Add(block.Hash(), block)
  796. stats.queued++
  797. continue
  798. }
  799. self.reportBlock(block, nil, err)
  800. return i, err
  801. }
  802. // Create a new statedb using the parent block and report an
  803. // error if it fails.
  804. switch {
  805. case i == 0:
  806. err = self.stateCache.Reset(self.GetBlock(block.ParentHash(), block.NumberU64()-1).Root())
  807. default:
  808. err = self.stateCache.Reset(chain[i-1].Root())
  809. }
  810. if err != nil {
  811. self.reportBlock(block, nil, err)
  812. return i, err
  813. }
  814. // Process block using the parent state as reference point.
  815. receipts, logs, usedGas, err := self.processor.Process(block, self.stateCache, vm.Config{})
  816. if err != nil {
  817. self.reportBlock(block, receipts, err)
  818. return i, err
  819. }
  820. // Validate the state using the default validator
  821. err = self.Validator().ValidateState(block, self.GetBlock(block.ParentHash(), block.NumberU64()-1), self.stateCache, receipts, usedGas)
  822. if err != nil {
  823. self.reportBlock(block, receipts, err)
  824. return i, err
  825. }
  826. // Write state changes to database
  827. _, err = self.stateCache.Commit(self.config.IsEIP158(block.Number()))
  828. if err != nil {
  829. return i, err
  830. }
  831. // coalesce logs for later processing
  832. coalescedLogs = append(coalescedLogs, logs...)
  833. if err := WriteBlockReceipts(self.chainDb, block.Hash(), block.NumberU64(), receipts); err != nil {
  834. return i, err
  835. }
  836. // write the block to the chain and get the status
  837. status, err := self.WriteBlock(block)
  838. if err != nil {
  839. return i, err
  840. }
  841. switch status {
  842. case CanonStatTy:
  843. if glog.V(logger.Debug) {
  844. glog.Infof("inserted block #%d [%x…] in %9v: %3d txs %7v gas %d uncles.", block.Number(), block.Hash().Bytes()[0:4], common.PrettyDuration(time.Since(bstart)), len(block.Transactions()), block.GasUsed(), len(block.Uncles()))
  845. }
  846. blockInsertTimer.UpdateSince(bstart)
  847. events = append(events, ChainEvent{block, block.Hash(), logs})
  848. // This puts transactions in a extra db for rpc
  849. if err := WriteTransactions(self.chainDb, block); err != nil {
  850. return i, err
  851. }
  852. // store the receipts
  853. if err := WriteReceipts(self.chainDb, receipts); err != nil {
  854. return i, err
  855. }
  856. // Write map map bloom filters
  857. if err := WriteMipmapBloom(self.chainDb, block.NumberU64(), receipts); err != nil {
  858. return i, err
  859. }
  860. case SideStatTy:
  861. if glog.V(logger.Detail) {
  862. glog.Infof("inserted forked block #%d [%x…] (TD=%v) in %9v: %3d txs %d uncles.", block.Number(), block.Hash().Bytes()[0:4], block.Difficulty(), common.PrettyDuration(time.Since(bstart)), len(block.Transactions()), len(block.Uncles()))
  863. }
  864. blockInsertTimer.UpdateSince(bstart)
  865. events = append(events, ChainSideEvent{block, logs})
  866. case SplitStatTy:
  867. events = append(events, ChainSplitEvent{block, logs})
  868. }
  869. stats.processed++
  870. if glog.V(logger.Info) {
  871. stats.usedGas += usedGas.Uint64()
  872. stats.report(chain, i)
  873. }
  874. }
  875. go self.postChainEvents(events, coalescedLogs)
  876. return 0, nil
  877. }
  878. // insertStats tracks and reports on block insertion.
  879. type insertStats struct {
  880. queued, processed, ignored int
  881. usedGas uint64
  882. lastIndex int
  883. startTime time.Time
  884. }
  885. // statsReportLimit is the time limit during import after which we always print
  886. // out progress. This avoids the user wondering what's going on.
  887. const statsReportLimit = 8 * time.Second
  888. // report prints statistics if some number of blocks have been processed
  889. // or more than a few seconds have passed since the last message.
  890. func (st *insertStats) report(chain []*types.Block, index int) {
  891. // Fetch the timings for the batch
  892. var (
  893. now = time.Now()
  894. elapsed = now.Sub(st.startTime)
  895. )
  896. if elapsed == 0 { // Yes Windows, I'm looking at you
  897. elapsed = 1
  898. }
  899. // If we're at the last block of the batch or report period reached, log
  900. if index == len(chain)-1 || elapsed >= statsReportLimit {
  901. start, end := chain[st.lastIndex], chain[index]
  902. txcount := countTransactions(chain[st.lastIndex : index+1])
  903. extra := ""
  904. if st.queued > 0 || st.ignored > 0 {
  905. extra = fmt.Sprintf(" (%d queued %d ignored)", st.queued, st.ignored)
  906. }
  907. hashes := ""
  908. if st.processed > 1 {
  909. hashes = fmt.Sprintf("%x… / %x…", start.Hash().Bytes()[:4], end.Hash().Bytes()[:4])
  910. } else {
  911. hashes = fmt.Sprintf("%x…", end.Hash().Bytes()[:4])
  912. }
  913. glog.Infof("imported %d blocks, %5d txs (%7.3f Mg) in %9v (%6.3f Mg/s). #%v [%s]%s", st.processed, txcount, float64(st.usedGas)/1000000, common.PrettyDuration(elapsed), float64(st.usedGas)*1000/float64(elapsed), end.Number(), hashes, extra)
  914. *st = insertStats{startTime: now, lastIndex: index}
  915. }
  916. }
  917. func countTransactions(chain []*types.Block) (c int) {
  918. for _, b := range chain {
  919. c += len(b.Transactions())
  920. }
  921. return c
  922. }
  923. // reorgs takes two blocks, an old chain and a new chain and will reconstruct the blocks and inserts them
  924. // to be part of the new canonical chain and accumulates potential missing transactions and post an
  925. // event about them
  926. func (self *BlockChain) reorg(oldBlock, newBlock *types.Block) error {
  927. var (
  928. newChain types.Blocks
  929. oldChain types.Blocks
  930. commonBlock *types.Block
  931. oldStart = oldBlock
  932. newStart = newBlock
  933. deletedTxs types.Transactions
  934. deletedLogs vm.Logs
  935. deletedLogsByHash = make(map[common.Hash]vm.Logs)
  936. // collectLogs collects the logs that were generated during the
  937. // processing of the block that corresponds with the given hash.
  938. // These logs are later announced as deleted.
  939. collectLogs = func(h common.Hash) {
  940. // Coalesce logs
  941. receipts := GetBlockReceipts(self.chainDb, h, self.hc.GetBlockNumber(h))
  942. for _, receipt := range receipts {
  943. deletedLogs = append(deletedLogs, receipt.Logs...)
  944. deletedLogsByHash[h] = receipt.Logs
  945. }
  946. }
  947. )
  948. // first reduce whoever is higher bound
  949. if oldBlock.NumberU64() > newBlock.NumberU64() {
  950. // reduce old chain
  951. for ; oldBlock != nil && oldBlock.NumberU64() != newBlock.NumberU64(); oldBlock = self.GetBlock(oldBlock.ParentHash(), oldBlock.NumberU64()-1) {
  952. oldChain = append(oldChain, oldBlock)
  953. deletedTxs = append(deletedTxs, oldBlock.Transactions()...)
  954. collectLogs(oldBlock.Hash())
  955. }
  956. } else {
  957. // reduce new chain and append new chain blocks for inserting later on
  958. for ; newBlock != nil && newBlock.NumberU64() != oldBlock.NumberU64(); newBlock = self.GetBlock(newBlock.ParentHash(), newBlock.NumberU64()-1) {
  959. newChain = append(newChain, newBlock)
  960. }
  961. }
  962. if oldBlock == nil {
  963. return fmt.Errorf("Invalid old chain")
  964. }
  965. if newBlock == nil {
  966. return fmt.Errorf("Invalid new chain")
  967. }
  968. numSplit := newBlock.Number()
  969. for {
  970. if oldBlock.Hash() == newBlock.Hash() {
  971. commonBlock = oldBlock
  972. break
  973. }
  974. oldChain = append(oldChain, oldBlock)
  975. newChain = append(newChain, newBlock)
  976. deletedTxs = append(deletedTxs, oldBlock.Transactions()...)
  977. collectLogs(oldBlock.Hash())
  978. oldBlock, newBlock = self.GetBlock(oldBlock.ParentHash(), oldBlock.NumberU64()-1), self.GetBlock(newBlock.ParentHash(), newBlock.NumberU64()-1)
  979. if oldBlock == nil {
  980. return fmt.Errorf("Invalid old chain")
  981. }
  982. if newBlock == nil {
  983. return fmt.Errorf("Invalid new chain")
  984. }
  985. }
  986. if glog.V(logger.Debug) {
  987. commonHash := commonBlock.Hash()
  988. glog.Infof("Chain split detected @ %x. Reorganising chain from #%v %x to %x", commonHash[:4], numSplit, oldStart.Hash().Bytes()[:4], newStart.Hash().Bytes()[:4])
  989. }
  990. var addedTxs types.Transactions
  991. // insert blocks. Order does not matter. Last block will be written in ImportChain itself which creates the new head properly
  992. for _, block := range newChain {
  993. // insert the block in the canonical way, re-writing history
  994. self.insert(block)
  995. // write canonical receipts and transactions
  996. if err := WriteTransactions(self.chainDb, block); err != nil {
  997. return err
  998. }
  999. receipts := GetBlockReceipts(self.chainDb, block.Hash(), block.NumberU64())
  1000. // write receipts
  1001. if err := WriteReceipts(self.chainDb, receipts); err != nil {
  1002. return err
  1003. }
  1004. // Write map map bloom filters
  1005. if err := WriteMipmapBloom(self.chainDb, block.NumberU64(), receipts); err != nil {
  1006. return err
  1007. }
  1008. addedTxs = append(addedTxs, block.Transactions()...)
  1009. }
  1010. // calculate the difference between deleted and added transactions
  1011. diff := types.TxDifference(deletedTxs, addedTxs)
  1012. // When transactions get deleted from the database that means the
  1013. // receipts that were created in the fork must also be deleted
  1014. for _, tx := range diff {
  1015. DeleteReceipt(self.chainDb, tx.Hash())
  1016. DeleteTransaction(self.chainDb, tx.Hash())
  1017. }
  1018. // Must be posted in a goroutine because of the transaction pool trying
  1019. // to acquire the chain manager lock
  1020. if len(diff) > 0 {
  1021. go self.eventMux.Post(RemovedTransactionEvent{diff})
  1022. }
  1023. if len(deletedLogs) > 0 {
  1024. go self.eventMux.Post(RemovedLogsEvent{deletedLogs})
  1025. }
  1026. if len(oldChain) > 0 {
  1027. go func() {
  1028. for _, block := range oldChain {
  1029. self.eventMux.Post(ChainSideEvent{Block: block, Logs: deletedLogsByHash[block.Hash()]})
  1030. }
  1031. }()
  1032. }
  1033. return nil
  1034. }
  1035. // postChainEvents iterates over the events generated by a chain insertion and
  1036. // posts them into the event mux.
  1037. func (self *BlockChain) postChainEvents(events []interface{}, logs vm.Logs) {
  1038. // post event logs for further processing
  1039. self.eventMux.Post(logs)
  1040. for _, event := range events {
  1041. if event, ok := event.(ChainEvent); ok {
  1042. // We need some control over the mining operation. Acquiring locks and waiting for the miner to create new block takes too long
  1043. // and in most cases isn't even necessary.
  1044. if self.LastBlockHash() == event.Hash {
  1045. self.eventMux.Post(ChainHeadEvent{event.Block})
  1046. }
  1047. }
  1048. // Fire the insertion events individually too
  1049. self.eventMux.Post(event)
  1050. }
  1051. }
  1052. func (self *BlockChain) update() {
  1053. futureTimer := time.Tick(5 * time.Second)
  1054. for {
  1055. select {
  1056. case <-futureTimer:
  1057. self.procFutureBlocks()
  1058. case <-self.quit:
  1059. return
  1060. }
  1061. }
  1062. }
  1063. // reportBlock logs a bad block error.
  1064. func (bc *BlockChain) reportBlock(block *types.Block, receipts types.Receipts, err error) {
  1065. if glog.V(logger.Error) {
  1066. var receiptString string
  1067. for _, receipt := range receipts {
  1068. receiptString += fmt.Sprintf("\t%v\n", receipt)
  1069. }
  1070. glog.Errorf(`
  1071. ########## BAD BLOCK #########
  1072. Chain config: %v
  1073. Number: %v
  1074. Hash: 0x%x
  1075. %v
  1076. Error: %v
  1077. ##############################
  1078. `, bc.config, block.Number(), block.Hash(), receiptString, err)
  1079. }
  1080. }
  1081. // InsertHeaderChain attempts to insert the given header chain in to the local
  1082. // chain, possibly creating a reorg. If an error is returned, it will return the
  1083. // index number of the failing header as well an error describing what went wrong.
  1084. //
  1085. // The verify parameter can be used to fine tune whether nonce verification
  1086. // should be done or not. The reason behind the optional check is because some
  1087. // of the header retrieval mechanisms already need to verify nonces, as well as
  1088. // because nonces can be verified sparsely, not needing to check each.
  1089. func (self *BlockChain) InsertHeaderChain(chain []*types.Header, checkFreq int) (int, error) {
  1090. // Make sure only one thread manipulates the chain at once
  1091. self.chainmu.Lock()
  1092. defer self.chainmu.Unlock()
  1093. self.wg.Add(1)
  1094. defer self.wg.Done()
  1095. whFunc := func(header *types.Header) error {
  1096. self.mu.Lock()
  1097. defer self.mu.Unlock()
  1098. _, err := self.hc.WriteHeader(header)
  1099. return err
  1100. }
  1101. return self.hc.InsertHeaderChain(chain, checkFreq, whFunc)
  1102. }
  1103. // writeHeader writes a header into the local chain, given that its parent is
  1104. // already known. If the total difficulty of the newly inserted header becomes
  1105. // greater than the current known TD, the canonical chain is re-routed.
  1106. //
  1107. // Note: This method is not concurrent-safe with inserting blocks simultaneously
  1108. // into the chain, as side effects caused by reorganisations cannot be emulated
  1109. // without the real blocks. Hence, writing headers directly should only be done
  1110. // in two scenarios: pure-header mode of operation (light clients), or properly
  1111. // separated header/block phases (non-archive clients).
  1112. func (self *BlockChain) writeHeader(header *types.Header) error {
  1113. self.wg.Add(1)
  1114. defer self.wg.Done()
  1115. self.mu.Lock()
  1116. defer self.mu.Unlock()
  1117. _, err := self.hc.WriteHeader(header)
  1118. return err
  1119. }
  1120. // CurrentHeader retrieves the current head header of the canonical chain. The
  1121. // header is retrieved from the HeaderChain's internal cache.
  1122. func (self *BlockChain) CurrentHeader() *types.Header {
  1123. self.mu.RLock()
  1124. defer self.mu.RUnlock()
  1125. return self.hc.CurrentHeader()
  1126. }
  1127. // GetTd retrieves a block's total difficulty in the canonical chain from the
  1128. // database by hash and number, caching it if found.
  1129. func (self *BlockChain) GetTd(hash common.Hash, number uint64) *big.Int {
  1130. return self.hc.GetTd(hash, number)
  1131. }
  1132. // GetTdByHash retrieves a block's total difficulty in the canonical chain from the
  1133. // database by hash, caching it if found.
  1134. func (self *BlockChain) GetTdByHash(hash common.Hash) *big.Int {
  1135. return self.hc.GetTdByHash(hash)
  1136. }
  1137. // GetHeader retrieves a block header from the database by hash and number,
  1138. // caching it if found.
  1139. func (self *BlockChain) GetHeader(hash common.Hash, number uint64) *types.Header {
  1140. return self.hc.GetHeader(hash, number)
  1141. }
  1142. // GetHeaderByHash retrieves a block header from the database by hash, caching it if
  1143. // found.
  1144. func (self *BlockChain) GetHeaderByHash(hash common.Hash) *types.Header {
  1145. return self.hc.GetHeaderByHash(hash)
  1146. }
  1147. // HasHeader checks if a block header is present in the database or not, caching
  1148. // it if present.
  1149. func (bc *BlockChain) HasHeader(hash common.Hash) bool {
  1150. return bc.hc.HasHeader(hash)
  1151. }
  1152. // GetBlockHashesFromHash retrieves a number of block hashes starting at a given
  1153. // hash, fetching towards the genesis block.
  1154. func (self *BlockChain) GetBlockHashesFromHash(hash common.Hash, max uint64) []common.Hash {
  1155. return self.hc.GetBlockHashesFromHash(hash, max)
  1156. }
  1157. // GetHeaderByNumber retrieves a block header from the database by number,
  1158. // caching it (associated with its hash) if found.
  1159. func (self *BlockChain) GetHeaderByNumber(number uint64) *types.Header {
  1160. return self.hc.GetHeaderByNumber(number)
  1161. }
  1162. // Config retrieves the blockchain's chain configuration.
  1163. func (self *BlockChain) Config() *params.ChainConfig { return self.config }