chain_manager.go 10 KB

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