lightchain.go 21 KB

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