chain_manager.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514
  1. package core
  2. import (
  3. "bytes"
  4. "fmt"
  5. "io"
  6. "math/big"
  7. "sync"
  8. "github.com/ethereum/go-ethereum/common"
  9. "github.com/ethereum/go-ethereum/core/types"
  10. "github.com/ethereum/go-ethereum/event"
  11. "github.com/ethereum/go-ethereum/logger"
  12. "github.com/ethereum/go-ethereum/rlp"
  13. "github.com/ethereum/go-ethereum/state"
  14. )
  15. var (
  16. chainlogger = logger.NewLogger("CHAIN")
  17. jsonlogger = logger.NewJsonLogger()
  18. blockHashPre = []byte("block-hash-")
  19. blockNumPre = []byte("block-num-")
  20. )
  21. type StateQuery interface {
  22. GetAccount(addr []byte) *state.StateObject
  23. }
  24. func CalcDifficulty(block, parent *types.Header) *big.Int {
  25. diff := new(big.Int)
  26. min := big.NewInt(2048)
  27. adjust := new(big.Int).Div(parent.Difficulty, min)
  28. if (block.Time - parent.Time) < 8 {
  29. diff.Add(parent.Difficulty, adjust)
  30. } else {
  31. diff.Sub(parent.Difficulty, adjust)
  32. }
  33. if diff.Cmp(min) < 0 {
  34. return min
  35. }
  36. return diff
  37. }
  38. func CalculateTD(block, parent *types.Block) *big.Int {
  39. uncleDiff := new(big.Int)
  40. for _, uncle := range block.Uncles() {
  41. uncleDiff = uncleDiff.Add(uncleDiff, uncle.Difficulty)
  42. }
  43. // TD(genesis_block) = 0 and TD(B) = TD(B.parent) + sum(u.difficulty for u in B.uncles) + B.difficulty
  44. td := new(big.Int)
  45. td = td.Add(parent.Td, uncleDiff)
  46. td = td.Add(td, block.Header().Difficulty)
  47. return td
  48. }
  49. func CalcGasLimit(parent, block *types.Block) *big.Int {
  50. if block.Number().Cmp(big.NewInt(0)) == 0 {
  51. return common.BigPow(10, 6)
  52. }
  53. // ((1024-1) * parent.gasLimit + (gasUsed * 6 / 5)) / 1024
  54. previous := new(big.Int).Mul(big.NewInt(1024-1), parent.GasLimit())
  55. current := new(big.Rat).Mul(new(big.Rat).SetInt(parent.GasUsed()), big.NewRat(6, 5))
  56. curInt := new(big.Int).Div(current.Num(), current.Denom())
  57. result := new(big.Int).Add(previous, curInt)
  58. result.Div(result, big.NewInt(1024))
  59. return common.BigMax(GenesisGasLimit, result)
  60. }
  61. type ChainManager struct {
  62. //eth EthManager
  63. blockDb common.Database
  64. stateDb common.Database
  65. processor types.BlockProcessor
  66. eventMux *event.TypeMux
  67. genesisBlock *types.Block
  68. // Last known total difficulty
  69. mu sync.RWMutex
  70. tsmu sync.RWMutex
  71. td *big.Int
  72. currentBlock *types.Block
  73. lastBlockHash common.Hash
  74. transState *state.StateDB
  75. txState *state.ManagedState
  76. quit chan struct{}
  77. }
  78. func NewChainManager(blockDb, stateDb common.Database, mux *event.TypeMux) *ChainManager {
  79. bc := &ChainManager{blockDb: blockDb, stateDb: stateDb, genesisBlock: GenesisBlock(stateDb), eventMux: mux, quit: make(chan struct{})}
  80. bc.setLastBlock()
  81. bc.transState = bc.State().Copy()
  82. // Take ownership of this particular state
  83. bc.txState = state.ManageState(bc.State().Copy())
  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. chainlogger.Infof("Last block (#%v) %x TD=%v\n", bc.currentBlock.Number(), bc.currentBlock.Hash(), bc.td)
  143. }
  144. // Block creation & chain handling
  145. func (bc *ChainManager) NewBlock(coinbase common.Address) *types.Block {
  146. bc.mu.RLock()
  147. defer bc.mu.RUnlock()
  148. var (
  149. root common.Hash
  150. parentHash common.Hash
  151. )
  152. if bc.currentBlock != nil {
  153. root = bc.currentBlock.Header().Root
  154. parentHash = bc.lastBlockHash
  155. }
  156. block := types.NewBlock(
  157. parentHash,
  158. coinbase,
  159. root,
  160. common.BigPow(2, 32),
  161. 0,
  162. "")
  163. block.SetUncles(nil)
  164. block.SetTransactions(nil)
  165. block.SetReceipts(nil)
  166. parent := bc.currentBlock
  167. if parent != nil {
  168. header := block.Header()
  169. header.Difficulty = CalcDifficulty(block.Header(), parent.Header())
  170. header.Number = new(big.Int).Add(parent.Header().Number, common.Big1)
  171. header.GasLimit = CalcGasLimit(parent, block)
  172. }
  173. return block
  174. }
  175. func (bc *ChainManager) Reset() {
  176. bc.mu.Lock()
  177. defer bc.mu.Unlock()
  178. for block := bc.currentBlock; block != nil; block = bc.GetBlock(block.Header().ParentHash) {
  179. bc.removeBlock(block)
  180. }
  181. // Prepare the genesis block
  182. bc.write(bc.genesisBlock)
  183. bc.insert(bc.genesisBlock)
  184. bc.currentBlock = bc.genesisBlock
  185. bc.setTotalDifficulty(common.Big("0"))
  186. }
  187. func (bc *ChainManager) removeBlock(block *types.Block) {
  188. bc.blockDb.Delete(append(blockHashPre, block.Hash().Bytes()...))
  189. }
  190. func (bc *ChainManager) ResetWithGenesisBlock(gb *types.Block) {
  191. bc.mu.Lock()
  192. defer bc.mu.Unlock()
  193. for block := bc.currentBlock; block != nil; block = bc.GetBlock(block.Header().ParentHash) {
  194. bc.removeBlock(block)
  195. }
  196. // Prepare the genesis block
  197. bc.genesisBlock = gb
  198. bc.write(bc.genesisBlock)
  199. bc.insert(bc.genesisBlock)
  200. bc.currentBlock = bc.genesisBlock
  201. }
  202. // Export writes the active chain to the given writer.
  203. func (self *ChainManager) Export(w io.Writer) error {
  204. self.mu.RLock()
  205. defer self.mu.RUnlock()
  206. chainlogger.Infof("exporting %v blocks...\n", self.currentBlock.Header().Number)
  207. for block := self.currentBlock; block != nil; block = self.GetBlock(block.Header().ParentHash) {
  208. if err := block.EncodeRLP(w); err != nil {
  209. return err
  210. }
  211. }
  212. return nil
  213. }
  214. func (bc *ChainManager) insert(block *types.Block) {
  215. bc.blockDb.Put([]byte("LastBlock"), block.Hash().Bytes())
  216. bc.currentBlock = block
  217. bc.lastBlockHash = block.Hash()
  218. key := append(blockNumPre, block.Number().Bytes()...)
  219. bc.blockDb.Put(key, bc.lastBlockHash.Bytes())
  220. }
  221. func (bc *ChainManager) write(block *types.Block) {
  222. enc, _ := rlp.EncodeToBytes((*types.StorageBlock)(block))
  223. key := append(blockHashPre, block.Hash().Bytes()...)
  224. bc.blockDb.Put(key, enc)
  225. }
  226. // Accessors
  227. func (bc *ChainManager) Genesis() *types.Block {
  228. return bc.genesisBlock
  229. }
  230. // Block fetching methods
  231. func (bc *ChainManager) HasBlock(hash common.Hash) bool {
  232. data, _ := bc.blockDb.Get(append(blockHashPre, hash[:]...))
  233. return len(data) != 0
  234. }
  235. func (self *ChainManager) GetBlockHashesFromHash(hash common.Hash, max uint64) (chain []common.Hash) {
  236. block := self.GetBlock(hash)
  237. if block == nil {
  238. return
  239. }
  240. // XXX Could be optimised by using a different database which only holds hashes (i.e., linked list)
  241. for i := uint64(0); i < max; i++ {
  242. parentHash := block.Header().ParentHash
  243. block = self.GetBlock(parentHash)
  244. if block == nil {
  245. chainlogger.Infof("GetBlockHashesFromHash Parent UNKNOWN %x\n", parentHash)
  246. break
  247. }
  248. chain = append(chain, block.Hash())
  249. if block.Header().Number.Cmp(common.Big0) <= 0 {
  250. break
  251. }
  252. }
  253. return
  254. }
  255. func (self *ChainManager) GetBlock(hash common.Hash) *types.Block {
  256. data, _ := self.blockDb.Get(append(blockHashPre, hash[:]...))
  257. if len(data) == 0 {
  258. return nil
  259. }
  260. var block types.StorageBlock
  261. if err := rlp.Decode(bytes.NewReader(data), &block); err != nil {
  262. chainlogger.Errorf("invalid block RLP for hash %x: %v", hash, err)
  263. return nil
  264. }
  265. return (*types.Block)(&block)
  266. }
  267. func (self *ChainManager) GetBlockByNumber(num uint64) *types.Block {
  268. self.mu.RLock()
  269. defer self.mu.RUnlock()
  270. key, _ := self.blockDb.Get(append(blockNumPre, big.NewInt(int64(num)).Bytes()...))
  271. if len(key) == 0 {
  272. return nil
  273. }
  274. return self.GetBlock(common.BytesToHash(key))
  275. }
  276. func (self *ChainManager) GetUnclesInChain(block *types.Block, length int) (uncles []*types.Header) {
  277. for i := 0; block != nil && i < length; i++ {
  278. uncles = append(uncles, block.Uncles()...)
  279. block = self.GetBlock(block.ParentHash())
  280. }
  281. return
  282. }
  283. func (self *ChainManager) GetAncestors(block *types.Block, length int) (blocks []*types.Block) {
  284. for i := 0; i < length; i++ {
  285. block = self.GetBlock(block.ParentHash())
  286. if block == nil {
  287. break
  288. }
  289. blocks = append(blocks, block)
  290. }
  291. return
  292. }
  293. func (bc *ChainManager) setTotalDifficulty(td *big.Int) {
  294. bc.blockDb.Put([]byte("LTD"), td.Bytes())
  295. bc.td = td
  296. }
  297. func (self *ChainManager) CalcTotalDiff(block *types.Block) (*big.Int, error) {
  298. parent := self.GetBlock(block.Header().ParentHash)
  299. if parent == nil {
  300. return nil, fmt.Errorf("Unable to calculate total diff without known parent %x", block.Header().ParentHash)
  301. }
  302. parentTd := parent.Td
  303. uncleDiff := new(big.Int)
  304. for _, uncle := range block.Uncles() {
  305. uncleDiff = uncleDiff.Add(uncleDiff, uncle.Difficulty)
  306. }
  307. td := new(big.Int)
  308. td = td.Add(parentTd, uncleDiff)
  309. td = td.Add(td, block.Header().Difficulty)
  310. return td, nil
  311. }
  312. func (bc *ChainManager) Stop() {
  313. close(bc.quit)
  314. }
  315. type queueEvent struct {
  316. queue []interface{}
  317. canonicalCount int
  318. sideCount int
  319. splitCount int
  320. }
  321. func (self *ChainManager) InsertChain(chain types.Blocks) error {
  322. //self.tsmu.Lock()
  323. //defer self.tsmu.Unlock()
  324. // A queued approach to delivering events. This is generally faster than direct delivery and requires much less mutex acquiring.
  325. var queue = make([]interface{}, len(chain))
  326. var queueEvent = queueEvent{queue: queue}
  327. for i, block := range chain {
  328. // Call in to the block processor and check for errors. It's likely that if one block fails
  329. // all others will fail too (unless a known block is returned).
  330. td, logs, err := self.processor.Process(block)
  331. if err != nil {
  332. if IsKnownBlockErr(err) {
  333. continue
  334. }
  335. h := block.Header()
  336. chainlogger.Infof("INVALID block #%v (%x)\n", h.Number, h.Hash().Bytes()[:4])
  337. chainlogger.Infoln(err)
  338. chainlogger.Debugln(block)
  339. return err
  340. }
  341. block.Td = td
  342. self.mu.Lock()
  343. cblock := self.currentBlock
  344. {
  345. // Write block to database. Eventually we'll have to improve on this and throw away blocks that are
  346. // not in the canonical chain.
  347. self.write(block)
  348. // Compare the TD of the last known block in the canonical chain to make sure it's greater.
  349. // At this point it's possible that a different chain (fork) becomes the new canonical chain.
  350. if td.Cmp(self.td) > 0 {
  351. if block.Header().Number.Cmp(new(big.Int).Add(cblock.Header().Number, common.Big1)) < 0 {
  352. chash := cblock.Hash()
  353. hash := block.Hash()
  354. 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)
  355. queue[i] = ChainSplitEvent{block, logs}
  356. queueEvent.splitCount++
  357. }
  358. self.setTotalDifficulty(td)
  359. self.insert(block)
  360. jsonlogger.LogJson(&logger.EthChainNewHead{
  361. BlockHash: block.Hash().Hex(),
  362. BlockNumber: block.Number(),
  363. ChainHeadHash: cblock.Hash().Hex(),
  364. BlockPrevHash: block.ParentHash().Hex(),
  365. })
  366. self.setTransState(state.New(block.Root(), self.stateDb))
  367. self.setTxState(state.New(block.Root(), self.stateDb))
  368. queue[i] = ChainEvent{block, logs}
  369. queueEvent.canonicalCount++
  370. } else {
  371. queue[i] = ChainSideEvent{block, logs}
  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. */