chain_manager.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628
  1. package core
  2. import (
  3. "bytes"
  4. "fmt"
  5. "io"
  6. "math/big"
  7. "sync"
  8. "time"
  9. "github.com/ethereum/go-ethereum/common"
  10. "github.com/ethereum/go-ethereum/core/state"
  11. "github.com/ethereum/go-ethereum/core/types"
  12. "github.com/ethereum/go-ethereum/event"
  13. "github.com/ethereum/go-ethereum/logger"
  14. "github.com/ethereum/go-ethereum/logger/glog"
  15. "github.com/ethereum/go-ethereum/params"
  16. "github.com/ethereum/go-ethereum/rlp"
  17. )
  18. var (
  19. chainlogger = logger.NewLogger("CHAIN")
  20. jsonlogger = logger.NewJsonLogger()
  21. blockHashPre = []byte("block-hash-")
  22. blockNumPre = []byte("block-num-")
  23. )
  24. const blockCacheLimit = 10000
  25. type StateQuery interface {
  26. GetAccount(addr []byte) *state.StateObject
  27. }
  28. func CalcDifficulty(block, parent *types.Header) *big.Int {
  29. diff := new(big.Int)
  30. adjust := new(big.Int).Div(parent.Difficulty, params.DifficultyBoundDivisor)
  31. if big.NewInt(int64(block.Time)-int64(parent.Time)).Cmp(params.DurationLimit) < 0 {
  32. diff.Add(parent.Difficulty, adjust)
  33. } else {
  34. diff.Sub(parent.Difficulty, adjust)
  35. }
  36. if diff.Cmp(params.MinimumDifficulty) < 0 {
  37. return params.MinimumDifficulty
  38. }
  39. return diff
  40. }
  41. func CalculateTD(block, parent *types.Block) *big.Int {
  42. td := new(big.Int).Add(parent.Td, block.Header().Difficulty)
  43. return td
  44. }
  45. func CalcGasLimit(parent, block *types.Block) *big.Int {
  46. if block.Number().Cmp(big.NewInt(0)) == 0 {
  47. return common.BigPow(10, 6)
  48. }
  49. // ((1024-1) * parent.gasLimit + (gasUsed * 6 / 5)) / 1024
  50. previous := new(big.Int).Mul(big.NewInt(1024-1), parent.GasLimit())
  51. current := new(big.Rat).Mul(new(big.Rat).SetInt(parent.GasUsed()), big.NewRat(6, 5))
  52. curInt := new(big.Int).Div(current.Num(), current.Denom())
  53. result := new(big.Int).Add(previous, curInt)
  54. result.Div(result, big.NewInt(1024))
  55. return common.BigMax(params.GenesisGasLimit, result)
  56. }
  57. type ChainManager struct {
  58. //eth EthManager
  59. blockDb common.Database
  60. stateDb common.Database
  61. processor types.BlockProcessor
  62. eventMux *event.TypeMux
  63. genesisBlock *types.Block
  64. // Last known total difficulty
  65. mu sync.RWMutex
  66. tsmu sync.RWMutex
  67. td *big.Int
  68. currentBlock *types.Block
  69. lastBlockHash common.Hash
  70. transState *state.StateDB
  71. txState *state.ManagedState
  72. cache *BlockCache
  73. futureBlocks *BlockCache
  74. quit chan struct{}
  75. }
  76. func NewChainManager(blockDb, stateDb common.Database, mux *event.TypeMux) *ChainManager {
  77. bc := &ChainManager{blockDb: blockDb, stateDb: stateDb, genesisBlock: GenesisBlock(stateDb), eventMux: mux, quit: make(chan struct{}), cache: NewBlockCache(blockCacheLimit)}
  78. bc.setLastBlock()
  79. bc.transState = bc.State().Copy()
  80. // Take ownership of this particular state
  81. bc.txState = state.ManageState(bc.State().Copy())
  82. bc.futureBlocks = NewBlockCache(254)
  83. bc.makeCache()
  84. go bc.update()
  85. return bc
  86. }
  87. func (self *ChainManager) Td() *big.Int {
  88. self.mu.RLock()
  89. defer self.mu.RUnlock()
  90. return self.td
  91. }
  92. func (self *ChainManager) LastBlockHash() common.Hash {
  93. self.mu.RLock()
  94. defer self.mu.RUnlock()
  95. return self.lastBlockHash
  96. }
  97. func (self *ChainManager) CurrentBlock() *types.Block {
  98. self.mu.RLock()
  99. defer self.mu.RUnlock()
  100. return self.currentBlock
  101. }
  102. func (self *ChainManager) Status() (td *big.Int, currentBlock common.Hash, genesisBlock common.Hash) {
  103. self.mu.RLock()
  104. defer self.mu.RUnlock()
  105. return self.td, self.currentBlock.Hash(), self.genesisBlock.Hash()
  106. }
  107. func (self *ChainManager) SetProcessor(proc types.BlockProcessor) {
  108. self.processor = proc
  109. }
  110. func (self *ChainManager) State() *state.StateDB {
  111. return state.New(self.CurrentBlock().Root(), self.stateDb)
  112. }
  113. func (self *ChainManager) TransState() *state.StateDB {
  114. self.tsmu.RLock()
  115. defer self.tsmu.RUnlock()
  116. return self.transState
  117. }
  118. func (self *ChainManager) TxState() *state.ManagedState {
  119. self.tsmu.RLock()
  120. defer self.tsmu.RUnlock()
  121. return self.txState
  122. }
  123. func (self *ChainManager) setTxState(statedb *state.StateDB) {
  124. self.tsmu.Lock()
  125. defer self.tsmu.Unlock()
  126. self.txState = state.ManageState(statedb)
  127. }
  128. func (self *ChainManager) setTransState(statedb *state.StateDB) {
  129. self.transState = statedb
  130. }
  131. func (bc *ChainManager) setLastBlock() {
  132. data, _ := bc.blockDb.Get([]byte("LastBlock"))
  133. if len(data) != 0 {
  134. block := bc.GetBlock(common.BytesToHash(data))
  135. bc.currentBlock = block
  136. bc.lastBlockHash = block.Hash()
  137. // Set the last know difficulty (might be 0x0 as initial value, Genesis)
  138. bc.td = common.BigD(bc.blockDb.LastKnownTD())
  139. } else {
  140. bc.Reset()
  141. }
  142. if glog.V(logger.Info) {
  143. glog.Infof("Last block (#%v) %x TD=%v\n", bc.currentBlock.Number(), bc.currentBlock.Hash(), bc.td)
  144. }
  145. }
  146. func (bc *ChainManager) makeCache() {
  147. if bc.cache == nil {
  148. bc.cache = NewBlockCache(blockCacheLimit)
  149. }
  150. // load in last `blockCacheLimit` - 1 blocks. Last block is the current.
  151. ancestors := bc.GetAncestors(bc.currentBlock, blockCacheLimit-1)
  152. ancestors = append(ancestors, bc.currentBlock)
  153. for _, block := range ancestors {
  154. bc.cache.Push(block)
  155. }
  156. }
  157. // Block creation & chain handling
  158. func (bc *ChainManager) NewBlock(coinbase common.Address) *types.Block {
  159. bc.mu.RLock()
  160. defer bc.mu.RUnlock()
  161. var (
  162. root common.Hash
  163. parentHash common.Hash
  164. )
  165. if bc.currentBlock != nil {
  166. root = bc.currentBlock.Header().Root
  167. parentHash = bc.lastBlockHash
  168. }
  169. block := types.NewBlock(
  170. parentHash,
  171. coinbase,
  172. root,
  173. common.BigPow(2, 32),
  174. 0,
  175. nil)
  176. block.SetUncles(nil)
  177. block.SetTransactions(nil)
  178. block.SetReceipts(nil)
  179. parent := bc.currentBlock
  180. if parent != nil {
  181. header := block.Header()
  182. header.Difficulty = CalcDifficulty(block.Header(), parent.Header())
  183. header.Number = new(big.Int).Add(parent.Header().Number, common.Big1)
  184. header.GasLimit = CalcGasLimit(parent, block)
  185. }
  186. return block
  187. }
  188. func (bc *ChainManager) Reset() {
  189. bc.mu.Lock()
  190. defer bc.mu.Unlock()
  191. for block := bc.currentBlock; block != nil; block = bc.GetBlock(block.Header().ParentHash) {
  192. bc.removeBlock(block)
  193. }
  194. if bc.cache == nil {
  195. bc.cache = NewBlockCache(blockCacheLimit)
  196. }
  197. // Prepare the genesis block
  198. bc.write(bc.genesisBlock)
  199. bc.insert(bc.genesisBlock)
  200. bc.currentBlock = bc.genesisBlock
  201. bc.makeCache()
  202. bc.setTotalDifficulty(common.Big("0"))
  203. }
  204. func (bc *ChainManager) removeBlock(block *types.Block) {
  205. bc.blockDb.Delete(append(blockHashPre, block.Hash().Bytes()...))
  206. }
  207. func (bc *ChainManager) ResetWithGenesisBlock(gb *types.Block) {
  208. bc.mu.Lock()
  209. defer bc.mu.Unlock()
  210. for block := bc.currentBlock; block != nil; block = bc.GetBlock(block.Header().ParentHash) {
  211. bc.removeBlock(block)
  212. }
  213. // Prepare the genesis block
  214. bc.genesisBlock = gb
  215. bc.write(bc.genesisBlock)
  216. bc.insert(bc.genesisBlock)
  217. bc.currentBlock = bc.genesisBlock
  218. bc.makeCache()
  219. }
  220. // Export writes the active chain to the given writer.
  221. func (self *ChainManager) Export(w io.Writer) error {
  222. self.mu.RLock()
  223. defer self.mu.RUnlock()
  224. glog.V(logger.Info).Infof("exporting %v blocks...\n", self.currentBlock.Header().Number)
  225. last := self.currentBlock.NumberU64()
  226. for nr := uint64(0); nr <= last; nr++ {
  227. if err := self.GetBlockByNumber(nr).EncodeRLP(w); err != nil {
  228. return err
  229. }
  230. }
  231. return nil
  232. }
  233. func (bc *ChainManager) insert(block *types.Block) {
  234. bc.blockDb.Put([]byte("LastBlock"), block.Hash().Bytes())
  235. bc.currentBlock = block
  236. bc.lastBlockHash = block.Hash()
  237. key := append(blockNumPre, block.Number().Bytes()...)
  238. bc.blockDb.Put(key, bc.lastBlockHash.Bytes())
  239. // Push block to cache
  240. bc.cache.Push(block)
  241. }
  242. func (bc *ChainManager) write(block *types.Block) {
  243. enc, _ := rlp.EncodeToBytes((*types.StorageBlock)(block))
  244. key := append(blockHashPre, block.Hash().Bytes()...)
  245. bc.blockDb.Put(key, enc)
  246. }
  247. // Accessors
  248. func (bc *ChainManager) Genesis() *types.Block {
  249. return bc.genesisBlock
  250. }
  251. // Block fetching methods
  252. func (bc *ChainManager) HasBlock(hash common.Hash) bool {
  253. data, _ := bc.blockDb.Get(append(blockHashPre, hash[:]...))
  254. return len(data) != 0
  255. }
  256. func (self *ChainManager) GetBlockHashesFromHash(hash common.Hash, max uint64) (chain []common.Hash) {
  257. block := self.GetBlock(hash)
  258. if block == nil {
  259. return
  260. }
  261. // XXX Could be optimised by using a different database which only holds hashes (i.e., linked list)
  262. for i := uint64(0); i < max; i++ {
  263. block = self.GetBlock(block.ParentHash())
  264. if block == nil {
  265. break
  266. }
  267. chain = append(chain, block.Hash())
  268. if block.Number().Cmp(common.Big0) <= 0 {
  269. break
  270. }
  271. }
  272. return
  273. }
  274. func (self *ChainManager) GetBlock(hash common.Hash) *types.Block {
  275. if block := self.cache.Get(hash); block != nil {
  276. return block
  277. }
  278. data, _ := self.blockDb.Get(append(blockHashPre, hash[:]...))
  279. if len(data) == 0 {
  280. return nil
  281. }
  282. var block types.StorageBlock
  283. if err := rlp.Decode(bytes.NewReader(data), &block); err != nil {
  284. glog.V(logger.Error).Infof("invalid block RLP for hash %x: %v", hash, err)
  285. return nil
  286. }
  287. return (*types.Block)(&block)
  288. }
  289. func (self *ChainManager) GetBlockByNumber(num uint64) *types.Block {
  290. self.mu.RLock()
  291. defer self.mu.RUnlock()
  292. return self.getBlockByNumber(num)
  293. }
  294. // non blocking version
  295. func (self *ChainManager) getBlockByNumber(num uint64) *types.Block {
  296. key, _ := self.blockDb.Get(append(blockNumPre, big.NewInt(int64(num)).Bytes()...))
  297. if len(key) == 0 {
  298. return nil
  299. }
  300. return self.GetBlock(common.BytesToHash(key))
  301. }
  302. func (self *ChainManager) GetUnclesInChain(block *types.Block, length int) (uncles []*types.Header) {
  303. for i := 0; block != nil && i < length; i++ {
  304. uncles = append(uncles, block.Uncles()...)
  305. block = self.GetBlock(block.ParentHash())
  306. }
  307. return
  308. }
  309. func (self *ChainManager) GetAncestors(block *types.Block, length int) (blocks []*types.Block) {
  310. for i := 0; i < length; i++ {
  311. block = self.GetBlock(block.ParentHash())
  312. if block == nil {
  313. break
  314. }
  315. blocks = append(blocks, block)
  316. }
  317. return
  318. }
  319. func (bc *ChainManager) setTotalDifficulty(td *big.Int) {
  320. bc.blockDb.Put([]byte("LTD"), td.Bytes())
  321. bc.td = td
  322. }
  323. func (self *ChainManager) CalcTotalDiff(block *types.Block) (*big.Int, error) {
  324. parent := self.GetBlock(block.Header().ParentHash)
  325. if parent == nil {
  326. return nil, fmt.Errorf("Unable to calculate total diff without known parent %x", block.Header().ParentHash)
  327. }
  328. parentTd := parent.Td
  329. uncleDiff := new(big.Int)
  330. for _, uncle := range block.Uncles() {
  331. uncleDiff = uncleDiff.Add(uncleDiff, uncle.Difficulty)
  332. }
  333. td := new(big.Int)
  334. td = td.Add(parentTd, uncleDiff)
  335. td = td.Add(td, block.Header().Difficulty)
  336. return td, nil
  337. }
  338. func (bc *ChainManager) Stop() {
  339. close(bc.quit)
  340. }
  341. type queueEvent struct {
  342. queue []interface{}
  343. canonicalCount int
  344. sideCount int
  345. splitCount int
  346. }
  347. func (self *ChainManager) procFutureBlocks() {
  348. blocks := make([]*types.Block, len(self.futureBlocks.blocks))
  349. self.futureBlocks.Each(func(i int, block *types.Block) {
  350. blocks[i] = block
  351. })
  352. types.BlockBy(types.Number).Sort(blocks)
  353. self.InsertChain(blocks)
  354. }
  355. func (self *ChainManager) InsertChain(chain types.Blocks) error {
  356. // A queued approach to delivering events. This is generally faster than direct delivery and requires much less mutex acquiring.
  357. var (
  358. queue = make([]interface{}, len(chain))
  359. queueEvent = queueEvent{queue: queue}
  360. stats struct{ queued, processed int }
  361. tstart = time.Now()
  362. )
  363. for i, block := range chain {
  364. if block == nil {
  365. continue
  366. }
  367. // Call in to the block processor and check for errors. It's likely that if one block fails
  368. // all others will fail too (unless a known block is returned).
  369. logs, err := self.processor.Process(block)
  370. if err != nil {
  371. if IsKnownBlockErr(err) {
  372. continue
  373. }
  374. block.Td = new(big.Int)
  375. // Do not penelise on future block. We'll need a block queue eventually that will queue
  376. // future block for future use
  377. if err == BlockFutureErr {
  378. block.SetQueued(true)
  379. self.futureBlocks.Push(block)
  380. stats.queued++
  381. continue
  382. }
  383. if IsParentErr(err) && self.futureBlocks.Has(block.ParentHash()) {
  384. block.SetQueued(true)
  385. self.futureBlocks.Push(block)
  386. stats.queued++
  387. continue
  388. }
  389. h := block.Header()
  390. glog.V(logger.Error).Infof("INVALID block #%v (%x)\n", h.Number, h.Hash().Bytes()[:4])
  391. glog.V(logger.Error).Infoln(err)
  392. glog.V(logger.Debug).Infoln(block)
  393. return err
  394. }
  395. block.Td = new(big.Int).Set(CalculateTD(block, self.GetBlock(block.ParentHash())))
  396. self.mu.Lock()
  397. {
  398. cblock := self.currentBlock
  399. // Write block to database. Eventually we'll have to improve on this and throw away blocks that are
  400. // not in the canonical chain.
  401. self.write(block)
  402. // Compare the TD of the last known block in the canonical chain to make sure it's greater.
  403. // At this point it's possible that a different chain (fork) becomes the new canonical chain.
  404. if block.Td.Cmp(self.td) > 0 {
  405. //if block.Header().Number.Cmp(new(big.Int).Add(cblock.Header().Number, common.Big1)) < 0 {
  406. if block.Number().Cmp(cblock.Number()) <= 0 {
  407. chash := cblock.Hash()
  408. hash := block.Hash()
  409. if glog.V(logger.Info) {
  410. glog.Infof("Split detected. New head #%v (%x) TD=%v, was #%v (%x) TD=%v\n", block.Header().Number, hash[:4], block.Td, cblock.Header().Number, chash[:4], self.td)
  411. }
  412. // during split we merge two different chains and create the new canonical chain
  413. self.merge(self.getBlockByNumber(block.NumberU64()), block)
  414. queue[i] = ChainSplitEvent{block, logs}
  415. queueEvent.splitCount++
  416. }
  417. self.setTotalDifficulty(block.Td)
  418. self.insert(block)
  419. jsonlogger.LogJson(&logger.EthChainNewHead{
  420. BlockHash: block.Hash().Hex(),
  421. BlockNumber: block.Number(),
  422. ChainHeadHash: cblock.Hash().Hex(),
  423. BlockPrevHash: block.ParentHash().Hex(),
  424. })
  425. self.setTransState(state.New(block.Root(), self.stateDb))
  426. self.setTxState(state.New(block.Root(), self.stateDb))
  427. queue[i] = ChainEvent{block, logs}
  428. queueEvent.canonicalCount++
  429. if glog.V(logger.Debug) {
  430. glog.Infof("inserted block #%d (%d TXs %d UNCs) (%x...)\n", block.Number(), len(block.Transactions()), len(block.Uncles()), block.Hash().Bytes()[0:4])
  431. }
  432. } else {
  433. queue[i] = ChainSideEvent{block, logs}
  434. queueEvent.sideCount++
  435. }
  436. }
  437. self.mu.Unlock()
  438. stats.processed++
  439. self.futureBlocks.Delete(block.Hash())
  440. }
  441. if (stats.queued > 0 || stats.processed > 0) && bool(glog.V(logger.Info)) {
  442. tend := time.Since(tstart)
  443. start, end := chain[0], chain[len(chain)-1]
  444. glog.Infof("imported %d block(s) %d queued in %v. #%v [%x / %x]\n", stats.processed, stats.queued, tend, end.Number(), start.Hash().Bytes()[:4], end.Hash().Bytes()[:4])
  445. }
  446. go self.eventMux.Post(queueEvent)
  447. return nil
  448. }
  449. // merge takes two blocks, an old chain and a new chain and will reconstruct the blocks and inserts them
  450. // to be part of the new canonical chain.
  451. func (self *ChainManager) merge(oldBlock, newBlock *types.Block) {
  452. glog.V(logger.Debug).Infof("Applying diff to %x & %x\n", oldBlock.Hash().Bytes()[:4], newBlock.Hash().Bytes()[:4])
  453. var oldChain, newChain types.Blocks
  454. // First find the split (common ancestor) so we can perform an adequate merge
  455. for {
  456. oldBlock, newBlock = self.GetBlock(oldBlock.ParentHash()), self.GetBlock(newBlock.ParentHash())
  457. if oldBlock.Hash() == newBlock.Hash() {
  458. break
  459. }
  460. oldChain = append(oldChain, oldBlock)
  461. newChain = append(newChain, newBlock)
  462. }
  463. // insert blocks
  464. for _, block := range newChain {
  465. self.insert(block)
  466. }
  467. if glog.V(logger.Detail) {
  468. for i, oldBlock := range oldChain {
  469. glog.Infof("- %.10v = %x\n", oldBlock.Number(), oldBlock.Hash())
  470. glog.Infof("+ %.10v = %x\n", newChain[i].Number(), newChain[i].Hash())
  471. }
  472. }
  473. }
  474. func (self *ChainManager) update() {
  475. events := self.eventMux.Subscribe(queueEvent{})
  476. futureTimer := time.NewTicker(5 * time.Second)
  477. out:
  478. for {
  479. select {
  480. case ev := <-events.Chan():
  481. switch ev := ev.(type) {
  482. case queueEvent:
  483. for i, event := range ev.queue {
  484. switch event := event.(type) {
  485. case ChainEvent:
  486. // We need some control over the mining operation. Acquiring locks and waiting for the miner to create new block takes too long
  487. // and in most cases isn't even necessary.
  488. if i+1 == ev.canonicalCount {
  489. self.eventMux.Post(ChainHeadEvent{event.Block})
  490. }
  491. case ChainSplitEvent:
  492. // On chain splits we need to reset the transaction state. We can't be sure whether the actual
  493. // state of the accounts are still valid.
  494. if i == ev.splitCount {
  495. self.setTxState(state.New(event.Block.Root(), self.stateDb))
  496. }
  497. }
  498. self.eventMux.Post(event)
  499. }
  500. }
  501. case <-futureTimer.C:
  502. self.procFutureBlocks()
  503. case <-self.quit:
  504. break out
  505. }
  506. }
  507. }