chain_manager.go 15 KB

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