chain_manager.go 11 KB

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