chain_manager.go 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367
  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 StateQuery interface {
  16. GetAccount(addr []byte) *state.StateObject
  17. }
  18. func CalcDifficulty(block, parent *types.Block) *big.Int {
  19. diff := new(big.Int)
  20. bh, ph := block.Header(), parent.Header()
  21. adjust := new(big.Int).Rsh(ph.Difficulty, 10)
  22. if bh.Time >= ph.Time+5 {
  23. diff.Sub(ph.Difficulty, adjust)
  24. } else {
  25. diff.Add(ph.Difficulty, adjust)
  26. }
  27. return diff
  28. }
  29. func CalcGasLimit(parent, block *types.Block) *big.Int {
  30. if block.Number().Cmp(big.NewInt(0)) == 0 {
  31. return ethutil.BigPow(10, 6)
  32. }
  33. // ((1024-1) * parent.gasLimit + (gasUsed * 6 / 5)) / 1024
  34. previous := new(big.Int).Mul(big.NewInt(1024-1), parent.GasLimit())
  35. current := new(big.Rat).Mul(new(big.Rat).SetInt(parent.GasUsed()), big.NewRat(6, 5))
  36. curInt := new(big.Int).Div(current.Num(), current.Denom())
  37. result := new(big.Int).Add(previous, curInt)
  38. result.Div(result, big.NewInt(1024))
  39. min := big.NewInt(125000)
  40. return ethutil.BigMax(min, result)
  41. }
  42. type ChainManager struct {
  43. //eth EthManager
  44. processor types.BlockProcessor
  45. eventMux *event.TypeMux
  46. genesisBlock *types.Block
  47. // Last known total difficulty
  48. mu sync.RWMutex
  49. td *big.Int
  50. lastBlockNumber uint64
  51. currentBlock *types.Block
  52. lastBlockHash []byte
  53. transState *state.StateDB
  54. }
  55. func (self *ChainManager) Td() *big.Int {
  56. self.mu.RLock()
  57. defer self.mu.RUnlock()
  58. return self.td
  59. }
  60. func (self *ChainManager) LastBlockNumber() uint64 {
  61. self.mu.RLock()
  62. defer self.mu.RUnlock()
  63. return self.lastBlockNumber
  64. }
  65. func (self *ChainManager) LastBlockHash() []byte {
  66. self.mu.RLock()
  67. defer self.mu.RUnlock()
  68. return self.lastBlockHash
  69. }
  70. func (self *ChainManager) CurrentBlock() *types.Block {
  71. self.mu.RLock()
  72. defer self.mu.RUnlock()
  73. return self.currentBlock
  74. }
  75. func NewChainManager(mux *event.TypeMux) *ChainManager {
  76. bc := &ChainManager{}
  77. bc.genesisBlock = GenesisBlock()
  78. bc.eventMux = mux
  79. bc.setLastBlock()
  80. bc.transState = bc.State().Copy()
  81. return bc
  82. }
  83. func (self *ChainManager) Status() (td *big.Int, currentBlock []byte, genesisBlock []byte) {
  84. self.mu.RLock()
  85. defer self.mu.RUnlock()
  86. return self.td, self.currentBlock.Hash(), self.Genesis().Hash()
  87. }
  88. func (self *ChainManager) SetProcessor(proc types.BlockProcessor) {
  89. self.processor = proc
  90. }
  91. func (self *ChainManager) State() *state.StateDB {
  92. return state.New(self.CurrentBlock().Trie())
  93. }
  94. func (self *ChainManager) TransState() *state.StateDB {
  95. return self.transState
  96. }
  97. func (bc *ChainManager) setLastBlock() {
  98. data, _ := ethutil.Config.Db.Get([]byte("LastBlock"))
  99. if len(data) != 0 {
  100. var block types.Block
  101. rlp.Decode(bytes.NewReader(data), &block)
  102. bc.currentBlock = &block
  103. bc.lastBlockHash = block.Hash()
  104. bc.lastBlockNumber = block.Header().Number.Uint64()
  105. // Set the last know difficulty (might be 0x0 as initial value, Genesis)
  106. bc.td = ethutil.BigD(ethutil.Config.Db.LastKnownTD())
  107. } else {
  108. bc.Reset()
  109. }
  110. chainlogger.Infof("Last block (#%d) %x\n", bc.lastBlockNumber, bc.currentBlock.Hash())
  111. }
  112. // Block creation & chain handling
  113. func (bc *ChainManager) NewBlock(coinbase []byte) *types.Block {
  114. bc.mu.RLock()
  115. defer bc.mu.RUnlock()
  116. var root []byte
  117. parentHash := ZeroHash256
  118. if bc.CurrentBlock != nil {
  119. root = bc.currentBlock.Header().Root
  120. parentHash = bc.lastBlockHash
  121. }
  122. block := types.NewBlock(
  123. parentHash,
  124. coinbase,
  125. root,
  126. ethutil.BigPow(2, 32),
  127. nil,
  128. "")
  129. parent := bc.currentBlock
  130. if parent != nil {
  131. header := block.Header()
  132. header.Difficulty = CalcDifficulty(block, parent)
  133. header.Number = new(big.Int).Add(parent.Header().Number, ethutil.Big1)
  134. header.GasLimit = CalcGasLimit(parent, block)
  135. }
  136. return block
  137. }
  138. func (bc *ChainManager) Reset() {
  139. bc.mu.Lock()
  140. defer bc.mu.Unlock()
  141. for block := bc.currentBlock; block != nil; block = bc.GetBlock(block.Header().ParentHash) {
  142. ethutil.Config.Db.Delete(block.Hash())
  143. }
  144. // Prepare the genesis block
  145. bc.write(bc.genesisBlock)
  146. bc.insert(bc.genesisBlock)
  147. bc.currentBlock = bc.genesisBlock
  148. bc.setTotalDifficulty(ethutil.Big("0"))
  149. }
  150. func (self *ChainManager) Export() []byte {
  151. self.mu.RLock()
  152. defer self.mu.RUnlock()
  153. chainlogger.Infof("exporting %v blocks...\n", self.currentBlock.Header().Number)
  154. blocks := make([]*types.Block, int(self.currentBlock.NumberU64())+1)
  155. for block := self.currentBlock; block != nil; block = self.GetBlock(block.Header().ParentHash) {
  156. blocks[block.NumberU64()] = block
  157. }
  158. return ethutil.Encode(blocks)
  159. }
  160. func (bc *ChainManager) insert(block *types.Block) {
  161. encodedBlock := ethutil.Encode(block)
  162. ethutil.Config.Db.Put([]byte("LastBlock"), encodedBlock)
  163. bc.currentBlock = block
  164. bc.lastBlockHash = block.Hash()
  165. }
  166. func (bc *ChainManager) write(block *types.Block) {
  167. bc.writeBlockInfo(block)
  168. encodedBlock := ethutil.Encode(block)
  169. ethutil.Config.Db.Put(block.Hash(), encodedBlock)
  170. }
  171. // Accessors
  172. func (bc *ChainManager) Genesis() *types.Block {
  173. return bc.genesisBlock
  174. }
  175. // Block fetching methods
  176. func (bc *ChainManager) HasBlock(hash []byte) bool {
  177. data, _ := ethutil.Config.Db.Get(hash)
  178. return len(data) != 0
  179. }
  180. func (self *ChainManager) GetBlockHashesFromHash(hash []byte, max uint64) (chain [][]byte) {
  181. block := self.GetBlock(hash)
  182. if block == nil {
  183. return
  184. }
  185. // XXX Could be optimised by using a different database which only holds hashes (i.e., linked list)
  186. for i := uint64(0); i < max; i++ {
  187. chain = append(chain, block.Hash())
  188. if block.Header().Number.Cmp(ethutil.Big0) <= 0 {
  189. break
  190. }
  191. block = self.GetBlock(block.Header().ParentHash)
  192. }
  193. return
  194. }
  195. func (self *ChainManager) GetBlock(hash []byte) *types.Block {
  196. data, _ := ethutil.Config.Db.Get(hash)
  197. if len(data) == 0 {
  198. return nil
  199. }
  200. var block types.Block
  201. if err := rlp.Decode(bytes.NewReader(data), &block); err != nil {
  202. fmt.Println(err)
  203. return nil
  204. }
  205. return &block
  206. }
  207. func (self *ChainManager) GetBlockByNumber(num uint64) *types.Block {
  208. self.mu.RLock()
  209. defer self.mu.RUnlock()
  210. var block *types.Block
  211. if num <= self.currentBlock.Number().Uint64() {
  212. block = self.currentBlock
  213. for ; block != nil; block = self.GetBlock(block.Header().ParentHash) {
  214. if block.Header().Number.Uint64() == num {
  215. break
  216. }
  217. }
  218. }
  219. return block
  220. }
  221. func (bc *ChainManager) setTotalDifficulty(td *big.Int) {
  222. ethutil.Config.Db.Put([]byte("LTD"), td.Bytes())
  223. bc.td = td
  224. }
  225. func (self *ChainManager) CalcTotalDiff(block *types.Block) (*big.Int, error) {
  226. parent := self.GetBlock(block.Header().ParentHash)
  227. if parent == nil {
  228. return nil, fmt.Errorf("Unable to calculate total diff without known parent %x", block.Header().ParentHash)
  229. }
  230. parentTd := parent.Td
  231. uncleDiff := new(big.Int)
  232. for _, uncle := range block.Uncles() {
  233. uncleDiff = uncleDiff.Add(uncleDiff, uncle.Difficulty)
  234. }
  235. td := new(big.Int)
  236. td = td.Add(parentTd, uncleDiff)
  237. td = td.Add(td, block.Header().Difficulty)
  238. return td, nil
  239. }
  240. // Unexported method for writing extra non-essential block info to the db
  241. func (bc *ChainManager) writeBlockInfo(block *types.Block) {
  242. bc.lastBlockNumber++
  243. }
  244. func (bc *ChainManager) Stop() {
  245. if bc.CurrentBlock != nil {
  246. chainlogger.Infoln("Stopped")
  247. }
  248. }
  249. func (self *ChainManager) InsertChain(chain types.Blocks) error {
  250. for _, block := range chain {
  251. td, messages, err := self.processor.Process(block)
  252. if err != nil {
  253. if IsKnownBlockErr(err) {
  254. continue
  255. }
  256. h := block.Header()
  257. chainlogger.Infof("block #%v process failed (%x)\n", h.Number, h.Hash()[:4])
  258. chainlogger.Infoln(block)
  259. chainlogger.Infoln(err)
  260. return err
  261. }
  262. block.Td = td
  263. self.mu.Lock()
  264. {
  265. self.write(block)
  266. cblock := self.currentBlock
  267. if td.Cmp(self.td) > 0 {
  268. if block.Header().Number.Cmp(new(big.Int).Add(cblock.Header().Number, ethutil.Big1)) < 0 {
  269. chainlogger.Infof("Split detected. New head #%v (%x), was #%v (%x)\n", block.Header().Number, block.Hash()[:4], cblock.Header().Number, cblock.Hash()[:4])
  270. }
  271. self.setTotalDifficulty(td)
  272. self.insert(block)
  273. self.transState = state.New(cblock.Trie().Copy())
  274. }
  275. }
  276. self.mu.Unlock()
  277. self.eventMux.Post(NewBlockEvent{block})
  278. self.eventMux.Post(messages)
  279. }
  280. return nil
  281. }
  282. // Satisfy state query interface
  283. func (self *ChainManager) GetAccount(addr []byte) *state.StateObject {
  284. return self.State().GetAccount(addr)
  285. }