lightchain.go 17 KB

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