lightchain.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520
  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. "math/big"
  20. "sync"
  21. "sync/atomic"
  22. "time"
  23. "github.com/ethereum/go-ethereum/common"
  24. "github.com/ethereum/go-ethereum/consensus"
  25. "github.com/ethereum/go-ethereum/core"
  26. "github.com/ethereum/go-ethereum/core/types"
  27. "github.com/ethereum/go-ethereum/ethdb"
  28. "github.com/ethereum/go-ethereum/event"
  29. "github.com/ethereum/go-ethereum/log"
  30. "github.com/ethereum/go-ethereum/params"
  31. "github.com/ethereum/go-ethereum/rlp"
  32. "github.com/hashicorp/golang-lru"
  33. )
  34. var (
  35. bodyCacheLimit = 256
  36. blockCacheLimit = 256
  37. )
  38. // LightChain represents a canonical chain that by default only handles block
  39. // headers, downloading block bodies and receipts on demand through an ODR
  40. // interface. It only does header validation during chain insertion.
  41. type LightChain struct {
  42. hc *core.HeaderChain
  43. chainDb ethdb.Database
  44. odr OdrBackend
  45. chainFeed event.Feed
  46. chainSideFeed event.Feed
  47. chainHeadFeed event.Feed
  48. scope event.SubscriptionScope
  49. genesisBlock *types.Block
  50. mu sync.RWMutex
  51. chainmu sync.RWMutex
  52. bodyCache *lru.Cache // Cache for the most recent block bodies
  53. bodyRLPCache *lru.Cache // Cache for the most recent block bodies in RLP encoded format
  54. blockCache *lru.Cache // Cache for the most recent entire blocks
  55. quit chan struct{}
  56. running int32 // running must be called automically
  57. // procInterrupt must be atomically called
  58. procInterrupt int32 // interrupt signaler for block processing
  59. wg sync.WaitGroup
  60. engine consensus.Engine
  61. }
  62. // NewLightChain returns a fully initialised light chain using information
  63. // available in the database. It initialises the default Ethereum header
  64. // validator.
  65. func NewLightChain(odr OdrBackend, config *params.ChainConfig, engine consensus.Engine) (*LightChain, error) {
  66. bodyCache, _ := lru.New(bodyCacheLimit)
  67. bodyRLPCache, _ := lru.New(bodyCacheLimit)
  68. blockCache, _ := lru.New(blockCacheLimit)
  69. bc := &LightChain{
  70. chainDb: odr.Database(),
  71. odr: odr,
  72. quit: make(chan struct{}),
  73. bodyCache: bodyCache,
  74. bodyRLPCache: bodyRLPCache,
  75. blockCache: blockCache,
  76. engine: engine,
  77. }
  78. var err error
  79. bc.hc, err = core.NewHeaderChain(odr.Database(), config, bc.engine, bc.getProcInterrupt)
  80. if err != nil {
  81. return nil, err
  82. }
  83. bc.genesisBlock, _ = bc.GetBlockByNumber(NoOdr, 0)
  84. if bc.genesisBlock == nil {
  85. return nil, core.ErrNoGenesis
  86. }
  87. if cp, ok := trustedCheckpoints[bc.genesisBlock.Hash()]; ok {
  88. bc.addTrustedCheckpoint(cp)
  89. }
  90. if err := bc.loadLastState(); err != nil {
  91. return nil, err
  92. }
  93. // Check the current state of the block hashes and make sure that we do not have any of the bad blocks in our chain
  94. for hash := range core.BadHashes {
  95. if header := bc.GetHeaderByHash(hash); header != nil {
  96. log.Error("Found bad hash, rewinding chain", "number", header.Number, "hash", header.ParentHash)
  97. bc.SetHead(header.Number.Uint64() - 1)
  98. log.Error("Chain rewind was successful, resuming normal operation")
  99. }
  100. }
  101. return bc, nil
  102. }
  103. // addTrustedCheckpoint adds a trusted checkpoint to the blockchain
  104. func (self *LightChain) addTrustedCheckpoint(cp trustedCheckpoint) {
  105. if self.odr.ChtIndexer() != nil {
  106. StoreChtRoot(self.chainDb, cp.sectionIdx, cp.sectionHead, cp.chtRoot)
  107. self.odr.ChtIndexer().AddKnownSectionHead(cp.sectionIdx, cp.sectionHead)
  108. }
  109. if self.odr.BloomTrieIndexer() != nil {
  110. StoreBloomTrieRoot(self.chainDb, cp.sectionIdx, cp.sectionHead, cp.bloomTrieRoot)
  111. self.odr.BloomTrieIndexer().AddKnownSectionHead(cp.sectionIdx, cp.sectionHead)
  112. }
  113. if self.odr.BloomIndexer() != nil {
  114. self.odr.BloomIndexer().AddKnownSectionHead(cp.sectionIdx, cp.sectionHead)
  115. }
  116. log.Info("Added trusted checkpoint", "chain name", cp.name)
  117. }
  118. func (self *LightChain) getProcInterrupt() bool {
  119. return atomic.LoadInt32(&self.procInterrupt) == 1
  120. }
  121. // Odr returns the ODR backend of the chain
  122. func (self *LightChain) Odr() OdrBackend {
  123. return self.odr
  124. }
  125. // loadLastState loads the last known chain state from the database. This method
  126. // assumes that the chain manager mutex is held.
  127. func (self *LightChain) loadLastState() error {
  128. if head := core.GetHeadHeaderHash(self.chainDb); head == (common.Hash{}) {
  129. // Corrupt or empty database, init from scratch
  130. self.Reset()
  131. } else {
  132. if header := self.GetHeaderByHash(head); header != nil {
  133. self.hc.SetCurrentHeader(header)
  134. }
  135. }
  136. // Issue a status log and return
  137. header := self.hc.CurrentHeader()
  138. headerTd := self.GetTd(header.Hash(), header.Number.Uint64())
  139. log.Info("Loaded most recent local header", "number", header.Number, "hash", header.Hash(), "td", headerTd)
  140. return nil
  141. }
  142. // SetHead rewinds the local chain to a new head. Everything above the new
  143. // head will be deleted and the new one set.
  144. func (bc *LightChain) SetHead(head uint64) {
  145. bc.mu.Lock()
  146. defer bc.mu.Unlock()
  147. bc.hc.SetHead(head, nil)
  148. bc.loadLastState()
  149. }
  150. // GasLimit returns the gas limit of the current HEAD block.
  151. func (self *LightChain) GasLimit() uint64 {
  152. self.mu.RLock()
  153. defer self.mu.RUnlock()
  154. return self.hc.CurrentHeader().GasLimit
  155. }
  156. // LastBlockHash return the hash of the HEAD block.
  157. func (self *LightChain) LastBlockHash() common.Hash {
  158. self.mu.RLock()
  159. defer self.mu.RUnlock()
  160. return self.hc.CurrentHeader().Hash()
  161. }
  162. // Status returns status information about the current chain such as the HEAD Td,
  163. // the HEAD hash and the hash of the genesis block.
  164. func (self *LightChain) Status() (td *big.Int, currentBlock common.Hash, genesisBlock common.Hash) {
  165. self.mu.RLock()
  166. defer self.mu.RUnlock()
  167. header := self.hc.CurrentHeader()
  168. hash := header.Hash()
  169. return self.GetTd(hash, header.Number.Uint64()), hash, self.genesisBlock.Hash()
  170. }
  171. // Reset purges the entire blockchain, restoring it to its genesis state.
  172. func (bc *LightChain) Reset() {
  173. bc.ResetWithGenesisBlock(bc.genesisBlock)
  174. }
  175. // ResetWithGenesisBlock purges the entire blockchain, restoring it to the
  176. // specified genesis state.
  177. func (bc *LightChain) ResetWithGenesisBlock(genesis *types.Block) {
  178. // Dump the entire block chain and purge the caches
  179. bc.SetHead(0)
  180. bc.mu.Lock()
  181. defer bc.mu.Unlock()
  182. // Prepare the genesis block and reinitialise the chain
  183. if err := core.WriteTd(bc.chainDb, genesis.Hash(), genesis.NumberU64(), genesis.Difficulty()); err != nil {
  184. log.Crit("Failed to write genesis block TD", "err", err)
  185. }
  186. if err := core.WriteBlock(bc.chainDb, genesis); err != nil {
  187. log.Crit("Failed to write genesis block", "err", err)
  188. }
  189. bc.genesisBlock = genesis
  190. bc.hc.SetGenesis(bc.genesisBlock.Header())
  191. bc.hc.SetCurrentHeader(bc.genesisBlock.Header())
  192. }
  193. // Accessors
  194. // Engine retrieves the light chain's consensus engine.
  195. func (bc *LightChain) Engine() consensus.Engine { return bc.engine }
  196. // Genesis returns the genesis block
  197. func (bc *LightChain) Genesis() *types.Block {
  198. return bc.genesisBlock
  199. }
  200. // GetBody retrieves a block body (transactions and uncles) from the database
  201. // or ODR service by hash, caching it if found.
  202. func (self *LightChain) GetBody(ctx context.Context, hash common.Hash) (*types.Body, error) {
  203. // Short circuit if the body's already in the cache, retrieve otherwise
  204. if cached, ok := self.bodyCache.Get(hash); ok {
  205. body := cached.(*types.Body)
  206. return body, nil
  207. }
  208. body, err := GetBody(ctx, self.odr, hash, self.hc.GetBlockNumber(hash))
  209. if err != nil {
  210. return nil, err
  211. }
  212. // Cache the found body for next time and return
  213. self.bodyCache.Add(hash, body)
  214. return body, nil
  215. }
  216. // GetBodyRLP retrieves a block body in RLP encoding from the database or
  217. // ODR service by hash, caching it if found.
  218. func (self *LightChain) GetBodyRLP(ctx context.Context, hash common.Hash) (rlp.RawValue, error) {
  219. // Short circuit if the body's already in the cache, retrieve otherwise
  220. if cached, ok := self.bodyRLPCache.Get(hash); ok {
  221. return cached.(rlp.RawValue), nil
  222. }
  223. body, err := GetBodyRLP(ctx, self.odr, hash, self.hc.GetBlockNumber(hash))
  224. if err != nil {
  225. return nil, err
  226. }
  227. // Cache the found body for next time and return
  228. self.bodyRLPCache.Add(hash, body)
  229. return body, nil
  230. }
  231. // HasBlock checks if a block is fully present in the database or not, caching
  232. // it if present.
  233. func (bc *LightChain) HasBlock(hash common.Hash, number uint64) bool {
  234. blk, _ := bc.GetBlock(NoOdr, hash, number)
  235. return blk != nil
  236. }
  237. // GetBlock retrieves a block from the database or ODR service by hash and number,
  238. // caching it if found.
  239. func (self *LightChain) GetBlock(ctx context.Context, hash common.Hash, number uint64) (*types.Block, error) {
  240. // Short circuit if the block's already in the cache, retrieve otherwise
  241. if block, ok := self.blockCache.Get(hash); ok {
  242. return block.(*types.Block), nil
  243. }
  244. block, err := GetBlock(ctx, self.odr, hash, number)
  245. if err != nil {
  246. return nil, err
  247. }
  248. // Cache the found block for next time and return
  249. self.blockCache.Add(block.Hash(), block)
  250. return block, nil
  251. }
  252. // GetBlockByHash retrieves a block from the database or ODR service by hash,
  253. // caching it if found.
  254. func (self *LightChain) GetBlockByHash(ctx context.Context, hash common.Hash) (*types.Block, error) {
  255. return self.GetBlock(ctx, hash, self.hc.GetBlockNumber(hash))
  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.LastBlockHash() == 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. 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, number uint64) bool {
  377. return bc.hc.HasHeader(hash, number)
  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. // Config retrieves the header chain's chain configuration.
  398. func (self *LightChain) Config() *params.ChainConfig { return self.hc.Config() }
  399. func (self *LightChain) SyncCht(ctx context.Context) bool {
  400. if self.odr.ChtIndexer() == nil {
  401. return false
  402. }
  403. headNum := self.CurrentHeader().Number.Uint64()
  404. chtCount, _, _ := self.odr.ChtIndexer().Sections()
  405. if headNum+1 < chtCount*ChtFrequency {
  406. num := chtCount*ChtFrequency - 1
  407. header, err := GetHeaderByNumber(ctx, self.odr, num)
  408. if header != nil && err == nil {
  409. self.mu.Lock()
  410. if self.hc.CurrentHeader().Number.Uint64() < header.Number.Uint64() {
  411. self.hc.SetCurrentHeader(header)
  412. }
  413. self.mu.Unlock()
  414. return true
  415. }
  416. }
  417. return false
  418. }
  419. // LockChain locks the chain mutex for reading so that multiple canonical hashes can be
  420. // retrieved while it is guaranteed that they belong to the same version of the chain
  421. func (self *LightChain) LockChain() {
  422. self.chainmu.RLock()
  423. }
  424. // UnlockChain unlocks the chain mutex
  425. func (self *LightChain) UnlockChain() {
  426. self.chainmu.RUnlock()
  427. }
  428. // SubscribeChainEvent registers a subscription of ChainEvent.
  429. func (self *LightChain) SubscribeChainEvent(ch chan<- core.ChainEvent) event.Subscription {
  430. return self.scope.Track(self.chainFeed.Subscribe(ch))
  431. }
  432. // SubscribeChainHeadEvent registers a subscription of ChainHeadEvent.
  433. func (self *LightChain) SubscribeChainHeadEvent(ch chan<- core.ChainHeadEvent) event.Subscription {
  434. return self.scope.Track(self.chainHeadFeed.Subscribe(ch))
  435. }
  436. // SubscribeChainSideEvent registers a subscription of ChainSideEvent.
  437. func (self *LightChain) SubscribeChainSideEvent(ch chan<- core.ChainSideEvent) event.Subscription {
  438. return self.scope.Track(self.chainSideFeed.Subscribe(ch))
  439. }
  440. // SubscribeLogsEvent implements the interface of filters.Backend
  441. // LightChain does not send logs events, so return an empty subscription.
  442. func (self *LightChain) SubscribeLogsEvent(ch chan<- []*types.Log) event.Subscription {
  443. return self.scope.Track(new(event.Feed).Subscribe(ch))
  444. }
  445. // SubscribeRemovedLogsEvent implements the interface of filters.Backend
  446. // LightChain does not send core.RemovedLogsEvent, so return an empty subscription.
  447. func (self *LightChain) SubscribeRemovedLogsEvent(ch chan<- core.RemovedLogsEvent) event.Subscription {
  448. return self.scope.Track(new(event.Feed).Subscribe(ch))
  449. }