lightchain.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492
  1. // Copyright 2016 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 light
  17. import (
  18. "math/big"
  19. "sync"
  20. "sync/atomic"
  21. "github.com/ethereum/go-ethereum/common"
  22. "github.com/ethereum/go-ethereum/core"
  23. "github.com/ethereum/go-ethereum/core/types"
  24. "github.com/ethereum/go-ethereum/ethdb"
  25. "github.com/ethereum/go-ethereum/event"
  26. "github.com/ethereum/go-ethereum/log"
  27. "github.com/ethereum/go-ethereum/params"
  28. "github.com/ethereum/go-ethereum/pow"
  29. "github.com/ethereum/go-ethereum/rlp"
  30. "github.com/hashicorp/golang-lru"
  31. "golang.org/x/net/context"
  32. )
  33. var (
  34. bodyCacheLimit = 256
  35. blockCacheLimit = 256
  36. )
  37. // LightChain represents a canonical chain that by default only handles block
  38. // headers, downloading block bodies and receipts on demand through an ODR
  39. // interface. It only does header validation during chain insertion.
  40. type LightChain struct {
  41. hc *core.HeaderChain
  42. chainDb ethdb.Database
  43. odr OdrBackend
  44. eventMux *event.TypeMux
  45. genesisBlock *types.Block
  46. mu sync.RWMutex
  47. chainmu sync.RWMutex
  48. procmu sync.RWMutex
  49. bodyCache *lru.Cache // Cache for the most recent block bodies
  50. bodyRLPCache *lru.Cache // Cache for the most recent block bodies in RLP encoded format
  51. blockCache *lru.Cache // Cache for the most recent entire blocks
  52. quit chan struct{}
  53. running int32 // running must be called automically
  54. // procInterrupt must be atomically called
  55. procInterrupt int32 // interrupt signaler for block processing
  56. wg sync.WaitGroup
  57. pow pow.PoW
  58. validator core.HeaderValidator
  59. }
  60. // NewLightChain returns a fully initialised light chain using information
  61. // available in the database. It initialises the default Ethereum header
  62. // validator.
  63. func NewLightChain(odr OdrBackend, config *params.ChainConfig, pow pow.PoW, mux *event.TypeMux) (*LightChain, error) {
  64. bodyCache, _ := lru.New(bodyCacheLimit)
  65. bodyRLPCache, _ := lru.New(bodyCacheLimit)
  66. blockCache, _ := lru.New(blockCacheLimit)
  67. bc := &LightChain{
  68. chainDb: odr.Database(),
  69. odr: odr,
  70. eventMux: mux,
  71. quit: make(chan struct{}),
  72. bodyCache: bodyCache,
  73. bodyRLPCache: bodyRLPCache,
  74. blockCache: blockCache,
  75. pow: pow,
  76. }
  77. var err error
  78. bc.hc, err = core.NewHeaderChain(odr.Database(), config, bc.Validator, bc.getProcInterrupt)
  79. bc.SetValidator(core.NewHeaderValidator(config, bc.hc, pow))
  80. if err != nil {
  81. return nil, err
  82. }
  83. bc.genesisBlock, _ = bc.GetBlockByNumber(NoOdr, 0)
  84. if bc.genesisBlock == nil {
  85. bc.genesisBlock, err = core.WriteDefaultGenesisBlock(odr.Database())
  86. if err != nil {
  87. return nil, err
  88. }
  89. log.Warn("Wrote default ethereum genesis block")
  90. }
  91. if bc.genesisBlock.Hash() == params.MainNetGenesisHash {
  92. // add trusted CHT
  93. WriteTrustedCht(bc.chainDb, TrustedCht{Number: 805, Root: common.HexToHash("85e4286fe0a730390245c49de8476977afdae0eb5530b277f62a52b12313d50f")})
  94. log.Info("Added trusted CHT for mainnet")
  95. }
  96. if err := bc.loadLastState(); err != nil {
  97. return nil, err
  98. }
  99. // Check the current state of the block hashes and make sure that we do not have any of the bad blocks in our chain
  100. for hash := range core.BadHashes {
  101. if header := bc.GetHeaderByHash(hash); header != nil {
  102. log.Error("Found bad hash, rewinding chain", "number", header.Number, "hash", header.ParentHash)
  103. bc.SetHead(header.Number.Uint64() - 1)
  104. log.Error("Chain rewind was successful, resuming normal operation")
  105. }
  106. }
  107. return bc, nil
  108. }
  109. func (self *LightChain) getProcInterrupt() bool {
  110. return atomic.LoadInt32(&self.procInterrupt) == 1
  111. }
  112. // Odr returns the ODR backend of the chain
  113. func (self *LightChain) Odr() OdrBackend {
  114. return self.odr
  115. }
  116. // loadLastState loads the last known chain state from the database. This method
  117. // assumes that the chain manager mutex is held.
  118. func (self *LightChain) loadLastState() error {
  119. if head := core.GetHeadHeaderHash(self.chainDb); head == (common.Hash{}) {
  120. // Corrupt or empty database, init from scratch
  121. self.Reset()
  122. } else {
  123. if header := self.GetHeaderByHash(head); header != nil {
  124. self.hc.SetCurrentHeader(header)
  125. }
  126. }
  127. // Issue a status log and return
  128. header := self.hc.CurrentHeader()
  129. headerTd := self.GetTd(header.Hash(), header.Number.Uint64())
  130. log.Info("Loaded most recent local header", "number", header.Number, "hash", header.Hash(), "td", headerTd)
  131. // Try to be smart and issue a pow verification for the head to pre-generate caches
  132. go self.pow.Verify(types.NewBlockWithHeader(header))
  133. return nil
  134. }
  135. // SetHead rewinds the local chain to a new head. Everything above the new
  136. // head will be deleted and the new one set.
  137. func (bc *LightChain) SetHead(head uint64) {
  138. bc.mu.Lock()
  139. defer bc.mu.Unlock()
  140. bc.hc.SetHead(head, nil)
  141. bc.loadLastState()
  142. }
  143. // GasLimit returns the gas limit of the current HEAD block.
  144. func (self *LightChain) GasLimit() *big.Int {
  145. self.mu.RLock()
  146. defer self.mu.RUnlock()
  147. return self.hc.CurrentHeader().GasLimit
  148. }
  149. // LastBlockHash return the hash of the HEAD block.
  150. func (self *LightChain) LastBlockHash() common.Hash {
  151. self.mu.RLock()
  152. defer self.mu.RUnlock()
  153. return self.hc.CurrentHeader().Hash()
  154. }
  155. // Status returns status information about the current chain such as the HEAD Td,
  156. // the HEAD hash and the hash of the genesis block.
  157. func (self *LightChain) Status() (td *big.Int, currentBlock common.Hash, genesisBlock common.Hash) {
  158. self.mu.RLock()
  159. defer self.mu.RUnlock()
  160. header := self.hc.CurrentHeader()
  161. hash := header.Hash()
  162. return self.GetTd(hash, header.Number.Uint64()), hash, self.genesisBlock.Hash()
  163. }
  164. // SetValidator sets the validator which is used to validate incoming headers.
  165. func (self *LightChain) SetValidator(validator core.HeaderValidator) {
  166. self.procmu.Lock()
  167. defer self.procmu.Unlock()
  168. self.validator = validator
  169. }
  170. // Validator returns the current header validator.
  171. func (self *LightChain) Validator() core.HeaderValidator {
  172. self.procmu.RLock()
  173. defer self.procmu.RUnlock()
  174. return self.validator
  175. }
  176. // State returns a new mutable state based on the current HEAD block.
  177. func (self *LightChain) State() *LightState {
  178. return NewLightState(StateTrieID(self.hc.CurrentHeader()), self.odr)
  179. }
  180. // Reset purges the entire blockchain, restoring it to its genesis state.
  181. func (bc *LightChain) Reset() {
  182. bc.ResetWithGenesisBlock(bc.genesisBlock)
  183. }
  184. // ResetWithGenesisBlock purges the entire blockchain, restoring it to the
  185. // specified genesis state.
  186. func (bc *LightChain) ResetWithGenesisBlock(genesis *types.Block) {
  187. // Dump the entire block chain and purge the caches
  188. bc.SetHead(0)
  189. bc.mu.Lock()
  190. defer bc.mu.Unlock()
  191. // Prepare the genesis block and reinitialise the chain
  192. if err := core.WriteTd(bc.chainDb, genesis.Hash(), genesis.NumberU64(), genesis.Difficulty()); err != nil {
  193. log.Crit("Failed to write genesis block TD", "err", err)
  194. }
  195. if err := core.WriteBlock(bc.chainDb, genesis); err != nil {
  196. log.Crit("Failed to write genesis block", "err", err)
  197. }
  198. bc.genesisBlock = genesis
  199. bc.hc.SetGenesis(bc.genesisBlock.Header())
  200. bc.hc.SetCurrentHeader(bc.genesisBlock.Header())
  201. }
  202. // Accessors
  203. // Genesis returns the genesis block
  204. func (bc *LightChain) Genesis() *types.Block {
  205. return bc.genesisBlock
  206. }
  207. // GetBody retrieves a block body (transactions and uncles) from the database
  208. // or ODR service by hash, caching it if found.
  209. func (self *LightChain) GetBody(ctx context.Context, hash common.Hash) (*types.Body, error) {
  210. // Short circuit if the body's already in the cache, retrieve otherwise
  211. if cached, ok := self.bodyCache.Get(hash); ok {
  212. body := cached.(*types.Body)
  213. return body, nil
  214. }
  215. body, err := GetBody(ctx, self.odr, hash, self.hc.GetBlockNumber(hash))
  216. if err != nil {
  217. return nil, err
  218. }
  219. // Cache the found body for next time and return
  220. self.bodyCache.Add(hash, body)
  221. return body, nil
  222. }
  223. // GetBodyRLP retrieves a block body in RLP encoding from the database or
  224. // ODR service by hash, caching it if found.
  225. func (self *LightChain) GetBodyRLP(ctx context.Context, hash common.Hash) (rlp.RawValue, error) {
  226. // Short circuit if the body's already in the cache, retrieve otherwise
  227. if cached, ok := self.bodyRLPCache.Get(hash); ok {
  228. return cached.(rlp.RawValue), nil
  229. }
  230. body, err := GetBodyRLP(ctx, self.odr, hash, self.hc.GetBlockNumber(hash))
  231. if err != nil {
  232. return nil, err
  233. }
  234. // Cache the found body for next time and return
  235. self.bodyRLPCache.Add(hash, body)
  236. return body, nil
  237. }
  238. // HasBlock checks if a block is fully present in the database or not, caching
  239. // it if present.
  240. func (bc *LightChain) HasBlock(hash common.Hash) bool {
  241. blk, _ := bc.GetBlockByHash(NoOdr, hash)
  242. return blk != nil
  243. }
  244. // GetBlock retrieves a block from the database or ODR service by hash and number,
  245. // caching it if found.
  246. func (self *LightChain) GetBlock(ctx context.Context, hash common.Hash, number uint64) (*types.Block, error) {
  247. // Short circuit if the block's already in the cache, retrieve otherwise
  248. if block, ok := self.blockCache.Get(hash); ok {
  249. return block.(*types.Block), nil
  250. }
  251. block, err := GetBlock(ctx, self.odr, hash, number)
  252. if err != nil {
  253. return nil, err
  254. }
  255. // Cache the found block for next time and return
  256. self.blockCache.Add(block.Hash(), block)
  257. return block, nil
  258. }
  259. // GetBlockByHash retrieves a block from the database or ODR service by hash,
  260. // caching it if found.
  261. func (self *LightChain) GetBlockByHash(ctx context.Context, hash common.Hash) (*types.Block, error) {
  262. return self.GetBlock(ctx, hash, self.hc.GetBlockNumber(hash))
  263. }
  264. // GetBlockByNumber retrieves a block from the database or ODR service by
  265. // number, caching it (associated with its hash) if found.
  266. func (self *LightChain) GetBlockByNumber(ctx context.Context, number uint64) (*types.Block, error) {
  267. hash, err := GetCanonicalHash(ctx, self.odr, number)
  268. if hash == (common.Hash{}) || err != nil {
  269. return nil, err
  270. }
  271. return self.GetBlock(ctx, hash, number)
  272. }
  273. // Stop stops the blockchain service. If any imports are currently in progress
  274. // it will abort them using the procInterrupt.
  275. func (bc *LightChain) Stop() {
  276. if !atomic.CompareAndSwapInt32(&bc.running, 0, 1) {
  277. return
  278. }
  279. close(bc.quit)
  280. atomic.StoreInt32(&bc.procInterrupt, 1)
  281. bc.wg.Wait()
  282. log.Info("Blockchain manager stopped")
  283. }
  284. // Rollback is designed to remove a chain of links from the database that aren't
  285. // certain enough to be valid.
  286. func (self *LightChain) Rollback(chain []common.Hash) {
  287. self.mu.Lock()
  288. defer self.mu.Unlock()
  289. for i := len(chain) - 1; i >= 0; i-- {
  290. hash := chain[i]
  291. if head := self.hc.CurrentHeader(); head.Hash() == hash {
  292. self.hc.SetCurrentHeader(self.GetHeader(head.ParentHash, head.Number.Uint64()-1))
  293. }
  294. }
  295. }
  296. // postChainEvents iterates over the events generated by a chain insertion and
  297. // posts them into the event mux.
  298. func (self *LightChain) postChainEvents(events []interface{}) {
  299. for _, event := range events {
  300. if event, ok := event.(core.ChainEvent); ok {
  301. if self.LastBlockHash() == event.Hash {
  302. self.eventMux.Post(core.ChainHeadEvent{Block: event.Block})
  303. }
  304. }
  305. // Fire the insertion events individually too
  306. self.eventMux.Post(event)
  307. }
  308. }
  309. // InsertHeaderChain attempts to insert the given header chain in to the local
  310. // chain, possibly creating a reorg. If an error is returned, it will return the
  311. // index number of the failing header as well an error describing what went wrong.
  312. //
  313. // The verify parameter can be used to fine tune whether nonce verification
  314. // should be done or not. The reason behind the optional check is because some
  315. // of the header retrieval mechanisms already need to verfy nonces, as well as
  316. // because nonces can be verified sparsely, not needing to check each.
  317. //
  318. // In the case of a light chain, InsertHeaderChain also creates and posts light
  319. // chain events when necessary.
  320. func (self *LightChain) InsertHeaderChain(chain []*types.Header, checkFreq int) (int, error) {
  321. // Make sure only one thread manipulates the chain at once
  322. self.chainmu.Lock()
  323. defer self.chainmu.Unlock()
  324. self.wg.Add(1)
  325. defer self.wg.Done()
  326. var events []interface{}
  327. whFunc := func(header *types.Header) error {
  328. self.mu.Lock()
  329. defer self.mu.Unlock()
  330. status, err := self.hc.WriteHeader(header)
  331. switch status {
  332. case core.CanonStatTy:
  333. log.Debug("Inserted new header", "number", header.Number, "hash", header.Hash())
  334. events = append(events, core.ChainEvent{Block: types.NewBlockWithHeader(header), Hash: header.Hash()})
  335. case core.SideStatTy:
  336. log.Debug("Inserted forked header", "number", header.Number, "hash", header.Hash())
  337. events = append(events, core.ChainSideEvent{Block: types.NewBlockWithHeader(header)})
  338. case core.SplitStatTy:
  339. events = append(events, core.ChainSplitEvent{Block: types.NewBlockWithHeader(header)})
  340. }
  341. return err
  342. }
  343. i, err := self.hc.InsertHeaderChain(chain, checkFreq, whFunc)
  344. go self.postChainEvents(events)
  345. return i, err
  346. }
  347. // CurrentHeader retrieves the current head header of the canonical chain. The
  348. // header is retrieved from the HeaderChain's internal cache.
  349. func (self *LightChain) CurrentHeader() *types.Header {
  350. self.mu.RLock()
  351. defer self.mu.RUnlock()
  352. return self.hc.CurrentHeader()
  353. }
  354. // GetTd retrieves a block's total difficulty in the canonical chain from the
  355. // database by hash and number, caching it if found.
  356. func (self *LightChain) GetTd(hash common.Hash, number uint64) *big.Int {
  357. return self.hc.GetTd(hash, number)
  358. }
  359. // GetTdByHash retrieves a block's total difficulty in the canonical chain from the
  360. // database by hash, caching it if found.
  361. func (self *LightChain) GetTdByHash(hash common.Hash) *big.Int {
  362. return self.hc.GetTdByHash(hash)
  363. }
  364. // GetHeader retrieves a block header from the database by hash and number,
  365. // caching it if found.
  366. func (self *LightChain) GetHeader(hash common.Hash, number uint64) *types.Header {
  367. return self.hc.GetHeader(hash, number)
  368. }
  369. // GetHeaderByHash retrieves a block header from the database by hash, caching it if
  370. // found.
  371. func (self *LightChain) GetHeaderByHash(hash common.Hash) *types.Header {
  372. return self.hc.GetHeaderByHash(hash)
  373. }
  374. // HasHeader checks if a block header is present in the database or not, caching
  375. // it if present.
  376. func (bc *LightChain) HasHeader(hash common.Hash) bool {
  377. return bc.hc.HasHeader(hash)
  378. }
  379. // GetBlockHashesFromHash retrieves a number of block hashes starting at a given
  380. // hash, fetching towards the genesis block.
  381. func (self *LightChain) GetBlockHashesFromHash(hash common.Hash, max uint64) []common.Hash {
  382. return self.hc.GetBlockHashesFromHash(hash, max)
  383. }
  384. // GetHeaderByNumber retrieves a block header from the database by number,
  385. // caching it (associated with its hash) if found.
  386. func (self *LightChain) GetHeaderByNumber(number uint64) *types.Header {
  387. return self.hc.GetHeaderByNumber(number)
  388. }
  389. // GetHeaderByNumberOdr retrieves a block header from the database or network
  390. // by number, caching it (associated with its hash) if found.
  391. func (self *LightChain) GetHeaderByNumberOdr(ctx context.Context, number uint64) (*types.Header, error) {
  392. if header := self.hc.GetHeaderByNumber(number); header != nil {
  393. return header, nil
  394. }
  395. return GetHeaderByNumber(ctx, self.odr, number)
  396. }
  397. func (self *LightChain) SyncCht(ctx context.Context) bool {
  398. headNum := self.CurrentHeader().Number.Uint64()
  399. cht := GetTrustedCht(self.chainDb)
  400. if headNum+1 < cht.Number*ChtFrequency {
  401. num := cht.Number*ChtFrequency - 1
  402. header, err := GetHeaderByNumber(ctx, self.odr, num)
  403. if header != nil && err == nil {
  404. self.mu.Lock()
  405. if self.hc.CurrentHeader().Number.Uint64() < header.Number.Uint64() {
  406. self.hc.SetCurrentHeader(header)
  407. }
  408. self.mu.Unlock()
  409. return true
  410. }
  411. }
  412. return false
  413. }
  414. // LockChain locks the chain mutex for reading so that multiple canonical hashes can be
  415. // retrieved while it is guaranteed that they belong to the same version of the chain
  416. func (self *LightChain) LockChain() {
  417. self.chainmu.RLock()
  418. }
  419. // UnlockChain unlocks the chain mutex
  420. func (self *LightChain) UnlockChain() {
  421. self.chainmu.RUnlock()
  422. }