lightchain.go 17 KB

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