lightchain.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500
  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 bc.genesisBlock.Hash() == params.MainnetGenesisHash {
  88. // add trusted CHT
  89. WriteTrustedCht(bc.chainDb, TrustedCht{Number: 805, Root: common.HexToHash("85e4286fe0a730390245c49de8476977afdae0eb5530b277f62a52b12313d50f")})
  90. log.Info("Added trusted CHT for mainnet")
  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. func (self *LightChain) getProcInterrupt() bool {
  106. return atomic.LoadInt32(&self.procInterrupt) == 1
  107. }
  108. // Odr returns the ODR backend of the chain
  109. func (self *LightChain) Odr() OdrBackend {
  110. return self.odr
  111. }
  112. // loadLastState loads the last known chain state from the database. This method
  113. // assumes that the chain manager mutex is held.
  114. func (self *LightChain) loadLastState() error {
  115. if head := core.GetHeadHeaderHash(self.chainDb); head == (common.Hash{}) {
  116. // Corrupt or empty database, init from scratch
  117. self.Reset()
  118. } else {
  119. if header := self.GetHeaderByHash(head); header != nil {
  120. self.hc.SetCurrentHeader(header)
  121. }
  122. }
  123. // Issue a status log and return
  124. header := self.hc.CurrentHeader()
  125. headerTd := self.GetTd(header.Hash(), header.Number.Uint64())
  126. log.Info("Loaded most recent local header", "number", header.Number, "hash", header.Hash(), "td", headerTd)
  127. return nil
  128. }
  129. // SetHead rewinds the local chain to a new head. Everything above the new
  130. // head will be deleted and the new one set.
  131. func (bc *LightChain) SetHead(head uint64) {
  132. bc.mu.Lock()
  133. defer bc.mu.Unlock()
  134. bc.hc.SetHead(head, nil)
  135. bc.loadLastState()
  136. }
  137. // GasLimit returns the gas limit of the current HEAD block.
  138. func (self *LightChain) GasLimit() *big.Int {
  139. self.mu.RLock()
  140. defer self.mu.RUnlock()
  141. return self.hc.CurrentHeader().GasLimit
  142. }
  143. // LastBlockHash return the hash of the HEAD block.
  144. func (self *LightChain) LastBlockHash() common.Hash {
  145. self.mu.RLock()
  146. defer self.mu.RUnlock()
  147. return self.hc.CurrentHeader().Hash()
  148. }
  149. // Status returns status information about the current chain such as the HEAD Td,
  150. // the HEAD hash and the hash of the genesis block.
  151. func (self *LightChain) Status() (td *big.Int, currentBlock common.Hash, genesisBlock common.Hash) {
  152. self.mu.RLock()
  153. defer self.mu.RUnlock()
  154. header := self.hc.CurrentHeader()
  155. hash := header.Hash()
  156. return self.GetTd(hash, header.Number.Uint64()), hash, self.genesisBlock.Hash()
  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. // GetBody retrieves a block body (transactions and uncles) from the database
  188. // or ODR service by hash, caching it if found.
  189. func (self *LightChain) GetBody(ctx context.Context, hash common.Hash) (*types.Body, error) {
  190. // Short circuit if the body's already in the cache, retrieve otherwise
  191. if cached, ok := self.bodyCache.Get(hash); ok {
  192. body := cached.(*types.Body)
  193. return body, nil
  194. }
  195. body, err := GetBody(ctx, self.odr, hash, self.hc.GetBlockNumber(hash))
  196. if err != nil {
  197. return nil, err
  198. }
  199. // Cache the found body for next time and return
  200. self.bodyCache.Add(hash, body)
  201. return body, nil
  202. }
  203. // GetBodyRLP retrieves a block body in RLP encoding from the database or
  204. // ODR service by hash, caching it if found.
  205. func (self *LightChain) GetBodyRLP(ctx context.Context, hash common.Hash) (rlp.RawValue, error) {
  206. // Short circuit if the body's already in the cache, retrieve otherwise
  207. if cached, ok := self.bodyRLPCache.Get(hash); ok {
  208. return cached.(rlp.RawValue), nil
  209. }
  210. body, err := GetBodyRLP(ctx, self.odr, hash, self.hc.GetBlockNumber(hash))
  211. if err != nil {
  212. return nil, err
  213. }
  214. // Cache the found body for next time and return
  215. self.bodyRLPCache.Add(hash, body)
  216. return body, nil
  217. }
  218. // HasBlock checks if a block is fully present in the database or not, caching
  219. // it if present.
  220. func (bc *LightChain) HasBlock(hash common.Hash, number uint64) bool {
  221. blk, _ := bc.GetBlock(NoOdr, hash, number)
  222. return blk != nil
  223. }
  224. // GetBlock retrieves a block from the database or ODR service by hash and number,
  225. // caching it if found.
  226. func (self *LightChain) GetBlock(ctx context.Context, hash common.Hash, number uint64) (*types.Block, error) {
  227. // Short circuit if the block's already in the cache, retrieve otherwise
  228. if block, ok := self.blockCache.Get(hash); ok {
  229. return block.(*types.Block), nil
  230. }
  231. block, err := GetBlock(ctx, self.odr, hash, number)
  232. if err != nil {
  233. return nil, err
  234. }
  235. // Cache the found block for next time and return
  236. self.blockCache.Add(block.Hash(), block)
  237. return block, nil
  238. }
  239. // GetBlockByHash retrieves a block from the database or ODR service by hash,
  240. // caching it if found.
  241. func (self *LightChain) GetBlockByHash(ctx context.Context, hash common.Hash) (*types.Block, error) {
  242. return self.GetBlock(ctx, hash, self.hc.GetBlockNumber(hash))
  243. }
  244. // GetBlockByNumber retrieves a block from the database or ODR service by
  245. // number, caching it (associated with its hash) if found.
  246. func (self *LightChain) GetBlockByNumber(ctx context.Context, number uint64) (*types.Block, error) {
  247. hash, err := GetCanonicalHash(ctx, self.odr, number)
  248. if hash == (common.Hash{}) || err != nil {
  249. return nil, err
  250. }
  251. return self.GetBlock(ctx, hash, number)
  252. }
  253. // Stop stops the blockchain service. If any imports are currently in progress
  254. // it will abort them using the procInterrupt.
  255. func (bc *LightChain) Stop() {
  256. if !atomic.CompareAndSwapInt32(&bc.running, 0, 1) {
  257. return
  258. }
  259. close(bc.quit)
  260. atomic.StoreInt32(&bc.procInterrupt, 1)
  261. bc.wg.Wait()
  262. log.Info("Blockchain manager stopped")
  263. }
  264. // Rollback is designed to remove a chain of links from the database that aren't
  265. // certain enough to be valid.
  266. func (self *LightChain) Rollback(chain []common.Hash) {
  267. self.mu.Lock()
  268. defer self.mu.Unlock()
  269. for i := len(chain) - 1; i >= 0; i-- {
  270. hash := chain[i]
  271. if head := self.hc.CurrentHeader(); head.Hash() == hash {
  272. self.hc.SetCurrentHeader(self.GetHeader(head.ParentHash, head.Number.Uint64()-1))
  273. }
  274. }
  275. }
  276. // postChainEvents iterates over the events generated by a chain insertion and
  277. // posts them into the event feed.
  278. func (self *LightChain) postChainEvents(events []interface{}) {
  279. for _, event := range events {
  280. switch ev := event.(type) {
  281. case core.ChainEvent:
  282. if self.LastBlockHash() == ev.Hash {
  283. self.chainHeadFeed.Send(core.ChainHeadEvent{Block: ev.Block})
  284. }
  285. self.chainFeed.Send(ev)
  286. case core.ChainSideEvent:
  287. self.chainSideFeed.Send(ev)
  288. }
  289. }
  290. }
  291. // InsertHeaderChain attempts to insert the given header chain in to the local
  292. // chain, possibly creating a reorg. If an error is returned, it will return the
  293. // index number of the failing header as well an error describing what went wrong.
  294. //
  295. // The verify parameter can be used to fine tune whether nonce verification
  296. // should be done or not. The reason behind the optional check is because some
  297. // of the header retrieval mechanisms already need to verfy nonces, as well as
  298. // because nonces can be verified sparsely, not needing to check each.
  299. //
  300. // In the case of a light chain, InsertHeaderChain also creates and posts light
  301. // chain events when necessary.
  302. func (self *LightChain) InsertHeaderChain(chain []*types.Header, checkFreq int) (int, error) {
  303. start := time.Now()
  304. if i, err := self.hc.ValidateHeaderChain(chain, checkFreq); err != nil {
  305. return i, err
  306. }
  307. // Make sure only one thread manipulates the chain at once
  308. self.chainmu.Lock()
  309. defer func() {
  310. self.chainmu.Unlock()
  311. time.Sleep(time.Millisecond * 10) // ugly hack; do not hog chain lock in case syncing is CPU-limited by validation
  312. }()
  313. self.wg.Add(1)
  314. defer self.wg.Done()
  315. var events []interface{}
  316. whFunc := func(header *types.Header) error {
  317. self.mu.Lock()
  318. defer self.mu.Unlock()
  319. status, err := self.hc.WriteHeader(header)
  320. switch status {
  321. case core.CanonStatTy:
  322. log.Debug("Inserted new header", "number", header.Number, "hash", header.Hash())
  323. events = append(events, core.ChainEvent{Block: types.NewBlockWithHeader(header), Hash: header.Hash()})
  324. case core.SideStatTy:
  325. log.Debug("Inserted forked header", "number", header.Number, "hash", header.Hash())
  326. events = append(events, core.ChainSideEvent{Block: types.NewBlockWithHeader(header)})
  327. }
  328. return err
  329. }
  330. i, err := self.hc.InsertHeaderChain(chain, whFunc, start)
  331. go self.postChainEvents(events)
  332. return i, err
  333. }
  334. // CurrentHeader retrieves the current head header of the canonical chain. The
  335. // header is retrieved from the HeaderChain's internal cache.
  336. func (self *LightChain) CurrentHeader() *types.Header {
  337. self.mu.RLock()
  338. defer self.mu.RUnlock()
  339. return self.hc.CurrentHeader()
  340. }
  341. // GetTd retrieves a block's total difficulty in the canonical chain from the
  342. // database by hash and number, caching it if found.
  343. func (self *LightChain) GetTd(hash common.Hash, number uint64) *big.Int {
  344. return self.hc.GetTd(hash, number)
  345. }
  346. // GetTdByHash retrieves a block's total difficulty in the canonical chain from the
  347. // database by hash, caching it if found.
  348. func (self *LightChain) GetTdByHash(hash common.Hash) *big.Int {
  349. return self.hc.GetTdByHash(hash)
  350. }
  351. // GetHeader retrieves a block header from the database by hash and number,
  352. // caching it if found.
  353. func (self *LightChain) GetHeader(hash common.Hash, number uint64) *types.Header {
  354. return self.hc.GetHeader(hash, number)
  355. }
  356. // GetHeaderByHash retrieves a block header from the database by hash, caching it if
  357. // found.
  358. func (self *LightChain) GetHeaderByHash(hash common.Hash) *types.Header {
  359. return self.hc.GetHeaderByHash(hash)
  360. }
  361. // HasHeader checks if a block header is present in the database or not, caching
  362. // it if present.
  363. func (bc *LightChain) HasHeader(hash common.Hash, number uint64) bool {
  364. return bc.hc.HasHeader(hash, number)
  365. }
  366. // GetBlockHashesFromHash retrieves a number of block hashes starting at a given
  367. // hash, fetching towards the genesis block.
  368. func (self *LightChain) GetBlockHashesFromHash(hash common.Hash, max uint64) []common.Hash {
  369. return self.hc.GetBlockHashesFromHash(hash, max)
  370. }
  371. // GetHeaderByNumber retrieves a block header from the database by number,
  372. // caching it (associated with its hash) if found.
  373. func (self *LightChain) GetHeaderByNumber(number uint64) *types.Header {
  374. return self.hc.GetHeaderByNumber(number)
  375. }
  376. // GetHeaderByNumberOdr retrieves a block header from the database or network
  377. // by number, caching it (associated with its hash) if found.
  378. func (self *LightChain) GetHeaderByNumberOdr(ctx context.Context, number uint64) (*types.Header, error) {
  379. if header := self.hc.GetHeaderByNumber(number); header != nil {
  380. return header, nil
  381. }
  382. return GetHeaderByNumber(ctx, self.odr, number)
  383. }
  384. func (self *LightChain) SyncCht(ctx context.Context) bool {
  385. headNum := self.CurrentHeader().Number.Uint64()
  386. cht := GetTrustedCht(self.chainDb)
  387. if headNum+1 < cht.Number*ChtFrequency {
  388. num := cht.Number*ChtFrequency - 1
  389. header, err := GetHeaderByNumber(ctx, self.odr, num)
  390. if header != nil && err == nil {
  391. self.mu.Lock()
  392. if self.hc.CurrentHeader().Number.Uint64() < header.Number.Uint64() {
  393. self.hc.SetCurrentHeader(header)
  394. }
  395. self.mu.Unlock()
  396. return true
  397. }
  398. }
  399. return false
  400. }
  401. // LockChain locks the chain mutex for reading so that multiple canonical hashes can be
  402. // retrieved while it is guaranteed that they belong to the same version of the chain
  403. func (self *LightChain) LockChain() {
  404. self.chainmu.RLock()
  405. }
  406. // UnlockChain unlocks the chain mutex
  407. func (self *LightChain) UnlockChain() {
  408. self.chainmu.RUnlock()
  409. }
  410. // SubscribeChainEvent registers a subscription of ChainEvent.
  411. func (self *LightChain) SubscribeChainEvent(ch chan<- core.ChainEvent) event.Subscription {
  412. return self.scope.Track(self.chainFeed.Subscribe(ch))
  413. }
  414. // SubscribeChainHeadEvent registers a subscription of ChainHeadEvent.
  415. func (self *LightChain) SubscribeChainHeadEvent(ch chan<- core.ChainHeadEvent) event.Subscription {
  416. return self.scope.Track(self.chainHeadFeed.Subscribe(ch))
  417. }
  418. // SubscribeChainSideEvent registers a subscription of ChainSideEvent.
  419. func (self *LightChain) SubscribeChainSideEvent(ch chan<- core.ChainSideEvent) event.Subscription {
  420. return self.scope.Track(self.chainSideFeed.Subscribe(ch))
  421. }
  422. // SubscribeLogsEvent implements the interface of filters.Backend
  423. // LightChain does not send logs events, so return an empty subscription.
  424. func (self *LightChain) SubscribeLogsEvent(ch chan<- []*types.Log) event.Subscription {
  425. return self.scope.Track(new(event.Feed).Subscribe(ch))
  426. }
  427. // SubscribeRemovedLogsEvent implements the interface of filters.Backend
  428. // LightChain does not send core.RemovedLogsEvent, so return an empty subscription.
  429. func (self *LightChain) SubscribeRemovedLogsEvent(ch chan<- core.RemovedLogsEvent) event.Subscription {
  430. return self.scope.Track(new(event.Feed).Subscribe(ch))
  431. }