chain_manager.go 11 KB

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