chain_manager.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519
  1. package core
  2. import (
  3. "bytes"
  4. "fmt"
  5. "math/big"
  6. "sync"
  7. "github.com/ethereum/go-ethereum/common"
  8. "github.com/ethereum/go-ethereum/core/types"
  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 common.Hash
  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() common.Hash {
  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 common.Hash, genesisBlock common.Hash) {
  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(common.BytesToHash(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 common.Address) *types.Block {
  145. bc.mu.RLock()
  146. defer bc.mu.RUnlock()
  147. var (
  148. root common.Hash
  149. parentHash common.Hash
  150. )
  151. if bc.currentBlock != nil {
  152. root = bc.currentBlock.Header().Root
  153. parentHash = bc.lastBlockHash
  154. }
  155. block := types.NewBlock(
  156. parentHash,
  157. coinbase,
  158. root,
  159. common.BigPow(2, 32),
  160. 0,
  161. "")
  162. block.SetUncles(nil)
  163. block.SetTransactions(nil)
  164. block.SetReceipts(nil)
  165. parent := bc.currentBlock
  166. if parent != nil {
  167. header := block.Header()
  168. header.Difficulty = CalcDifficulty(block.Header(), parent.Header())
  169. header.Number = new(big.Int).Add(parent.Header().Number, common.Big1)
  170. header.GasLimit = CalcGasLimit(parent, block)
  171. }
  172. return block
  173. }
  174. func (bc *ChainManager) Reset() {
  175. bc.mu.Lock()
  176. defer bc.mu.Unlock()
  177. for block := bc.currentBlock; block != nil; block = bc.GetBlock(block.Header().ParentHash) {
  178. bc.removeBlock(block)
  179. }
  180. // Prepare the genesis block
  181. bc.write(bc.genesisBlock)
  182. bc.insert(bc.genesisBlock)
  183. bc.currentBlock = bc.genesisBlock
  184. bc.setTotalDifficulty(common.Big("0"))
  185. }
  186. func (bc *ChainManager) removeBlock(block *types.Block) {
  187. bc.blockDb.Delete(append(blockHashPre, block.Hash().Bytes()...))
  188. }
  189. func (bc *ChainManager) ResetWithGenesisBlock(gb *types.Block) {
  190. bc.mu.Lock()
  191. defer bc.mu.Unlock()
  192. for block := bc.currentBlock; block != nil; block = bc.GetBlock(block.Header().ParentHash) {
  193. bc.removeBlock(block)
  194. }
  195. // Prepare the genesis block
  196. bc.genesisBlock = gb
  197. bc.write(bc.genesisBlock)
  198. bc.insert(bc.genesisBlock)
  199. bc.currentBlock = bc.genesisBlock
  200. }
  201. func (self *ChainManager) Export() []byte {
  202. self.mu.RLock()
  203. defer self.mu.RUnlock()
  204. chainlogger.Infof("exporting %v blocks...\n", self.currentBlock.Header().Number)
  205. blocks := make([]*types.Block, int(self.currentBlock.NumberU64())+1)
  206. for block := self.currentBlock; block != nil; block = self.GetBlock(block.Header().ParentHash) {
  207. blocks[block.NumberU64()] = block
  208. }
  209. return common.Encode(blocks)
  210. }
  211. func (bc *ChainManager) insert(block *types.Block) {
  212. //encodedBlock := common.Encode(block)
  213. bc.blockDb.Put([]byte("LastBlock"), block.Hash().Bytes())
  214. bc.currentBlock = block
  215. bc.lastBlockHash = block.Hash()
  216. key := append(blockNumPre, block.Number().Bytes()...)
  217. bc.blockDb.Put(key, bc.lastBlockHash.Bytes())
  218. }
  219. func (bc *ChainManager) write(block *types.Block) {
  220. encodedBlock := common.Encode(block.RlpDataForStorage())
  221. key := append(blockHashPre, block.Hash().Bytes()...)
  222. bc.blockDb.Put(key, encodedBlock)
  223. }
  224. // Accessors
  225. func (bc *ChainManager) Genesis() *types.Block {
  226. return bc.genesisBlock
  227. }
  228. // Block fetching methods
  229. func (bc *ChainManager) HasBlock(hash common.Hash) bool {
  230. data, _ := bc.blockDb.Get(append(blockHashPre, hash[:]...))
  231. return len(data) != 0
  232. }
  233. func (self *ChainManager) GetBlockHashesFromHash(hash common.Hash, max uint64) (chain []common.Hash) {
  234. block := self.GetBlock(hash)
  235. if block == nil {
  236. return
  237. }
  238. // XXX Could be optimised by using a different database which only holds hashes (i.e., linked list)
  239. for i := uint64(0); i < max; i++ {
  240. parentHash := block.Header().ParentHash
  241. block = self.GetBlock(parentHash)
  242. if block == nil {
  243. chainlogger.Infof("GetBlockHashesFromHash Parent UNKNOWN %x\n", parentHash)
  244. break
  245. }
  246. chain = append(chain, block.Hash())
  247. if block.Header().Number.Cmp(common.Big0) <= 0 {
  248. break
  249. }
  250. }
  251. return
  252. }
  253. func (self *ChainManager) GetBlock(hash common.Hash) *types.Block {
  254. data, _ := self.blockDb.Get(append(blockHashPre, hash[:]...))
  255. if len(data) == 0 {
  256. return nil
  257. }
  258. var block types.Block
  259. if err := rlp.Decode(bytes.NewReader(data), &block); err != nil {
  260. fmt.Println(err)
  261. return nil
  262. }
  263. return &block
  264. }
  265. func (self *ChainManager) GetBlockByNumber(num uint64) *types.Block {
  266. self.mu.RLock()
  267. defer self.mu.RUnlock()
  268. key, _ := self.blockDb.Get(append(blockNumPre, big.NewInt(int64(num)).Bytes()...))
  269. if len(key) == 0 {
  270. return nil
  271. }
  272. return self.GetBlock(common.BytesToHash(key))
  273. }
  274. func (self *ChainManager) GetUnclesInChain(block *types.Block, length int) (uncles []*types.Header) {
  275. for i := 0; block != nil && i < length; i++ {
  276. uncles = append(uncles, block.Uncles()...)
  277. block = self.GetBlock(block.ParentHash())
  278. }
  279. return
  280. }
  281. func (self *ChainManager) GetAncestors(block *types.Block, length int) (blocks []*types.Block) {
  282. for i := 0; i < length; i++ {
  283. block = self.GetBlock(block.ParentHash())
  284. if block == nil {
  285. break
  286. }
  287. blocks = append(blocks, block)
  288. }
  289. return
  290. }
  291. func (bc *ChainManager) setTotalDifficulty(td *big.Int) {
  292. bc.blockDb.Put([]byte("LTD"), td.Bytes())
  293. bc.td = td
  294. }
  295. func (self *ChainManager) CalcTotalDiff(block *types.Block) (*big.Int, error) {
  296. parent := self.GetBlock(block.Header().ParentHash)
  297. if parent == nil {
  298. return nil, fmt.Errorf("Unable to calculate total diff without known parent %x", block.Header().ParentHash)
  299. }
  300. parentTd := parent.Td
  301. uncleDiff := new(big.Int)
  302. for _, uncle := range block.Uncles() {
  303. uncleDiff = uncleDiff.Add(uncleDiff, uncle.Difficulty)
  304. }
  305. td := new(big.Int)
  306. td = td.Add(parentTd, uncleDiff)
  307. td = td.Add(td, block.Header().Difficulty)
  308. return td, nil
  309. }
  310. func (bc *ChainManager) Stop() {
  311. close(bc.quit)
  312. }
  313. type queueEvent struct {
  314. queue []interface{}
  315. canonicalCount int
  316. sideCount int
  317. splitCount int
  318. }
  319. func (self *ChainManager) InsertChain(chain types.Blocks) error {
  320. //self.tsmu.Lock()
  321. //defer self.tsmu.Unlock()
  322. // A queued approach to delivering events. This is generally faster than direct delivery and requires much less mutex acquiring.
  323. var queue = make([]interface{}, len(chain))
  324. var queueEvent = queueEvent{queue: queue}
  325. for i, block := range chain {
  326. // Call in to the block processor and check for errors. It's likely that if one block fails
  327. // all others will fail too (unless a known block is returned).
  328. td, err := self.processor.Process(block)
  329. if err != nil {
  330. if IsKnownBlockErr(err) {
  331. continue
  332. }
  333. h := block.Header()
  334. chainlogger.Infof("INVALID block #%v (%x)\n", h.Number, h.Hash().Bytes()[:4])
  335. chainlogger.Infoln(err)
  336. chainlogger.Debugln(block)
  337. return err
  338. }
  339. block.Td = td
  340. self.mu.Lock()
  341. cblock := self.currentBlock
  342. {
  343. // Write block to database. Eventually we'll have to improve on this and throw away blocks that are
  344. // not in the canonical chain.
  345. self.write(block)
  346. // Compare the TD of the last known block in the canonical chain to make sure it's greater.
  347. // At this point it's possible that a different chain (fork) becomes the new canonical chain.
  348. if td.Cmp(self.td) > 0 {
  349. if block.Header().Number.Cmp(new(big.Int).Add(cblock.Header().Number, common.Big1)) < 0 {
  350. chash := cblock.Hash()
  351. hash := block.Hash()
  352. chainlogger.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)
  353. queue[i] = ChainSplitEvent{block}
  354. queueEvent.splitCount++
  355. }
  356. self.setTotalDifficulty(td)
  357. self.insert(block)
  358. /* XXX crashes
  359. jsonlogger.LogJson(&logger.EthChainNewHead{
  360. BlockHash: common.Bytes2Hex(block.Hash()),
  361. BlockNumber: block.Number(),
  362. ChainHeadHash: common.Bytes2Hex(cblock.Hash()),
  363. BlockPrevHash: common.Bytes2Hex(block.ParentHash()),
  364. })
  365. */
  366. self.setTransState(state.New(block.Root(), self.stateDb))
  367. self.setTxState(state.New(block.Root(), self.stateDb))
  368. queue[i] = ChainEvent{block}
  369. queueEvent.canonicalCount++
  370. } else {
  371. queue[i] = ChainSideEvent{block}
  372. queueEvent.sideCount++
  373. }
  374. }
  375. self.mu.Unlock()
  376. }
  377. // XXX put this in a goroutine?
  378. go self.eventMux.Post(queueEvent)
  379. return nil
  380. }
  381. func (self *ChainManager) update() {
  382. events := self.eventMux.Subscribe(queueEvent{})
  383. out:
  384. for {
  385. select {
  386. case ev := <-events.Chan():
  387. switch ev := ev.(type) {
  388. case queueEvent:
  389. for i, event := range ev.queue {
  390. switch event := event.(type) {
  391. case ChainEvent:
  392. // We need some control over the mining operation. Acquiring locks and waiting for the miner to create new block takes too long
  393. // and in most cases isn't even necessary.
  394. if i == ev.canonicalCount {
  395. self.eventMux.Post(ChainHeadEvent{event.Block})
  396. }
  397. case ChainSplitEvent:
  398. // On chain splits we need to reset the transaction state. We can't be sure whether the actual
  399. // state of the accounts are still valid.
  400. if i == ev.splitCount {
  401. self.setTxState(state.New(event.Block.Root(), self.stateDb))
  402. }
  403. }
  404. self.eventMux.Post(event)
  405. }
  406. }
  407. case <-self.quit:
  408. break out
  409. }
  410. }
  411. }
  412. /*
  413. // Satisfy state query interface
  414. func (self *ChainManager) GetAccount(addr common.Hash) *state.StateObject {
  415. return self.State().GetAccount(addr)
  416. }
  417. */