blockchain.go 42 KB

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