lightchain.go 17 KB

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