blockchain.go 45 KB

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