blockchain.go 41 KB

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