lightchain.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535
  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. "context"
  19. "errors"
  20. "math/big"
  21. "sync"
  22. "sync/atomic"
  23. "time"
  24. "github.com/ethereum/go-ethereum/common"
  25. "github.com/ethereum/go-ethereum/consensus"
  26. "github.com/ethereum/go-ethereum/core"
  27. "github.com/ethereum/go-ethereum/core/rawdb"
  28. "github.com/ethereum/go-ethereum/core/state"
  29. "github.com/ethereum/go-ethereum/core/types"
  30. "github.com/ethereum/go-ethereum/ethdb"
  31. "github.com/ethereum/go-ethereum/event"
  32. "github.com/ethereum/go-ethereum/log"
  33. "github.com/ethereum/go-ethereum/params"
  34. "github.com/ethereum/go-ethereum/rlp"
  35. "github.com/hashicorp/golang-lru"
  36. )
  37. var (
  38. bodyCacheLimit = 256
  39. blockCacheLimit = 256
  40. )
  41. // LightChain represents a canonical chain that by default only handles block
  42. // headers, downloading block bodies and receipts on demand through an ODR
  43. // interface. It only does header validation during chain insertion.
  44. type LightChain struct {
  45. hc *core.HeaderChain
  46. indexerConfig *IndexerConfig
  47. chainDb ethdb.Database
  48. odr OdrBackend
  49. chainFeed event.Feed
  50. chainSideFeed event.Feed
  51. chainHeadFeed event.Feed
  52. scope event.SubscriptionScope
  53. genesisBlock *types.Block
  54. mu sync.RWMutex
  55. chainmu sync.RWMutex
  56. bodyCache *lru.Cache // Cache for the most recent block bodies
  57. bodyRLPCache *lru.Cache // Cache for the most recent block bodies in RLP encoded format
  58. blockCache *lru.Cache // Cache for the most recent entire blocks
  59. quit chan struct{}
  60. running int32 // running must be called automically
  61. // procInterrupt must be atomically called
  62. procInterrupt int32 // interrupt signaler for block processing
  63. wg sync.WaitGroup
  64. engine consensus.Engine
  65. }
  66. // NewLightChain returns a fully initialised light chain using information
  67. // available in the database. It initialises the default Ethereum header
  68. // validator.
  69. func NewLightChain(odr OdrBackend, config *params.ChainConfig, engine consensus.Engine) (*LightChain, error) {
  70. bodyCache, _ := lru.New(bodyCacheLimit)
  71. bodyRLPCache, _ := lru.New(bodyCacheLimit)
  72. blockCache, _ := lru.New(blockCacheLimit)
  73. bc := &LightChain{
  74. chainDb: odr.Database(),
  75. indexerConfig: odr.IndexerConfig(),
  76. odr: odr,
  77. quit: make(chan struct{}),
  78. bodyCache: bodyCache,
  79. bodyRLPCache: bodyRLPCache,
  80. blockCache: blockCache,
  81. engine: engine,
  82. }
  83. var err error
  84. bc.hc, err = core.NewHeaderChain(odr.Database(), config, bc.engine, bc.getProcInterrupt)
  85. if err != nil {
  86. return nil, err
  87. }
  88. bc.genesisBlock, _ = bc.GetBlockByNumber(NoOdr, 0)
  89. if bc.genesisBlock == nil {
  90. return nil, core.ErrNoGenesis
  91. }
  92. if cp, ok := trustedCheckpoints[bc.genesisBlock.Hash()]; ok {
  93. bc.addTrustedCheckpoint(cp)
  94. }
  95. if err := bc.loadLastState(); err != nil {
  96. return nil, err
  97. }
  98. // Check the current state of the block hashes and make sure that we do not have any of the bad blocks in our chain
  99. for hash := range core.BadHashes {
  100. if header := bc.GetHeaderByHash(hash); header != nil {
  101. log.Error("Found bad hash, rewinding chain", "number", header.Number, "hash", header.ParentHash)
  102. bc.SetHead(header.Number.Uint64() - 1)
  103. log.Error("Chain rewind was successful, resuming normal operation")
  104. }
  105. }
  106. return bc, nil
  107. }
  108. // addTrustedCheckpoint adds a trusted checkpoint to the blockchain
  109. func (self *LightChain) addTrustedCheckpoint(cp *params.TrustedCheckpoint) {
  110. if self.odr.ChtIndexer() != nil {
  111. StoreChtRoot(self.chainDb, cp.SectionIndex, cp.SectionHead, cp.CHTRoot)
  112. self.odr.ChtIndexer().AddCheckpoint(cp.SectionIndex, cp.SectionHead)
  113. }
  114. if self.odr.BloomTrieIndexer() != nil {
  115. StoreBloomTrieRoot(self.chainDb, cp.SectionIndex, cp.SectionHead, cp.BloomRoot)
  116. self.odr.BloomTrieIndexer().AddCheckpoint(cp.SectionIndex, cp.SectionHead)
  117. }
  118. if self.odr.BloomIndexer() != nil {
  119. self.odr.BloomIndexer().AddCheckpoint(cp.SectionIndex, cp.SectionHead)
  120. }
  121. log.Info("Added trusted checkpoint", "chain", cp.Name, "block", (cp.SectionIndex+1)*self.indexerConfig.ChtSize-1, "hash", cp.SectionHead)
  122. }
  123. func (self *LightChain) getProcInterrupt() bool {
  124. return atomic.LoadInt32(&self.procInterrupt) == 1
  125. }
  126. // Odr returns the ODR backend of the chain
  127. func (self *LightChain) Odr() OdrBackend {
  128. return self.odr
  129. }
  130. // loadLastState loads the last known chain state from the database. This method
  131. // assumes that the chain manager mutex is held.
  132. func (self *LightChain) loadLastState() error {
  133. if head := rawdb.ReadHeadHeaderHash(self.chainDb); head == (common.Hash{}) {
  134. // Corrupt or empty database, init from scratch
  135. self.Reset()
  136. } else {
  137. if header := self.GetHeaderByHash(head); header != nil {
  138. self.hc.SetCurrentHeader(header)
  139. }
  140. }
  141. // Issue a status log and return
  142. header := self.hc.CurrentHeader()
  143. headerTd := self.GetTd(header.Hash(), header.Number.Uint64())
  144. log.Info("Loaded most recent local header", "number", header.Number, "hash", header.Hash(), "td", headerTd, "age", common.PrettyAge(time.Unix(header.Time.Int64(), 0)))
  145. return nil
  146. }
  147. // SetHead rewinds the local chain to a new head. Everything above the new
  148. // head will be deleted and the new one set.
  149. func (bc *LightChain) SetHead(head uint64) {
  150. bc.mu.Lock()
  151. defer bc.mu.Unlock()
  152. bc.hc.SetHead(head, nil)
  153. bc.loadLastState()
  154. }
  155. // GasLimit returns the gas limit of the current HEAD block.
  156. func (self *LightChain) GasLimit() uint64 {
  157. return self.hc.CurrentHeader().GasLimit
  158. }
  159. // Reset purges the entire blockchain, restoring it to its genesis state.
  160. func (bc *LightChain) Reset() {
  161. bc.ResetWithGenesisBlock(bc.genesisBlock)
  162. }
  163. // ResetWithGenesisBlock purges the entire blockchain, restoring it to the
  164. // specified genesis state.
  165. func (bc *LightChain) ResetWithGenesisBlock(genesis *types.Block) {
  166. // Dump the entire block chain and purge the caches
  167. bc.SetHead(0)
  168. bc.mu.Lock()
  169. defer bc.mu.Unlock()
  170. // Prepare the genesis block and reinitialise the chain
  171. rawdb.WriteTd(bc.chainDb, genesis.Hash(), genesis.NumberU64(), genesis.Difficulty())
  172. rawdb.WriteBlock(bc.chainDb, genesis)
  173. bc.genesisBlock = genesis
  174. bc.hc.SetGenesis(bc.genesisBlock.Header())
  175. bc.hc.SetCurrentHeader(bc.genesisBlock.Header())
  176. }
  177. // Accessors
  178. // Engine retrieves the light chain's consensus engine.
  179. func (bc *LightChain) Engine() consensus.Engine { return bc.engine }
  180. // Genesis returns the genesis block
  181. func (bc *LightChain) Genesis() *types.Block {
  182. return bc.genesisBlock
  183. }
  184. // State returns a new mutable state based on the current HEAD block.
  185. func (bc *LightChain) State() (*state.StateDB, error) {
  186. return nil, errors.New("not implemented, needs client/server interface split")
  187. }
  188. // GetBody retrieves a block body (transactions and uncles) from the database
  189. // or ODR service by hash, caching it if found.
  190. func (self *LightChain) GetBody(ctx context.Context, hash common.Hash) (*types.Body, error) {
  191. // Short circuit if the body's already in the cache, retrieve otherwise
  192. if cached, ok := self.bodyCache.Get(hash); ok {
  193. body := cached.(*types.Body)
  194. return body, nil
  195. }
  196. number := self.hc.GetBlockNumber(hash)
  197. if number == nil {
  198. return nil, errors.New("unknown block")
  199. }
  200. body, err := GetBody(ctx, self.odr, hash, *number)
  201. if err != nil {
  202. return nil, err
  203. }
  204. // Cache the found body for next time and return
  205. self.bodyCache.Add(hash, body)
  206. return body, nil
  207. }
  208. // GetBodyRLP retrieves a block body in RLP encoding from the database or
  209. // ODR service by hash, caching it if found.
  210. func (self *LightChain) GetBodyRLP(ctx context.Context, hash common.Hash) (rlp.RawValue, error) {
  211. // Short circuit if the body's already in the cache, retrieve otherwise
  212. if cached, ok := self.bodyRLPCache.Get(hash); ok {
  213. return cached.(rlp.RawValue), nil
  214. }
  215. number := self.hc.GetBlockNumber(hash)
  216. if number == nil {
  217. return nil, errors.New("unknown block")
  218. }
  219. body, err := GetBodyRLP(ctx, self.odr, hash, *number)
  220. if err != nil {
  221. return nil, err
  222. }
  223. // Cache the found body for next time and return
  224. self.bodyRLPCache.Add(hash, body)
  225. return body, nil
  226. }
  227. // HasBlock checks if a block is fully present in the database or not, caching
  228. // it if present.
  229. func (bc *LightChain) HasBlock(hash common.Hash, number uint64) bool {
  230. blk, _ := bc.GetBlock(NoOdr, hash, number)
  231. return blk != nil
  232. }
  233. // GetBlock retrieves a block from the database or ODR service by hash and number,
  234. // caching it if found.
  235. func (self *LightChain) GetBlock(ctx context.Context, hash common.Hash, number uint64) (*types.Block, error) {
  236. // Short circuit if the block's already in the cache, retrieve otherwise
  237. if block, ok := self.blockCache.Get(hash); ok {
  238. return block.(*types.Block), nil
  239. }
  240. block, err := GetBlock(ctx, self.odr, hash, number)
  241. if err != nil {
  242. return nil, err
  243. }
  244. // Cache the found block for next time and return
  245. self.blockCache.Add(block.Hash(), block)
  246. return block, nil
  247. }
  248. // GetBlockByHash retrieves a block from the database or ODR service by hash,
  249. // caching it if found.
  250. func (self *LightChain) GetBlockByHash(ctx context.Context, hash common.Hash) (*types.Block, error) {
  251. number := self.hc.GetBlockNumber(hash)
  252. if number == nil {
  253. return nil, errors.New("unknown block")
  254. }
  255. return self.GetBlock(ctx, hash, *number)
  256. }
  257. // GetBlockByNumber retrieves a block from the database or ODR service by
  258. // number, caching it (associated with its hash) if found.
  259. func (self *LightChain) GetBlockByNumber(ctx context.Context, number uint64) (*types.Block, error) {
  260. hash, err := GetCanonicalHash(ctx, self.odr, number)
  261. if hash == (common.Hash{}) || err != nil {
  262. return nil, err
  263. }
  264. return self.GetBlock(ctx, hash, number)
  265. }
  266. // Stop stops the blockchain service. If any imports are currently in progress
  267. // it will abort them using the procInterrupt.
  268. func (bc *LightChain) Stop() {
  269. if !atomic.CompareAndSwapInt32(&bc.running, 0, 1) {
  270. return
  271. }
  272. close(bc.quit)
  273. atomic.StoreInt32(&bc.procInterrupt, 1)
  274. bc.wg.Wait()
  275. log.Info("Blockchain manager stopped")
  276. }
  277. // Rollback is designed to remove a chain of links from the database that aren't
  278. // certain enough to be valid.
  279. func (self *LightChain) Rollback(chain []common.Hash) {
  280. self.mu.Lock()
  281. defer self.mu.Unlock()
  282. for i := len(chain) - 1; i >= 0; i-- {
  283. hash := chain[i]
  284. if head := self.hc.CurrentHeader(); head.Hash() == hash {
  285. self.hc.SetCurrentHeader(self.GetHeader(head.ParentHash, head.Number.Uint64()-1))
  286. }
  287. }
  288. }
  289. // postChainEvents iterates over the events generated by a chain insertion and
  290. // posts them into the event feed.
  291. func (self *LightChain) postChainEvents(events []interface{}) {
  292. for _, event := range events {
  293. switch ev := event.(type) {
  294. case core.ChainEvent:
  295. if self.CurrentHeader().Hash() == ev.Hash {
  296. self.chainHeadFeed.Send(core.ChainHeadEvent{Block: ev.Block})
  297. }
  298. self.chainFeed.Send(ev)
  299. case core.ChainSideEvent:
  300. self.chainSideFeed.Send(ev)
  301. }
  302. }
  303. }
  304. // InsertHeaderChain attempts to insert the given header chain in to the local
  305. // chain, possibly creating a reorg. If an error is returned, it will return the
  306. // index number of the failing header as well an error describing what went wrong.
  307. //
  308. // The verify parameter can be used to fine tune whether nonce verification
  309. // should be done or not. The reason behind the optional check is because some
  310. // of the header retrieval mechanisms already need to verfy nonces, as well as
  311. // because nonces can be verified sparsely, not needing to check each.
  312. //
  313. // In the case of a light chain, InsertHeaderChain also creates and posts light
  314. // chain events when necessary.
  315. func (self *LightChain) InsertHeaderChain(chain []*types.Header, checkFreq int) (int, error) {
  316. start := time.Now()
  317. if i, err := self.hc.ValidateHeaderChain(chain, checkFreq); err != nil {
  318. return i, err
  319. }
  320. // Make sure only one thread manipulates the chain at once
  321. self.chainmu.Lock()
  322. defer func() {
  323. self.chainmu.Unlock()
  324. time.Sleep(time.Millisecond * 10) // ugly hack; do not hog chain lock in case syncing is CPU-limited by validation
  325. }()
  326. self.wg.Add(1)
  327. defer self.wg.Done()
  328. var events []interface{}
  329. whFunc := func(header *types.Header) error {
  330. self.mu.Lock()
  331. defer self.mu.Unlock()
  332. status, err := self.hc.WriteHeader(header)
  333. switch status {
  334. case core.CanonStatTy:
  335. log.Debug("Inserted new header", "number", header.Number, "hash", header.Hash())
  336. events = append(events, core.ChainEvent{Block: types.NewBlockWithHeader(header), Hash: header.Hash()})
  337. case core.SideStatTy:
  338. log.Debug("Inserted forked header", "number", header.Number, "hash", header.Hash())
  339. events = append(events, core.ChainSideEvent{Block: types.NewBlockWithHeader(header)})
  340. }
  341. return err
  342. }
  343. i, err := self.hc.InsertHeaderChain(chain, whFunc, start)
  344. 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. return self.hc.CurrentHeader()
  351. }
  352. // GetTd retrieves a block's total difficulty in the canonical chain from the
  353. // database by hash and number, caching it if found.
  354. func (self *LightChain) GetTd(hash common.Hash, number uint64) *big.Int {
  355. return self.hc.GetTd(hash, number)
  356. }
  357. // GetTdByHash retrieves a block's total difficulty in the canonical chain from the
  358. // database by hash, caching it if found.
  359. func (self *LightChain) GetTdByHash(hash common.Hash) *big.Int {
  360. return self.hc.GetTdByHash(hash)
  361. }
  362. // GetHeader retrieves a block header from the database by hash and number,
  363. // caching it if found.
  364. func (self *LightChain) GetHeader(hash common.Hash, number uint64) *types.Header {
  365. return self.hc.GetHeader(hash, number)
  366. }
  367. // GetHeaderByHash retrieves a block header from the database by hash, caching it if
  368. // found.
  369. func (self *LightChain) GetHeaderByHash(hash common.Hash) *types.Header {
  370. return self.hc.GetHeaderByHash(hash)
  371. }
  372. // HasHeader checks if a block header is present in the database or not, caching
  373. // it if present.
  374. func (bc *LightChain) HasHeader(hash common.Hash, number uint64) bool {
  375. return bc.hc.HasHeader(hash, number)
  376. }
  377. // GetBlockHashesFromHash retrieves a number of block hashes starting at a given
  378. // hash, fetching towards the genesis block.
  379. func (self *LightChain) GetBlockHashesFromHash(hash common.Hash, max uint64) []common.Hash {
  380. return self.hc.GetBlockHashesFromHash(hash, max)
  381. }
  382. // GetAncestor retrieves the Nth ancestor of a given block. It assumes that either the given block or
  383. // a close ancestor of it is canonical. maxNonCanonical points to a downwards counter limiting the
  384. // number of blocks to be individually checked before we reach the canonical chain.
  385. //
  386. // Note: ancestor == 0 returns the same block, 1 returns its parent and so on.
  387. func (bc *LightChain) GetAncestor(hash common.Hash, number, ancestor uint64, maxNonCanonical *uint64) (common.Hash, uint64) {
  388. bc.chainmu.Lock()
  389. defer bc.chainmu.Unlock()
  390. return bc.hc.GetAncestor(hash, number, ancestor, maxNonCanonical)
  391. }
  392. // GetHeaderByNumber retrieves a block header from the database by number,
  393. // caching it (associated with its hash) if found.
  394. func (self *LightChain) GetHeaderByNumber(number uint64) *types.Header {
  395. return self.hc.GetHeaderByNumber(number)
  396. }
  397. // GetHeaderByNumberOdr retrieves a block header from the database or network
  398. // by number, caching it (associated with its hash) if found.
  399. func (self *LightChain) GetHeaderByNumberOdr(ctx context.Context, number uint64) (*types.Header, error) {
  400. if header := self.hc.GetHeaderByNumber(number); header != nil {
  401. return header, nil
  402. }
  403. return GetHeaderByNumber(ctx, self.odr, number)
  404. }
  405. // Config retrieves the header chain's chain configuration.
  406. func (self *LightChain) Config() *params.ChainConfig { return self.hc.Config() }
  407. func (self *LightChain) SyncCht(ctx context.Context) bool {
  408. // If we don't have a CHT indexer, abort
  409. if self.odr.ChtIndexer() == nil {
  410. return false
  411. }
  412. // Ensure the remote CHT head is ahead of us
  413. head := self.CurrentHeader().Number.Uint64()
  414. sections, _, _ := self.odr.ChtIndexer().Sections()
  415. latest := sections*self.indexerConfig.ChtSize - 1
  416. if clique := self.hc.Config().Clique; clique != nil {
  417. latest -= latest % clique.Epoch // epoch snapshot for clique
  418. }
  419. if head >= latest {
  420. return false
  421. }
  422. // Retrieve the latest useful header and update to it
  423. if header, err := GetHeaderByNumber(ctx, self.odr, latest); header != nil && err == nil {
  424. self.mu.Lock()
  425. defer self.mu.Unlock()
  426. // Ensure the chain didn't move past the latest block while retrieving it
  427. if self.hc.CurrentHeader().Number.Uint64() < header.Number.Uint64() {
  428. log.Info("Updated latest header based on CHT", "number", header.Number, "hash", header.Hash(), "age", common.PrettyAge(time.Unix(header.Time.Int64(), 0)))
  429. self.hc.SetCurrentHeader(header)
  430. }
  431. return true
  432. }
  433. return false
  434. }
  435. // LockChain locks the chain mutex for reading so that multiple canonical hashes can be
  436. // retrieved while it is guaranteed that they belong to the same version of the chain
  437. func (self *LightChain) LockChain() {
  438. self.chainmu.RLock()
  439. }
  440. // UnlockChain unlocks the chain mutex
  441. func (self *LightChain) UnlockChain() {
  442. self.chainmu.RUnlock()
  443. }
  444. // SubscribeChainEvent registers a subscription of ChainEvent.
  445. func (self *LightChain) SubscribeChainEvent(ch chan<- core.ChainEvent) event.Subscription {
  446. return self.scope.Track(self.chainFeed.Subscribe(ch))
  447. }
  448. // SubscribeChainHeadEvent registers a subscription of ChainHeadEvent.
  449. func (self *LightChain) SubscribeChainHeadEvent(ch chan<- core.ChainHeadEvent) event.Subscription {
  450. return self.scope.Track(self.chainHeadFeed.Subscribe(ch))
  451. }
  452. // SubscribeChainSideEvent registers a subscription of ChainSideEvent.
  453. func (self *LightChain) SubscribeChainSideEvent(ch chan<- core.ChainSideEvent) event.Subscription {
  454. return self.scope.Track(self.chainSideFeed.Subscribe(ch))
  455. }
  456. // SubscribeLogsEvent implements the interface of filters.Backend
  457. // LightChain does not send logs events, so return an empty subscription.
  458. func (self *LightChain) SubscribeLogsEvent(ch chan<- []*types.Log) event.Subscription {
  459. return self.scope.Track(new(event.Feed).Subscribe(ch))
  460. }
  461. // SubscribeRemovedLogsEvent implements the interface of filters.Backend
  462. // LightChain does not send core.RemovedLogsEvent, so return an empty subscription.
  463. func (self *LightChain) SubscribeRemovedLogsEvent(ch chan<- core.RemovedLogsEvent) event.Subscription {
  464. return self.scope.Track(new(event.Feed).Subscribe(ch))
  465. }