lightchain.go 16 KB

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