chain_manager.go 13 KB

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