lightchain.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510
  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. return nil
  153. }
  154. // SetHead rewinds the local chain to a new head. Everything above the new
  155. // head will be deleted and the new one set.
  156. func (bc *LightChain) SetHead(head uint64) {
  157. bc.mu.Lock()
  158. defer bc.mu.Unlock()
  159. bc.hc.SetHead(head, nil)
  160. bc.loadLastState()
  161. }
  162. // GasLimit returns the gas limit of the current HEAD block.
  163. func (self *LightChain) GasLimit() *big.Int {
  164. self.mu.RLock()
  165. defer self.mu.RUnlock()
  166. return self.hc.CurrentHeader().GasLimit
  167. }
  168. // LastBlockHash return the hash of the HEAD block.
  169. func (self *LightChain) LastBlockHash() common.Hash {
  170. self.mu.RLock()
  171. defer self.mu.RUnlock()
  172. return self.hc.CurrentHeader().Hash()
  173. }
  174. // Status returns status information about the current chain such as the HEAD Td,
  175. // the HEAD hash and the hash of the genesis block.
  176. func (self *LightChain) Status() (td *big.Int, currentBlock common.Hash, genesisBlock common.Hash) {
  177. self.mu.RLock()
  178. defer self.mu.RUnlock()
  179. header := self.hc.CurrentHeader()
  180. hash := header.Hash()
  181. return self.GetTd(hash, header.Number.Uint64()), hash, self.genesisBlock.Hash()
  182. }
  183. // SetValidator sets the validator which is used to validate incoming headers.
  184. func (self *LightChain) SetValidator(validator core.HeaderValidator) {
  185. self.procmu.Lock()
  186. defer self.procmu.Unlock()
  187. self.validator = validator
  188. }
  189. // Validator returns the current header validator.
  190. func (self *LightChain) Validator() core.HeaderValidator {
  191. self.procmu.RLock()
  192. defer self.procmu.RUnlock()
  193. return self.validator
  194. }
  195. // State returns a new mutable state based on the current HEAD block.
  196. func (self *LightChain) State() *LightState {
  197. return NewLightState(StateTrieID(self.hc.CurrentHeader()), self.odr)
  198. }
  199. // Reset purges the entire blockchain, restoring it to its genesis state.
  200. func (bc *LightChain) Reset() {
  201. bc.ResetWithGenesisBlock(bc.genesisBlock)
  202. }
  203. // ResetWithGenesisBlock purges the entire blockchain, restoring it to the
  204. // specified genesis state.
  205. func (bc *LightChain) ResetWithGenesisBlock(genesis *types.Block) {
  206. // Dump the entire block chain and purge the caches
  207. bc.SetHead(0)
  208. bc.mu.Lock()
  209. defer bc.mu.Unlock()
  210. // Prepare the genesis block and reinitialise the chain
  211. if err := core.WriteTd(bc.chainDb, genesis.Hash(), genesis.NumberU64(), genesis.Difficulty()); err != nil {
  212. log.Crit("Failed to write genesis block TD", "err", err)
  213. }
  214. if err := core.WriteBlock(bc.chainDb, genesis); err != nil {
  215. log.Crit("Failed to write genesis block", "err", err)
  216. }
  217. bc.genesisBlock = genesis
  218. bc.hc.SetGenesis(bc.genesisBlock.Header())
  219. bc.hc.SetCurrentHeader(bc.genesisBlock.Header())
  220. }
  221. // Accessors
  222. // Genesis returns the genesis block
  223. func (bc *LightChain) Genesis() *types.Block {
  224. return bc.genesisBlock
  225. }
  226. // GetBody retrieves a block body (transactions and uncles) from the database
  227. // or ODR service by hash, caching it if found.
  228. func (self *LightChain) GetBody(ctx context.Context, hash common.Hash) (*types.Body, error) {
  229. // Short circuit if the body's already in the cache, retrieve otherwise
  230. if cached, ok := self.bodyCache.Get(hash); ok {
  231. body := cached.(*types.Body)
  232. return body, nil
  233. }
  234. body, err := GetBody(ctx, self.odr, hash, self.hc.GetBlockNumber(hash))
  235. if err != nil {
  236. return nil, err
  237. }
  238. // Cache the found body for next time and return
  239. self.bodyCache.Add(hash, body)
  240. return body, nil
  241. }
  242. // GetBodyRLP retrieves a block body in RLP encoding from the database or
  243. // ODR service by hash, caching it if found.
  244. func (self *LightChain) GetBodyRLP(ctx context.Context, hash common.Hash) (rlp.RawValue, error) {
  245. // Short circuit if the body's already in the cache, retrieve otherwise
  246. if cached, ok := self.bodyRLPCache.Get(hash); ok {
  247. return cached.(rlp.RawValue), nil
  248. }
  249. body, err := GetBodyRLP(ctx, self.odr, hash, self.hc.GetBlockNumber(hash))
  250. if err != nil {
  251. return nil, err
  252. }
  253. // Cache the found body for next time and return
  254. self.bodyRLPCache.Add(hash, body)
  255. return body, nil
  256. }
  257. // HasBlock checks if a block is fully present in the database or not, caching
  258. // it if present.
  259. func (bc *LightChain) HasBlock(hash common.Hash) bool {
  260. blk, _ := bc.GetBlockByHash(NoOdr, hash)
  261. return blk != nil
  262. }
  263. // GetBlock retrieves a block from the database or ODR service by hash and number,
  264. // caching it if found.
  265. func (self *LightChain) GetBlock(ctx context.Context, hash common.Hash, number uint64) (*types.Block, error) {
  266. // Short circuit if the block's already in the cache, retrieve otherwise
  267. if block, ok := self.blockCache.Get(hash); ok {
  268. return block.(*types.Block), nil
  269. }
  270. block, err := GetBlock(ctx, self.odr, hash, number)
  271. if err != nil {
  272. return nil, err
  273. }
  274. // Cache the found block for next time and return
  275. self.blockCache.Add(block.Hash(), block)
  276. return block, nil
  277. }
  278. // GetBlockByHash retrieves a block from the database or ODR service by hash,
  279. // caching it if found.
  280. func (self *LightChain) GetBlockByHash(ctx context.Context, hash common.Hash) (*types.Block, error) {
  281. return self.GetBlock(ctx, hash, self.hc.GetBlockNumber(hash))
  282. }
  283. // GetBlockByNumber retrieves a block from the database or ODR service by
  284. // number, caching it (associated with its hash) if found.
  285. func (self *LightChain) GetBlockByNumber(ctx context.Context, number uint64) (*types.Block, error) {
  286. hash, err := GetCanonicalHash(ctx, self.odr, number)
  287. if hash == (common.Hash{}) || err != nil {
  288. return nil, err
  289. }
  290. return self.GetBlock(ctx, hash, number)
  291. }
  292. // Stop stops the blockchain service. If any imports are currently in progress
  293. // it will abort them using the procInterrupt.
  294. func (bc *LightChain) Stop() {
  295. if !atomic.CompareAndSwapInt32(&bc.running, 0, 1) {
  296. return
  297. }
  298. close(bc.quit)
  299. atomic.StoreInt32(&bc.procInterrupt, 1)
  300. bc.wg.Wait()
  301. log.Info("Blockchain manager stopped")
  302. }
  303. // Rollback is designed to remove a chain of links from the database that aren't
  304. // certain enough to be valid.
  305. func (self *LightChain) Rollback(chain []common.Hash) {
  306. self.mu.Lock()
  307. defer self.mu.Unlock()
  308. for i := len(chain) - 1; i >= 0; i-- {
  309. hash := chain[i]
  310. if head := self.hc.CurrentHeader(); head.Hash() == hash {
  311. self.hc.SetCurrentHeader(self.GetHeader(head.ParentHash, head.Number.Uint64()-1))
  312. }
  313. }
  314. }
  315. // postChainEvents iterates over the events generated by a chain insertion and
  316. // posts them into the event mux.
  317. func (self *LightChain) postChainEvents(events []interface{}) {
  318. for _, event := range events {
  319. if event, ok := event.(core.ChainEvent); ok {
  320. if self.LastBlockHash() == event.Hash {
  321. self.eventMux.Post(core.ChainHeadEvent{Block: event.Block})
  322. }
  323. }
  324. // Fire the insertion events individually too
  325. self.eventMux.Post(event)
  326. }
  327. }
  328. // InsertHeaderChain attempts to insert the given header chain in to the local
  329. // chain, possibly creating a reorg. If an error is returned, it will return the
  330. // index number of the failing header as well an error describing what went wrong.
  331. //
  332. // The verify parameter can be used to fine tune whether nonce verification
  333. // should be done or not. The reason behind the optional check is because some
  334. // of the header retrieval mechanisms already need to verfy nonces, as well as
  335. // because nonces can be verified sparsely, not needing to check each.
  336. //
  337. // In the case of a light chain, InsertHeaderChain also creates and posts light
  338. // chain events when necessary.
  339. func (self *LightChain) InsertHeaderChain(chain []*types.Header, checkFreq int) (int, error) {
  340. // Make sure only one thread manipulates the chain at once
  341. self.chainmu.Lock()
  342. defer self.chainmu.Unlock()
  343. self.wg.Add(1)
  344. defer self.wg.Done()
  345. var events []interface{}
  346. whFunc := func(header *types.Header) error {
  347. self.mu.Lock()
  348. defer self.mu.Unlock()
  349. status, err := self.hc.WriteHeader(header)
  350. switch status {
  351. case core.CanonStatTy:
  352. log.Debug("Inserted new header", "number", header.Number, "hash", header.Hash())
  353. events = append(events, core.ChainEvent{Block: types.NewBlockWithHeader(header), Hash: header.Hash()})
  354. case core.SideStatTy:
  355. log.Debug("Inserted forked header", "number", header.Number, "hash", header.Hash())
  356. events = append(events, core.ChainSideEvent{Block: types.NewBlockWithHeader(header)})
  357. case core.SplitStatTy:
  358. events = append(events, core.ChainSplitEvent{Block: types.NewBlockWithHeader(header)})
  359. }
  360. return err
  361. }
  362. i, err := self.hc.InsertHeaderChain(chain, checkFreq, whFunc)
  363. go self.postChainEvents(events)
  364. return i, err
  365. }
  366. // CurrentHeader retrieves the current head header of the canonical chain. The
  367. // header is retrieved from the HeaderChain's internal cache.
  368. func (self *LightChain) CurrentHeader() *types.Header {
  369. self.mu.RLock()
  370. defer self.mu.RUnlock()
  371. return self.hc.CurrentHeader()
  372. }
  373. // GetTd retrieves a block's total difficulty in the canonical chain from the
  374. // database by hash and number, caching it if found.
  375. func (self *LightChain) GetTd(hash common.Hash, number uint64) *big.Int {
  376. return self.hc.GetTd(hash, number)
  377. }
  378. // GetTdByHash retrieves a block's total difficulty in the canonical chain from the
  379. // database by hash, caching it if found.
  380. func (self *LightChain) GetTdByHash(hash common.Hash) *big.Int {
  381. return self.hc.GetTdByHash(hash)
  382. }
  383. // GetHeader retrieves a block header from the database by hash and number,
  384. // caching it if found.
  385. func (self *LightChain) GetHeader(hash common.Hash, number uint64) *types.Header {
  386. return self.hc.GetHeader(hash, number)
  387. }
  388. // GetHeaderByHash retrieves a block header from the database by hash, caching it if
  389. // found.
  390. func (self *LightChain) GetHeaderByHash(hash common.Hash) *types.Header {
  391. return self.hc.GetHeaderByHash(hash)
  392. }
  393. // HasHeader checks if a block header is present in the database or not, caching
  394. // it if present.
  395. func (bc *LightChain) HasHeader(hash common.Hash) bool {
  396. return bc.hc.HasHeader(hash)
  397. }
  398. // GetBlockHashesFromHash retrieves a number of block hashes starting at a given
  399. // hash, fetching towards the genesis block.
  400. func (self *LightChain) GetBlockHashesFromHash(hash common.Hash, max uint64) []common.Hash {
  401. return self.hc.GetBlockHashesFromHash(hash, max)
  402. }
  403. // GetHeaderByNumber retrieves a block header from the database by number,
  404. // caching it (associated with its hash) if found.
  405. func (self *LightChain) GetHeaderByNumber(number uint64) *types.Header {
  406. return self.hc.GetHeaderByNumber(number)
  407. }
  408. // GetHeaderByNumberOdr retrieves a block header from the database or network
  409. // by number, caching it (associated with its hash) if found.
  410. func (self *LightChain) GetHeaderByNumberOdr(ctx context.Context, number uint64) (*types.Header, error) {
  411. if header := self.hc.GetHeaderByNumber(number); header != nil {
  412. return header, nil
  413. }
  414. return GetHeaderByNumber(ctx, self.odr, number)
  415. }
  416. func (self *LightChain) SyncCht(ctx context.Context) bool {
  417. headNum := self.CurrentHeader().Number.Uint64()
  418. cht := GetTrustedCht(self.chainDb)
  419. if headNum+1 < cht.Number*ChtFrequency {
  420. num := cht.Number*ChtFrequency - 1
  421. header, err := GetHeaderByNumber(ctx, self.odr, num)
  422. if header != nil && err == nil {
  423. self.mu.Lock()
  424. if self.hc.CurrentHeader().Number.Uint64() < header.Number.Uint64() {
  425. self.hc.SetCurrentHeader(header)
  426. }
  427. self.mu.Unlock()
  428. return true
  429. }
  430. }
  431. return false
  432. }
  433. // LockChain locks the chain mutex for reading so that multiple canonical hashes can be
  434. // retrieved while it is guaranteed that they belong to the same version of the chain
  435. func (self *LightChain) LockChain() {
  436. self.chainmu.RLock()
  437. }
  438. // UnlockChain unlocks the chain mutex
  439. func (self *LightChain) UnlockChain() {
  440. self.chainmu.RUnlock()
  441. }