lightchain.go 17 KB

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