chain_manager.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513
  1. package core
  2. import (
  3. "bytes"
  4. "fmt"
  5. "math/big"
  6. "sync"
  7. "github.com/ethereum/go-ethereum/core/types"
  8. "github.com/ethereum/go-ethereum/common"
  9. "github.com/ethereum/go-ethereum/event"
  10. "github.com/ethereum/go-ethereum/logger"
  11. "github.com/ethereum/go-ethereum/rlp"
  12. "github.com/ethereum/go-ethereum/state"
  13. )
  14. var (
  15. chainlogger = logger.NewLogger("CHAIN")
  16. jsonlogger = logger.NewJsonLogger()
  17. blockHashPre = []byte("block-hash-")
  18. blockNumPre = []byte("block-num-")
  19. )
  20. type StateQuery interface {
  21. GetAccount(addr []byte) *state.StateObject
  22. }
  23. func CalcDifficulty(block, parent *types.Header) *big.Int {
  24. diff := new(big.Int)
  25. min := big.NewInt(2048)
  26. adjust := new(big.Int).Div(parent.Difficulty, min)
  27. if (block.Time - parent.Time) < 8 {
  28. diff.Add(parent.Difficulty, adjust)
  29. } else {
  30. diff.Sub(parent.Difficulty, adjust)
  31. }
  32. if diff.Cmp(GenesisDiff) < 0 {
  33. return GenesisDiff
  34. }
  35. return diff
  36. }
  37. func CalculateTD(block, parent *types.Block) *big.Int {
  38. uncleDiff := new(big.Int)
  39. for _, uncle := range block.Uncles() {
  40. uncleDiff = uncleDiff.Add(uncleDiff, uncle.Difficulty)
  41. }
  42. // TD(genesis_block) = 0 and TD(B) = TD(B.parent) + sum(u.difficulty for u in B.uncles) + B.difficulty
  43. td := new(big.Int)
  44. td = td.Add(parent.Td, uncleDiff)
  45. td = td.Add(td, block.Header().Difficulty)
  46. return td
  47. }
  48. func CalcGasLimit(parent, block *types.Block) *big.Int {
  49. if block.Number().Cmp(big.NewInt(0)) == 0 {
  50. return common.BigPow(10, 6)
  51. }
  52. // ((1024-1) * parent.gasLimit + (gasUsed * 6 / 5)) / 1024
  53. previous := new(big.Int).Mul(big.NewInt(1024-1), parent.GasLimit())
  54. current := new(big.Rat).Mul(new(big.Rat).SetInt(parent.GasUsed()), big.NewRat(6, 5))
  55. curInt := new(big.Int).Div(current.Num(), current.Denom())
  56. result := new(big.Int).Add(previous, curInt)
  57. result.Div(result, big.NewInt(1024))
  58. return common.BigMax(GenesisGasLimit, result)
  59. }
  60. type ChainManager struct {
  61. //eth EthManager
  62. blockDb common.Database
  63. stateDb common.Database
  64. processor types.BlockProcessor
  65. eventMux *event.TypeMux
  66. genesisBlock *types.Block
  67. // Last known total difficulty
  68. mu sync.RWMutex
  69. tsmu sync.RWMutex
  70. td *big.Int
  71. currentBlock *types.Block
  72. lastBlockHash []byte
  73. transState *state.StateDB
  74. txState *state.ManagedState
  75. quit chan struct{}
  76. }
  77. func NewChainManager(blockDb, stateDb common.Database, mux *event.TypeMux) *ChainManager {
  78. bc := &ChainManager{blockDb: blockDb, stateDb: stateDb, genesisBlock: GenesisBlock(stateDb), eventMux: mux, quit: make(chan struct{})}
  79. bc.setLastBlock()
  80. bc.transState = bc.State().Copy()
  81. // Take ownership of this particular state
  82. bc.txState = state.ManageState(bc.State().Copy())
  83. go bc.update()
  84. return bc
  85. }
  86. func (self *ChainManager) Td() *big.Int {
  87. self.mu.RLock()
  88. defer self.mu.RUnlock()
  89. return self.td
  90. }
  91. func (self *ChainManager) LastBlockHash() []byte {
  92. self.mu.RLock()
  93. defer self.mu.RUnlock()
  94. return self.lastBlockHash
  95. }
  96. func (self *ChainManager) CurrentBlock() *types.Block {
  97. self.mu.RLock()
  98. defer self.mu.RUnlock()
  99. return self.currentBlock
  100. }
  101. func (self *ChainManager) Status() (td *big.Int, currentBlock []byte, genesisBlock []byte) {
  102. self.mu.RLock()
  103. defer self.mu.RUnlock()
  104. return self.td, self.currentBlock.Hash(), self.genesisBlock.Hash()
  105. }
  106. func (self *ChainManager) SetProcessor(proc types.BlockProcessor) {
  107. self.processor = proc
  108. }
  109. func (self *ChainManager) State() *state.StateDB {
  110. return state.New(self.CurrentBlock().Root(), self.stateDb)
  111. }
  112. func (self *ChainManager) TransState() *state.StateDB {
  113. self.tsmu.RLock()
  114. defer self.tsmu.RUnlock()
  115. return self.transState
  116. }
  117. func (self *ChainManager) TxState() *state.ManagedState {
  118. self.tsmu.RLock()
  119. defer self.tsmu.RUnlock()
  120. return self.txState
  121. }
  122. func (self *ChainManager) setTxState(statedb *state.StateDB) {
  123. self.tsmu.Lock()
  124. defer self.tsmu.Unlock()
  125. self.txState = state.ManageState(statedb)
  126. }
  127. func (self *ChainManager) setTransState(statedb *state.StateDB) {
  128. self.transState = statedb
  129. }
  130. func (bc *ChainManager) setLastBlock() {
  131. data, _ := bc.blockDb.Get([]byte("LastBlock"))
  132. if len(data) != 0 {
  133. block := bc.GetBlock(data)
  134. bc.currentBlock = block
  135. bc.lastBlockHash = block.Hash()
  136. // Set the last know difficulty (might be 0x0 as initial value, Genesis)
  137. bc.td = common.BigD(bc.blockDb.LastKnownTD())
  138. } else {
  139. bc.Reset()
  140. }
  141. chainlogger.Infof("Last block (#%v) %x TD=%v\n", bc.currentBlock.Number(), bc.currentBlock.Hash(), bc.td)
  142. }
  143. // Block creation & chain handling
  144. func (bc *ChainManager) NewBlock(coinbase []byte) *types.Block {
  145. bc.mu.RLock()
  146. defer bc.mu.RUnlock()
  147. var root []byte
  148. parentHash := ZeroHash256
  149. if bc.currentBlock != nil {
  150. root = bc.currentBlock.Header().Root
  151. parentHash = bc.lastBlockHash
  152. }
  153. block := types.NewBlock(
  154. parentHash,
  155. coinbase,
  156. root,
  157. common.BigPow(2, 32),
  158. 0,
  159. "")
  160. block.SetUncles(nil)
  161. block.SetTransactions(nil)
  162. block.SetReceipts(nil)
  163. parent := bc.currentBlock
  164. if parent != nil {
  165. header := block.Header()
  166. header.Difficulty = CalcDifficulty(block.Header(), parent.Header())
  167. header.Number = new(big.Int).Add(parent.Header().Number, common.Big1)
  168. header.GasLimit = CalcGasLimit(parent, block)
  169. }
  170. return block
  171. }
  172. func (bc *ChainManager) Reset() {
  173. bc.mu.Lock()
  174. defer bc.mu.Unlock()
  175. for block := bc.currentBlock; block != nil; block = bc.GetBlock(block.Header().ParentHash) {
  176. bc.removeBlock(block)
  177. }
  178. // Prepare the genesis block
  179. bc.write(bc.genesisBlock)
  180. bc.insert(bc.genesisBlock)
  181. bc.currentBlock = bc.genesisBlock
  182. bc.setTotalDifficulty(common.Big("0"))
  183. }
  184. func (bc *ChainManager) removeBlock(block *types.Block) {
  185. bc.blockDb.Delete(append(blockHashPre, block.Hash()...))
  186. }
  187. func (bc *ChainManager) ResetWithGenesisBlock(gb *types.Block) {
  188. bc.mu.Lock()
  189. defer bc.mu.Unlock()
  190. for block := bc.currentBlock; block != nil; block = bc.GetBlock(block.Header().ParentHash) {
  191. bc.removeBlock(block)
  192. }
  193. // Prepare the genesis block
  194. bc.genesisBlock = gb
  195. bc.write(bc.genesisBlock)
  196. bc.insert(bc.genesisBlock)
  197. bc.currentBlock = bc.genesisBlock
  198. }
  199. func (self *ChainManager) Export() []byte {
  200. self.mu.RLock()
  201. defer self.mu.RUnlock()
  202. chainlogger.Infof("exporting %v blocks...\n", self.currentBlock.Header().Number)
  203. blocks := make([]*types.Block, int(self.currentBlock.NumberU64())+1)
  204. for block := self.currentBlock; block != nil; block = self.GetBlock(block.Header().ParentHash) {
  205. blocks[block.NumberU64()] = block
  206. }
  207. return common.Encode(blocks)
  208. }
  209. func (bc *ChainManager) insert(block *types.Block) {
  210. //encodedBlock := common.Encode(block)
  211. bc.blockDb.Put([]byte("LastBlock"), block.Hash())
  212. bc.currentBlock = block
  213. bc.lastBlockHash = block.Hash()
  214. key := append(blockNumPre, block.Number().Bytes()...)
  215. bc.blockDb.Put(key, bc.lastBlockHash)
  216. }
  217. func (bc *ChainManager) write(block *types.Block) {
  218. encodedBlock := common.Encode(block.RlpDataForStorage())
  219. key := append(blockHashPre, block.Hash()...)
  220. bc.blockDb.Put(key, encodedBlock)
  221. }
  222. // Accessors
  223. func (bc *ChainManager) Genesis() *types.Block {
  224. return bc.genesisBlock
  225. }
  226. // Block fetching methods
  227. func (bc *ChainManager) HasBlock(hash []byte) bool {
  228. data, _ := bc.blockDb.Get(append(blockHashPre, hash...))
  229. return len(data) != 0
  230. }
  231. func (self *ChainManager) GetBlockHashesFromHash(hash []byte, max uint64) (chain [][]byte) {
  232. block := self.GetBlock(hash)
  233. if block == nil {
  234. return
  235. }
  236. // XXX Could be optimised by using a different database which only holds hashes (i.e., linked list)
  237. for i := uint64(0); i < max; i++ {
  238. parentHash := block.Header().ParentHash
  239. block = self.GetBlock(parentHash)
  240. if block == nil {
  241. chainlogger.Infof("GetBlockHashesFromHash Parent UNKNOWN %x\n", parentHash)
  242. break
  243. }
  244. chain = append(chain, block.Hash())
  245. if block.Header().Number.Cmp(common.Big0) <= 0 {
  246. break
  247. }
  248. }
  249. return
  250. }
  251. func (self *ChainManager) GetBlock(hash []byte) *types.Block {
  252. data, _ := self.blockDb.Get(append(blockHashPre, hash...))
  253. if len(data) == 0 {
  254. return nil
  255. }
  256. var block types.Block
  257. if err := rlp.Decode(bytes.NewReader(data), &block); err != nil {
  258. fmt.Println(err)
  259. return nil
  260. }
  261. return &block
  262. }
  263. func (self *ChainManager) GetBlockByNumber(num uint64) *types.Block {
  264. self.mu.RLock()
  265. defer self.mu.RUnlock()
  266. key, _ := self.blockDb.Get(append(blockNumPre, big.NewInt(int64(num)).Bytes()...))
  267. if len(key) == 0 {
  268. return nil
  269. }
  270. return self.GetBlock(key)
  271. }
  272. func (self *ChainManager) GetUnclesInChain(block *types.Block, length int) (uncles []*types.Header) {
  273. for i := 0; block != nil && i < length; i++ {
  274. uncles = append(uncles, block.Uncles()...)
  275. block = self.GetBlock(block.ParentHash())
  276. }
  277. return
  278. }
  279. func (self *ChainManager) GetAncestors(block *types.Block, length int) (blocks []*types.Block) {
  280. for i := 0; i < length; i++ {
  281. block = self.GetBlock(block.ParentHash())
  282. if block == nil {
  283. break
  284. }
  285. blocks = append(blocks, block)
  286. }
  287. return
  288. }
  289. func (bc *ChainManager) setTotalDifficulty(td *big.Int) {
  290. bc.blockDb.Put([]byte("LTD"), td.Bytes())
  291. bc.td = td
  292. }
  293. func (self *ChainManager) CalcTotalDiff(block *types.Block) (*big.Int, error) {
  294. parent := self.GetBlock(block.Header().ParentHash)
  295. if parent == nil {
  296. return nil, fmt.Errorf("Unable to calculate total diff without known parent %x", block.Header().ParentHash)
  297. }
  298. parentTd := parent.Td
  299. uncleDiff := new(big.Int)
  300. for _, uncle := range block.Uncles() {
  301. uncleDiff = uncleDiff.Add(uncleDiff, uncle.Difficulty)
  302. }
  303. td := new(big.Int)
  304. td = td.Add(parentTd, uncleDiff)
  305. td = td.Add(td, block.Header().Difficulty)
  306. return td, nil
  307. }
  308. func (bc *ChainManager) Stop() {
  309. close(bc.quit)
  310. }
  311. type queueEvent struct {
  312. queue []interface{}
  313. canonicalCount int
  314. sideCount int
  315. splitCount int
  316. }
  317. func (self *ChainManager) InsertChain(chain types.Blocks) error {
  318. //self.tsmu.Lock()
  319. //defer self.tsmu.Unlock()
  320. // A queued approach to delivering events. This is generally faster than direct delivery and requires much less mutex acquiring.
  321. var queue = make([]interface{}, len(chain))
  322. var queueEvent = queueEvent{queue: queue}
  323. for i, block := range chain {
  324. // Call in to the block processor and check for errors. It's likely that if one block fails
  325. // all others will fail too (unless a known block is returned).
  326. td, err := self.processor.Process(block)
  327. if err != nil {
  328. if IsKnownBlockErr(err) {
  329. continue
  330. }
  331. h := block.Header()
  332. chainlogger.Infof("INVALID block #%v (%x)\n", h.Number, h.Hash()[:4])
  333. chainlogger.Infoln(err)
  334. chainlogger.Debugln(block)
  335. return err
  336. }
  337. block.Td = td
  338. self.mu.Lock()
  339. cblock := self.currentBlock
  340. {
  341. // Write block to database. Eventually we'll have to improve on this and throw away blocks that are
  342. // not in the canonical chain.
  343. self.write(block)
  344. // Compare the TD of the last known block in the canonical chain to make sure it's greater.
  345. // At this point it's possible that a different chain (fork) becomes the new canonical chain.
  346. if td.Cmp(self.td) > 0 {
  347. if block.Header().Number.Cmp(new(big.Int).Add(cblock.Header().Number, common.Big1)) < 0 {
  348. chainlogger.Infof("Split detected. New head #%v (%x) TD=%v, was #%v (%x) TD=%v\n", block.Header().Number, block.Hash()[:4], td, cblock.Header().Number, cblock.Hash()[:4], self.td)
  349. queue[i] = ChainSplitEvent{block}
  350. queueEvent.splitCount++
  351. }
  352. self.setTotalDifficulty(td)
  353. self.insert(block)
  354. /* XXX crashes
  355. jsonlogger.LogJson(&logger.EthChainNewHead{
  356. BlockHash: common.Bytes2Hex(block.Hash()),
  357. BlockNumber: block.Number(),
  358. ChainHeadHash: common.Bytes2Hex(cblock.Hash()),
  359. BlockPrevHash: common.Bytes2Hex(block.ParentHash()),
  360. })
  361. */
  362. self.setTransState(state.New(block.Root(), self.stateDb))
  363. self.setTxState(state.New(block.Root(), self.stateDb))
  364. queue[i] = ChainEvent{block}
  365. queueEvent.canonicalCount++
  366. } else {
  367. queue[i] = ChainSideEvent{block}
  368. queueEvent.sideCount++
  369. }
  370. }
  371. self.mu.Unlock()
  372. }
  373. // XXX put this in a goroutine?
  374. go self.eventMux.Post(queueEvent)
  375. return nil
  376. }
  377. func (self *ChainManager) update() {
  378. events := self.eventMux.Subscribe(queueEvent{})
  379. out:
  380. for {
  381. select {
  382. case ev := <-events.Chan():
  383. switch ev := ev.(type) {
  384. case queueEvent:
  385. for i, event := range ev.queue {
  386. switch event := event.(type) {
  387. case ChainEvent:
  388. // We need some control over the mining operation. Acquiring locks and waiting for the miner to create new block takes too long
  389. // and in most cases isn't even necessary.
  390. if i == ev.canonicalCount {
  391. self.eventMux.Post(ChainHeadEvent{event.Block})
  392. }
  393. case ChainSplitEvent:
  394. // On chain splits we need to reset the transaction state. We can't be sure whether the actual
  395. // state of the accounts are still valid.
  396. if i == ev.splitCount {
  397. self.setTxState(state.New(event.Block.Root(), self.stateDb))
  398. }
  399. }
  400. self.eventMux.Post(event)
  401. }
  402. }
  403. case <-self.quit:
  404. break out
  405. }
  406. }
  407. }
  408. // Satisfy state query interface
  409. func (self *ChainManager) GetAccount(addr []byte) *state.StateObject {
  410. return self.State().GetAccount(addr)
  411. }