chain_manager.go 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404
  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. }
  70. func NewChainManager(db ethutil.Database, mux *event.TypeMux) *ChainManager {
  71. bc := &ChainManager{db: db, genesisBlock: GenesisBlock(db), eventMux: mux}
  72. bc.setLastBlock()
  73. bc.transState = bc.State().Copy()
  74. return bc
  75. }
  76. func (self *ChainManager) Td() *big.Int {
  77. self.mu.RLock()
  78. defer self.mu.RUnlock()
  79. return self.td
  80. }
  81. func (self *ChainManager) LastBlockHash() []byte {
  82. self.mu.RLock()
  83. defer self.mu.RUnlock()
  84. return self.lastBlockHash
  85. }
  86. func (self *ChainManager) CurrentBlock() *types.Block {
  87. self.mu.RLock()
  88. defer self.mu.RUnlock()
  89. return self.currentBlock
  90. }
  91. func (self *ChainManager) Status() (td *big.Int, currentBlock []byte, genesisBlock []byte) {
  92. self.mu.RLock()
  93. defer self.mu.RUnlock()
  94. return self.td, self.currentBlock.Hash(), self.Genesis().Hash()
  95. }
  96. func (self *ChainManager) SetProcessor(proc types.BlockProcessor) {
  97. self.processor = proc
  98. }
  99. func (self *ChainManager) State() *state.StateDB {
  100. return state.New(self.CurrentBlock().Root(), self.db)
  101. }
  102. func (self *ChainManager) TransState() *state.StateDB {
  103. self.tsmu.RLock()
  104. defer self.tsmu.RUnlock()
  105. //tmp := self.transState
  106. return self.transState
  107. }
  108. func (self *ChainManager) setTransState(statedb *state.StateDB) {
  109. self.tsmu.Lock()
  110. defer self.tsmu.Unlock()
  111. self.transState = statedb
  112. }
  113. func (bc *ChainManager) setLastBlock() {
  114. data, _ := bc.db.Get([]byte("LastBlock"))
  115. if len(data) != 0 {
  116. var block types.Block
  117. rlp.Decode(bytes.NewReader(data), &block)
  118. bc.currentBlock = &block
  119. bc.lastBlockHash = block.Hash()
  120. // Set the last know difficulty (might be 0x0 as initial value, Genesis)
  121. bc.td = ethutil.BigD(bc.db.LastKnownTD())
  122. } else {
  123. bc.Reset()
  124. }
  125. chainlogger.Infof("Last block (#%v) %x TD=%v\n", bc.currentBlock.Number(), bc.currentBlock.Hash(), bc.td)
  126. }
  127. // Block creation & chain handling
  128. func (bc *ChainManager) NewBlock(coinbase []byte) *types.Block {
  129. bc.mu.RLock()
  130. defer bc.mu.RUnlock()
  131. var root []byte
  132. parentHash := ZeroHash256
  133. if bc.currentBlock != nil {
  134. root = bc.currentBlock.Header().Root
  135. parentHash = bc.lastBlockHash
  136. }
  137. block := types.NewBlock(
  138. parentHash,
  139. coinbase,
  140. root,
  141. ethutil.BigPow(2, 32),
  142. nil,
  143. "")
  144. block.SetUncles(nil)
  145. block.SetTransactions(nil)
  146. block.SetReceipts(nil)
  147. parent := bc.currentBlock
  148. if parent != nil {
  149. header := block.Header()
  150. header.Difficulty = CalcDifficulty(block, parent)
  151. header.Number = new(big.Int).Add(parent.Header().Number, ethutil.Big1)
  152. header.GasLimit = CalcGasLimit(parent, block)
  153. }
  154. return block
  155. }
  156. func (bc *ChainManager) Reset() {
  157. bc.mu.Lock()
  158. defer bc.mu.Unlock()
  159. for block := bc.currentBlock; block != nil; block = bc.GetBlock(block.Header().ParentHash) {
  160. bc.db.Delete(block.Hash())
  161. }
  162. // Prepare the genesis block
  163. bc.write(bc.genesisBlock)
  164. bc.insert(bc.genesisBlock)
  165. bc.currentBlock = bc.genesisBlock
  166. bc.setTotalDifficulty(ethutil.Big("0"))
  167. }
  168. func (self *ChainManager) Export() []byte {
  169. self.mu.RLock()
  170. defer self.mu.RUnlock()
  171. chainlogger.Infof("exporting %v blocks...\n", self.currentBlock.Header().Number)
  172. blocks := make([]*types.Block, int(self.currentBlock.NumberU64())+1)
  173. for block := self.currentBlock; block != nil; block = self.GetBlock(block.Header().ParentHash) {
  174. blocks[block.NumberU64()] = block
  175. }
  176. return ethutil.Encode(blocks)
  177. }
  178. func (bc *ChainManager) insert(block *types.Block) {
  179. encodedBlock := ethutil.Encode(block)
  180. bc.db.Put([]byte("LastBlock"), encodedBlock)
  181. bc.currentBlock = block
  182. bc.lastBlockHash = block.Hash()
  183. }
  184. func (bc *ChainManager) write(block *types.Block) {
  185. encodedBlock := ethutil.Encode(block.RlpDataForStorage())
  186. bc.db.Put(block.Hash(), encodedBlock)
  187. }
  188. // Accessors
  189. func (bc *ChainManager) Genesis() *types.Block {
  190. return bc.genesisBlock
  191. }
  192. // Block fetching methods
  193. func (bc *ChainManager) HasBlock(hash []byte) bool {
  194. data, _ := bc.db.Get(hash)
  195. return len(data) != 0
  196. }
  197. func (self *ChainManager) GetBlockHashesFromHash(hash []byte, max uint64) (chain [][]byte) {
  198. block := self.GetBlock(hash)
  199. if block == nil {
  200. return
  201. }
  202. // XXX Could be optimised by using a different database which only holds hashes (i.e., linked list)
  203. for i := uint64(0); i < max; i++ {
  204. parentHash := block.Header().ParentHash
  205. block = self.GetBlock(parentHash)
  206. if block == nil {
  207. chainlogger.Infof("GetBlockHashesFromHash Parent UNKNOWN %x\n", parentHash)
  208. break
  209. }
  210. chain = append(chain, block.Hash())
  211. if block.Header().Number.Cmp(ethutil.Big0) <= 0 {
  212. break
  213. }
  214. }
  215. return
  216. }
  217. func (self *ChainManager) GetBlock(hash []byte) *types.Block {
  218. data, _ := self.db.Get(hash)
  219. if len(data) == 0 {
  220. return nil
  221. }
  222. var block types.Block
  223. if err := rlp.Decode(bytes.NewReader(data), &block); err != nil {
  224. fmt.Println(err)
  225. return nil
  226. }
  227. return &block
  228. }
  229. func (self *ChainManager) GetUnclesInChain(block *types.Block, length int) (uncles []*types.Header) {
  230. for i := 0; block != nil && i < length; i++ {
  231. uncles = append(uncles, block.Uncles()...)
  232. block = self.GetBlock(block.ParentHash())
  233. }
  234. return
  235. }
  236. func (self *ChainManager) GetAncestors(block *types.Block, length int) (blocks []*types.Block) {
  237. for i := 0; i < length; i++ {
  238. block = self.GetBlock(block.ParentHash())
  239. if block == nil {
  240. break
  241. }
  242. blocks = append(blocks, block)
  243. }
  244. return
  245. }
  246. func (self *ChainManager) GetBlockByNumber(num uint64) *types.Block {
  247. self.mu.RLock()
  248. defer self.mu.RUnlock()
  249. var block *types.Block
  250. if num <= self.currentBlock.Number().Uint64() {
  251. block = self.currentBlock
  252. for ; block != nil; block = self.GetBlock(block.Header().ParentHash) {
  253. if block.Header().Number.Uint64() == num {
  254. break
  255. }
  256. }
  257. }
  258. return block
  259. }
  260. func (bc *ChainManager) setTotalDifficulty(td *big.Int) {
  261. bc.db.Put([]byte("LTD"), td.Bytes())
  262. bc.td = td
  263. }
  264. func (self *ChainManager) CalcTotalDiff(block *types.Block) (*big.Int, error) {
  265. parent := self.GetBlock(block.Header().ParentHash)
  266. if parent == nil {
  267. return nil, fmt.Errorf("Unable to calculate total diff without known parent %x", block.Header().ParentHash)
  268. }
  269. parentTd := parent.Td
  270. uncleDiff := new(big.Int)
  271. for _, uncle := range block.Uncles() {
  272. uncleDiff = uncleDiff.Add(uncleDiff, uncle.Difficulty)
  273. }
  274. td := new(big.Int)
  275. td = td.Add(parentTd, uncleDiff)
  276. td = td.Add(td, block.Header().Difficulty)
  277. return td, nil
  278. }
  279. func (bc *ChainManager) Stop() {
  280. if bc.CurrentBlock != nil {
  281. chainlogger.Infoln("Stopped")
  282. }
  283. }
  284. func (self *ChainManager) InsertChain(chain types.Blocks) error {
  285. for _, block := range chain {
  286. td, err := self.processor.Process(block)
  287. if err != nil {
  288. if IsKnownBlockErr(err) {
  289. continue
  290. }
  291. h := block.Header()
  292. chainlogger.Infof("block #%v process failed (%x)\n", h.Number, h.Hash()[:4])
  293. chainlogger.Infoln(block)
  294. chainlogger.Infoln(err)
  295. return err
  296. }
  297. block.Td = td
  298. self.mu.Lock()
  299. {
  300. self.write(block)
  301. cblock := self.currentBlock
  302. if td.Cmp(self.td) > 0 {
  303. if block.Header().Number.Cmp(new(big.Int).Add(cblock.Header().Number, ethutil.Big1)) < 0 {
  304. 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)
  305. }
  306. self.setTotalDifficulty(td)
  307. self.insert(block)
  308. self.setTransState(state.New(cblock.Root(), self.db))
  309. self.eventMux.Post(ChainEvent{block, td})
  310. }
  311. }
  312. self.mu.Unlock()
  313. }
  314. return nil
  315. }
  316. // Satisfy state query interface
  317. func (self *ChainManager) GetAccount(addr []byte) *state.StateObject {
  318. return self.State().GetAccount(addr)
  319. }