chain_manager.go 11 KB

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