chain_manager.go 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368
  1. package chain
  2. import (
  3. "bytes"
  4. "container/list"
  5. "fmt"
  6. "math/big"
  7. "github.com/ethereum/go-ethereum/chain/types"
  8. "github.com/ethereum/go-ethereum/ethutil"
  9. "github.com/ethereum/go-ethereum/logger"
  10. "github.com/ethereum/go-ethereum/state"
  11. )
  12. var chainlogger = logger.NewLogger("CHAIN")
  13. func AddTestNetFunds(block *types.Block) {
  14. for _, addr := range []string{
  15. "51ba59315b3a95761d0863b05ccc7a7f54703d99",
  16. "e4157b34ea9615cfbde6b4fda419828124b70c78",
  17. "b9c015918bdaba24b4ff057a92a3873d6eb201be",
  18. "6c386a4b26f73c802f34673f7248bb118f97424a",
  19. "cd2a3d9f938e13cd947ec05abc7fe734df8dd826",
  20. "2ef47100e0787b915105fd5e3f4ff6752079d5cb",
  21. "e6716f9544a56c530d868e4bfbacb172315bdead",
  22. "1a26338f0d905e295fccb71fa9ea849ffa12aaf4",
  23. } {
  24. codedAddr := ethutil.Hex2Bytes(addr)
  25. account := block.State().GetAccount(codedAddr)
  26. account.SetBalance(ethutil.Big("1606938044258990275541962092341162602522202993782792835301376")) //ethutil.BigPow(2, 200)
  27. block.State().UpdateStateObject(account)
  28. }
  29. }
  30. func CalcDifficulty(block, parent *types.Block) *big.Int {
  31. diff := new(big.Int)
  32. adjust := new(big.Int).Rsh(parent.Difficulty, 10)
  33. if block.Time >= parent.Time+5 {
  34. diff.Sub(parent.Difficulty, adjust)
  35. } else {
  36. diff.Add(parent.Difficulty, adjust)
  37. }
  38. return diff
  39. }
  40. type ChainManager struct {
  41. //eth EthManager
  42. processor types.BlockProcessor
  43. genesisBlock *types.Block
  44. // Last known total difficulty
  45. TD *big.Int
  46. LastBlockNumber uint64
  47. CurrentBlock *types.Block
  48. LastBlockHash []byte
  49. workingChain *BlockChain
  50. }
  51. func NewChainManager() *ChainManager {
  52. bc := &ChainManager{}
  53. bc.genesisBlock = types.NewBlockFromBytes(ethutil.Encode(Genesis))
  54. //bc.eth = ethereum
  55. bc.setLastBlock()
  56. return bc
  57. }
  58. func (self *ChainManager) SetProcessor(proc types.BlockProcessor) {
  59. self.processor = proc
  60. }
  61. func (bc *ChainManager) setLastBlock() {
  62. data, _ := ethutil.Config.Db.Get([]byte("LastBlock"))
  63. if len(data) != 0 {
  64. // Prep genesis
  65. AddTestNetFunds(bc.genesisBlock)
  66. block := types.NewBlockFromBytes(data)
  67. bc.CurrentBlock = block
  68. bc.LastBlockHash = block.Hash()
  69. bc.LastBlockNumber = block.Number.Uint64()
  70. // Set the last know difficulty (might be 0x0 as initial value, Genesis)
  71. bc.TD = ethutil.BigD(ethutil.Config.Db.LastKnownTD())
  72. } else {
  73. bc.Reset()
  74. }
  75. chainlogger.Infof("Last block (#%d) %x\n", bc.LastBlockNumber, bc.CurrentBlock.Hash())
  76. }
  77. // Block creation & chain handling
  78. func (bc *ChainManager) NewBlock(coinbase []byte) *types.Block {
  79. var root interface{}
  80. hash := ZeroHash256
  81. if bc.CurrentBlock != nil {
  82. root = bc.CurrentBlock.Root()
  83. hash = bc.LastBlockHash
  84. }
  85. block := types.CreateBlock(
  86. root,
  87. hash,
  88. coinbase,
  89. ethutil.BigPow(2, 32),
  90. nil,
  91. "")
  92. block.MinGasPrice = big.NewInt(10000000000000)
  93. parent := bc.CurrentBlock
  94. if parent != nil {
  95. block.Difficulty = CalcDifficulty(block, parent)
  96. block.Number = new(big.Int).Add(bc.CurrentBlock.Number, ethutil.Big1)
  97. block.GasLimit = block.CalcGasLimit(bc.CurrentBlock)
  98. }
  99. return block
  100. }
  101. func (bc *ChainManager) Reset() {
  102. AddTestNetFunds(bc.genesisBlock)
  103. bc.genesisBlock.Trie().Sync()
  104. // Prepare the genesis block
  105. bc.add(bc.genesisBlock)
  106. bc.CurrentBlock = bc.genesisBlock
  107. bc.SetTotalDifficulty(ethutil.Big("0"))
  108. // Set the last know difficulty (might be 0x0 as initial value, Genesis)
  109. bc.TD = ethutil.BigD(ethutil.Config.Db.LastKnownTD())
  110. }
  111. // Add a block to the chain and record addition information
  112. func (bc *ChainManager) add(block *types.Block) {
  113. bc.writeBlockInfo(block)
  114. bc.CurrentBlock = block
  115. bc.LastBlockHash = block.Hash()
  116. encodedBlock := block.RlpEncode()
  117. ethutil.Config.Db.Put(block.Hash(), encodedBlock)
  118. ethutil.Config.Db.Put([]byte("LastBlock"), encodedBlock)
  119. //chainlogger.Infof("Imported block #%d (%x...)\n", block.Number, block.Hash()[0:4])
  120. }
  121. // Accessors
  122. func (bc *ChainManager) Genesis() *types.Block {
  123. return bc.genesisBlock
  124. }
  125. // Block fetching methods
  126. func (bc *ChainManager) HasBlock(hash []byte) bool {
  127. data, _ := ethutil.Config.Db.Get(hash)
  128. return len(data) != 0
  129. }
  130. func (self *ChainManager) GetChainHashesFromHash(hash []byte, max uint64) (chain [][]byte) {
  131. block := self.GetBlock(hash)
  132. if block == nil {
  133. return
  134. }
  135. // XXX Could be optimised by using a different database which only holds hashes (i.e., linked list)
  136. for i := uint64(0); i < max; i++ {
  137. chain = append(chain, block.Hash())
  138. if block.Number.Cmp(ethutil.Big0) <= 0 {
  139. break
  140. }
  141. block = self.GetBlock(block.PrevHash)
  142. }
  143. return
  144. }
  145. func (self *ChainManager) GetBlock(hash []byte) *types.Block {
  146. data, _ := ethutil.Config.Db.Get(hash)
  147. if len(data) == 0 {
  148. if self.workingChain != nil {
  149. // Check the temp chain
  150. for e := self.workingChain.Front(); e != nil; e = e.Next() {
  151. if bytes.Compare(e.Value.(*link).Block.Hash(), hash) == 0 {
  152. return e.Value.(*link).Block
  153. }
  154. }
  155. }
  156. return nil
  157. }
  158. return types.NewBlockFromBytes(data)
  159. }
  160. func (self *ChainManager) GetBlockByNumber(num uint64) *types.Block {
  161. block := self.CurrentBlock
  162. for ; block != nil; block = self.GetBlock(block.PrevHash) {
  163. if block.Number.Uint64() == num {
  164. break
  165. }
  166. }
  167. if block != nil && block.Number.Uint64() == 0 && num != 0 {
  168. return nil
  169. }
  170. return block
  171. }
  172. func (bc *ChainManager) SetTotalDifficulty(td *big.Int) {
  173. ethutil.Config.Db.Put([]byte("LTD"), td.Bytes())
  174. bc.TD = td
  175. }
  176. func (self *ChainManager) CalcTotalDiff(block *types.Block) (*big.Int, error) {
  177. parent := self.GetBlock(block.PrevHash)
  178. if parent == nil {
  179. return nil, fmt.Errorf("Unable to calculate total diff without known parent %x", block.PrevHash)
  180. }
  181. parentTd := parent.BlockInfo().TD
  182. uncleDiff := new(big.Int)
  183. for _, uncle := range block.Uncles {
  184. uncleDiff = uncleDiff.Add(uncleDiff, uncle.Difficulty)
  185. }
  186. td := new(big.Int)
  187. td = td.Add(parentTd, uncleDiff)
  188. td = td.Add(td, block.Difficulty)
  189. return td, nil
  190. }
  191. func (bc *ChainManager) BlockInfo(block *types.Block) types.BlockInfo {
  192. bi := types.BlockInfo{}
  193. data, _ := ethutil.Config.Db.Get(append(block.Hash(), []byte("Info")...))
  194. bi.RlpDecode(data)
  195. return bi
  196. }
  197. // Unexported method for writing extra non-essential block info to the db
  198. func (bc *ChainManager) writeBlockInfo(block *types.Block) {
  199. bc.LastBlockNumber++
  200. bi := types.BlockInfo{Number: bc.LastBlockNumber, Hash: block.Hash(), Parent: block.PrevHash, TD: bc.TD}
  201. // For now we use the block hash with the words "info" appended as key
  202. ethutil.Config.Db.Put(append(block.Hash(), []byte("Info")...), bi.RlpEncode())
  203. }
  204. func (bc *ChainManager) Stop() {
  205. if bc.CurrentBlock != nil {
  206. chainlogger.Infoln("Stopped")
  207. }
  208. }
  209. func (self *ChainManager) NewIterator(startHash []byte) *ChainIterator {
  210. return &ChainIterator{self, self.GetBlock(startHash)}
  211. }
  212. // This function assumes you've done your checking. No checking is done at this stage anymore
  213. func (self *ChainManager) InsertChain(chain *BlockChain, call func(*types.Block, state.Messages)) {
  214. for e := chain.Front(); e != nil; e = e.Next() {
  215. link := e.Value.(*link)
  216. self.add(link.Block)
  217. self.SetTotalDifficulty(link.Td)
  218. call(link.Block, link.Messages)
  219. }
  220. b, e := chain.Front(), chain.Back()
  221. if b != nil && e != nil {
  222. front, back := b.Value.(*link).Block, e.Value.(*link).Block
  223. chainlogger.Infof("Imported %d blocks. #%v (%x) / %#v (%x)", chain.Len(), front.Number, front.Hash()[0:4], back.Number, back.Hash()[0:4])
  224. }
  225. }
  226. func (self *ChainManager) TestChain(chain *BlockChain) (td *big.Int, err error) {
  227. self.workingChain = chain
  228. defer func() { self.workingChain = nil }()
  229. for e := chain.Front(); e != nil; e = e.Next() {
  230. var (
  231. l = e.Value.(*link)
  232. block = l.Block
  233. parent = self.GetBlock(block.PrevHash)
  234. )
  235. if parent == nil {
  236. err = fmt.Errorf("incoming chain broken on hash %x\n", block.PrevHash[0:4])
  237. return
  238. }
  239. var messages state.Messages
  240. td, messages, err = self.processor.ProcessWithParent(block, parent) //self.eth.BlockManager().ProcessWithParent(block, parent)
  241. if err != nil {
  242. chainlogger.Infoln(err)
  243. chainlogger.Debugf("Block #%v failed (%x...)\n", block.Number, block.Hash()[0:4])
  244. chainlogger.Debugln(block)
  245. err = fmt.Errorf("incoming chain failed %v\n", err)
  246. return
  247. }
  248. l.Td = td
  249. l.Messages = messages
  250. }
  251. if td.Cmp(self.TD) <= 0 {
  252. err = &TDError{td, self.TD}
  253. return
  254. }
  255. self.workingChain = nil
  256. return
  257. }
  258. type link struct {
  259. Block *types.Block
  260. Messages state.Messages
  261. Td *big.Int
  262. }
  263. type BlockChain struct {
  264. *list.List
  265. }
  266. func NewChain(blocks types.Blocks) *BlockChain {
  267. chain := &BlockChain{list.New()}
  268. for _, block := range blocks {
  269. chain.PushBack(&link{block, nil, nil})
  270. }
  271. return chain
  272. }
  273. func (self *BlockChain) RlpEncode() []byte {
  274. dat := make([]interface{}, 0)
  275. for e := self.Front(); e != nil; e = e.Next() {
  276. dat = append(dat, e.Value.(*link).Block.RlpData())
  277. }
  278. return ethutil.Encode(dat)
  279. }
  280. type ChainIterator struct {
  281. cm *ChainManager
  282. block *types.Block // current block in the iterator
  283. }
  284. func (self *ChainIterator) Prev() *types.Block {
  285. self.block = self.cm.GetBlock(self.block.PrevHash)
  286. return self.block
  287. }