lightchain.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507
  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. "time"
  22. "github.com/ethereum/go-ethereum/common"
  23. "github.com/ethereum/go-ethereum/core"
  24. "github.com/ethereum/go-ethereum/core/types"
  25. "github.com/ethereum/go-ethereum/ethdb"
  26. "github.com/ethereum/go-ethereum/event"
  27. "github.com/ethereum/go-ethereum/logger"
  28. "github.com/ethereum/go-ethereum/logger/glog"
  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. "golang.org/x/net/context"
  34. )
  35. var (
  36. bodyCacheLimit = 256
  37. blockCacheLimit = 256
  38. )
  39. // LightChain represents a canonical chain that by default only handles block
  40. // headers, downloading block bodies and receipts on demand through an ODR
  41. // interface. It only does header validation during chain insertion.
  42. type LightChain struct {
  43. hc *core.HeaderChain
  44. chainDb ethdb.Database
  45. odr OdrBackend
  46. eventMux *event.TypeMux
  47. genesisBlock *types.Block
  48. mu sync.RWMutex
  49. chainmu sync.RWMutex
  50. procmu sync.RWMutex
  51. bodyCache *lru.Cache // Cache for the most recent block bodies
  52. bodyRLPCache *lru.Cache // Cache for the most recent block bodies in RLP encoded format
  53. blockCache *lru.Cache // Cache for the most recent entire blocks
  54. quit chan struct{}
  55. running int32 // running must be called automically
  56. // procInterrupt must be atomically called
  57. procInterrupt int32 // interrupt signaler for block processing
  58. wg sync.WaitGroup
  59. pow pow.PoW
  60. validator core.HeaderValidator
  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, pow pow.PoW, mux *event.TypeMux) (*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. eventMux: mux,
  73. quit: make(chan struct{}),
  74. bodyCache: bodyCache,
  75. bodyRLPCache: bodyRLPCache,
  76. blockCache: blockCache,
  77. pow: pow,
  78. }
  79. var err error
  80. bc.hc, err = core.NewHeaderChain(odr.Database(), config, bc.Validator, bc.getProcInterrupt)
  81. bc.SetValidator(core.NewHeaderValidator(config, bc.hc, pow))
  82. if err != nil {
  83. return nil, err
  84. }
  85. bc.genesisBlock, _ = bc.GetBlockByNumber(NoOdr, 0)
  86. if bc.genesisBlock == nil {
  87. bc.genesisBlock, err = core.WriteDefaultGenesisBlock(odr.Database())
  88. if err != nil {
  89. return nil, err
  90. }
  91. glog.V(logger.Info).Infoln("WARNING: Wrote default ethereum genesis block")
  92. }
  93. 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}) {
  94. // add trusted CHT
  95. if config.DAOForkSupport {
  96. WriteTrustedCht(bc.chainDb, TrustedCht{
  97. Number: 637,
  98. Root: common.HexToHash("01e408d9b1942f05dba1a879f3eaafe34d219edaeb8223fecf1244cc023d3e23"),
  99. })
  100. } else {
  101. WriteTrustedCht(bc.chainDb, TrustedCht{
  102. Number: 523,
  103. Root: common.HexToHash("c035076523faf514038f619715de404a65398c51899b5dccca9c05b00bc79315"),
  104. })
  105. }
  106. glog.V(logger.Info).Infoln("Added trusted CHT for mainnet")
  107. } else {
  108. 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}) {
  109. // add trusted CHT for testnet
  110. WriteTrustedCht(bc.chainDb, TrustedCht{
  111. Number: 452,
  112. Root: common.HexToHash("511da2c88e32b14cf4a4e62f7fcbb297139faebc260a4ab5eb43cce6edcba324"),
  113. })
  114. glog.V(logger.Info).Infoln("Added trusted CHT for testnet")
  115. } else {
  116. DeleteTrustedCht(bc.chainDb)
  117. }
  118. }
  119. if err := bc.loadLastState(); err != nil {
  120. return nil, err
  121. }
  122. // Check the current state of the block hashes and make sure that we do not have any of the bad blocks in our chain
  123. for hash, _ := range core.BadHashes {
  124. if header := bc.GetHeaderByHash(hash); header != nil {
  125. glog.V(logger.Error).Infof("Found bad hash, rewinding chain to block #%d [%x…]", header.Number, header.ParentHash[:4])
  126. bc.SetHead(header.Number.Uint64() - 1)
  127. glog.V(logger.Error).Infoln("Chain rewind was successful, resuming normal operation")
  128. }
  129. }
  130. return bc, nil
  131. }
  132. func (self *LightChain) getProcInterrupt() bool {
  133. return atomic.LoadInt32(&self.procInterrupt) == 1
  134. }
  135. // Odr returns the ODR backend of the chain
  136. func (self *LightChain) Odr() OdrBackend {
  137. return self.odr
  138. }
  139. // loadLastState loads the last known chain state from the database. This method
  140. // assumes that the chain manager mutex is held.
  141. func (self *LightChain) loadLastState() error {
  142. if head := core.GetHeadHeaderHash(self.chainDb); head == (common.Hash{}) {
  143. // Corrupt or empty database, init from scratch
  144. self.Reset()
  145. } else {
  146. if header := self.GetHeaderByHash(head); header != nil {
  147. self.hc.SetCurrentHeader(header)
  148. }
  149. }
  150. // Issue a status log and return
  151. header := self.hc.CurrentHeader()
  152. headerTd := self.GetTd(header.Hash(), header.Number.Uint64())
  153. glog.V(logger.Info).Infof("Last header: #%d [%x…] TD=%v", self.hc.CurrentHeader().Number, self.hc.CurrentHeader().Hash().Bytes()[:4], headerTd)
  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. glog.Fatalf("failed to write genesis block TD: %v", err)
  215. }
  216. if err := core.WriteBlock(bc.chainDb, genesis); err != nil {
  217. glog.Fatalf("failed to write genesis block: %v", 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. glog.V(logger.Info).Infoln("Chain 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. if glog.V(logger.Debug) {
  355. glog.Infof("[%v] inserted header #%d (%x...).\n", time.Now().UnixNano(), header.Number, header.Hash().Bytes()[0:4])
  356. }
  357. events = append(events, core.ChainEvent{Block: types.NewBlockWithHeader(header), Hash: header.Hash()})
  358. case core.SideStatTy:
  359. if glog.V(logger.Detail) {
  360. glog.Infof("inserted forked header #%d (TD=%v) (%x...).\n", header.Number, header.Difficulty, header.Hash().Bytes()[0:4])
  361. }
  362. events = append(events, core.ChainSideEvent{Block: types.NewBlockWithHeader(header)})
  363. case core.SplitStatTy:
  364. events = append(events, core.ChainSplitEvent{Block: types.NewBlockWithHeader(header)})
  365. }
  366. return err
  367. }
  368. i, err := self.hc.InsertHeaderChain(chain, checkFreq, whFunc)
  369. go self.postChainEvents(events)
  370. return i, err
  371. }
  372. // CurrentHeader retrieves the current head header of the canonical chain. The
  373. // header is retrieved from the HeaderChain's internal cache.
  374. func (self *LightChain) CurrentHeader() *types.Header {
  375. self.mu.RLock()
  376. defer self.mu.RUnlock()
  377. return self.hc.CurrentHeader()
  378. }
  379. // GetTd retrieves a block's total difficulty in the canonical chain from the
  380. // database by hash and number, caching it if found.
  381. func (self *LightChain) GetTd(hash common.Hash, number uint64) *big.Int {
  382. return self.hc.GetTd(hash, number)
  383. }
  384. // GetTdByHash retrieves a block's total difficulty in the canonical chain from the
  385. // database by hash, caching it if found.
  386. func (self *LightChain) GetTdByHash(hash common.Hash) *big.Int {
  387. return self.hc.GetTdByHash(hash)
  388. }
  389. // GetHeader retrieves a block header from the database by hash and number,
  390. // caching it if found.
  391. func (self *LightChain) GetHeader(hash common.Hash, number uint64) *types.Header {
  392. return self.hc.GetHeader(hash, number)
  393. }
  394. // GetHeaderByHash retrieves a block header from the database by hash, caching it if
  395. // found.
  396. func (self *LightChain) GetHeaderByHash(hash common.Hash) *types.Header {
  397. return self.hc.GetHeaderByHash(hash)
  398. }
  399. // HasHeader checks if a block header is present in the database or not, caching
  400. // it if present.
  401. func (bc *LightChain) HasHeader(hash common.Hash) bool {
  402. return bc.hc.HasHeader(hash)
  403. }
  404. // GetBlockHashesFromHash retrieves a number of block hashes starting at a given
  405. // hash, fetching towards the genesis block.
  406. func (self *LightChain) GetBlockHashesFromHash(hash common.Hash, max uint64) []common.Hash {
  407. return self.hc.GetBlockHashesFromHash(hash, max)
  408. }
  409. // GetHeaderByNumber retrieves a block header from the database by number,
  410. // caching it (associated with its hash) if found.
  411. func (self *LightChain) GetHeaderByNumber(number uint64) *types.Header {
  412. return self.hc.GetHeaderByNumber(number)
  413. }
  414. // GetHeaderByNumberOdr retrieves a block header from the database or network
  415. // by number, caching it (associated with its hash) if found.
  416. func (self *LightChain) GetHeaderByNumberOdr(ctx context.Context, number uint64) (*types.Header, error) {
  417. if header := self.hc.GetHeaderByNumber(number); header != nil {
  418. return header, nil
  419. }
  420. return GetHeaderByNumber(ctx, self.odr, number)
  421. }
  422. func (self *LightChain) SyncCht(ctx context.Context) bool {
  423. headNum := self.CurrentHeader().Number.Uint64()
  424. cht := GetTrustedCht(self.chainDb)
  425. if headNum+1 < cht.Number*ChtFrequency {
  426. num := cht.Number*ChtFrequency - 1
  427. header, err := GetHeaderByNumber(ctx, self.odr, num)
  428. if header != nil && err == nil {
  429. self.mu.Lock()
  430. if self.hc.CurrentHeader().Number.Uint64() < header.Number.Uint64() {
  431. self.hc.SetCurrentHeader(header)
  432. }
  433. self.mu.Unlock()
  434. return true
  435. }
  436. }
  437. return false
  438. }