lightchain.go 21 KB

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