block.go 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419
  1. package chain
  2. import (
  3. "bytes"
  4. "fmt"
  5. "math/big"
  6. "sort"
  7. "time"
  8. "github.com/ethereum/go-ethereum/crypto"
  9. "github.com/ethereum/go-ethereum/ethutil"
  10. "github.com/ethereum/go-ethereum/state"
  11. "github.com/ethereum/go-ethereum/trie"
  12. )
  13. type BlockInfo struct {
  14. Number uint64
  15. Hash []byte
  16. Parent []byte
  17. TD *big.Int
  18. }
  19. func (bi *BlockInfo) RlpDecode(data []byte) {
  20. decoder := ethutil.NewValueFromBytes(data)
  21. bi.Number = decoder.Get(0).Uint()
  22. bi.Hash = decoder.Get(1).Bytes()
  23. bi.Parent = decoder.Get(2).Bytes()
  24. bi.TD = decoder.Get(3).BigInt()
  25. }
  26. func (bi *BlockInfo) RlpEncode() []byte {
  27. return ethutil.Encode([]interface{}{bi.Number, bi.Hash, bi.Parent, bi.TD})
  28. }
  29. type Blocks []*Block
  30. func (self Blocks) AsSet() ethutil.UniqueSet {
  31. set := make(ethutil.UniqueSet)
  32. for _, block := range self {
  33. set.Insert(block.Hash())
  34. }
  35. return set
  36. }
  37. type BlockBy func(b1, b2 *Block) bool
  38. func (self BlockBy) Sort(blocks Blocks) {
  39. bs := blockSorter{
  40. blocks: blocks,
  41. by: self,
  42. }
  43. sort.Sort(bs)
  44. }
  45. type blockSorter struct {
  46. blocks Blocks
  47. by func(b1, b2 *Block) bool
  48. }
  49. func (self blockSorter) Len() int { return len(self.blocks) }
  50. func (self blockSorter) Swap(i, j int) {
  51. self.blocks[i], self.blocks[j] = self.blocks[j], self.blocks[i]
  52. }
  53. func (self blockSorter) Less(i, j int) bool { return self.by(self.blocks[i], self.blocks[j]) }
  54. func Number(b1, b2 *Block) bool { return b1.Number.Cmp(b2.Number) < 0 }
  55. type Block struct {
  56. // Hash to the previous block
  57. PrevHash ethutil.Bytes
  58. // Uncles of this block
  59. Uncles Blocks
  60. UncleSha []byte
  61. // The coin base address
  62. Coinbase []byte
  63. // Block Trie state
  64. //state *ethutil.Trie
  65. state *state.State
  66. // Difficulty for the current block
  67. Difficulty *big.Int
  68. // Creation time
  69. Time int64
  70. // The block number
  71. Number *big.Int
  72. // Minimum Gas Price
  73. MinGasPrice *big.Int
  74. // Gas limit
  75. GasLimit *big.Int
  76. // Gas used
  77. GasUsed *big.Int
  78. // Extra data
  79. Extra string
  80. // Block Nonce for verification
  81. Nonce ethutil.Bytes
  82. // List of transactions and/or contracts
  83. transactions Transactions
  84. receipts Receipts
  85. TxSha, ReceiptSha []byte
  86. LogsBloom []byte
  87. }
  88. func NewBlockFromBytes(raw []byte) *Block {
  89. block := &Block{}
  90. block.RlpDecode(raw)
  91. return block
  92. }
  93. // New block takes a raw encoded string
  94. func NewBlockFromRlpValue(rlpValue *ethutil.Value) *Block {
  95. block := &Block{}
  96. block.RlpValueDecode(rlpValue)
  97. return block
  98. }
  99. func CreateBlock(root interface{},
  100. prevHash []byte,
  101. base []byte,
  102. Difficulty *big.Int,
  103. Nonce []byte,
  104. extra string) *Block {
  105. block := &Block{
  106. PrevHash: prevHash,
  107. Coinbase: base,
  108. Difficulty: Difficulty,
  109. Nonce: Nonce,
  110. Time: time.Now().Unix(),
  111. Extra: extra,
  112. UncleSha: nil,
  113. GasUsed: new(big.Int),
  114. MinGasPrice: new(big.Int),
  115. GasLimit: new(big.Int),
  116. }
  117. block.SetUncles([]*Block{})
  118. block.state = state.New(trie.New(ethutil.Config.Db, root))
  119. return block
  120. }
  121. // Returns a hash of the block
  122. func (block *Block) Hash() ethutil.Bytes {
  123. return crypto.Sha3(ethutil.NewValue(block.header()).Encode())
  124. //return crypto.Sha3(block.Value().Encode())
  125. }
  126. func (block *Block) HashNoNonce() []byte {
  127. return crypto.Sha3(ethutil.Encode(block.miningHeader()))
  128. }
  129. func (block *Block) State() *state.State {
  130. return block.state
  131. }
  132. func (block *Block) Transactions() []*Transaction {
  133. return block.transactions
  134. }
  135. func (block *Block) CalcGasLimit(parent *Block) *big.Int {
  136. if block.Number.Cmp(big.NewInt(0)) == 0 {
  137. return ethutil.BigPow(10, 6)
  138. }
  139. // ((1024-1) * parent.gasLimit + (gasUsed * 6 / 5)) / 1024
  140. previous := new(big.Int).Mul(big.NewInt(1024-1), parent.GasLimit)
  141. current := new(big.Rat).Mul(new(big.Rat).SetInt(parent.GasUsed), big.NewRat(6, 5))
  142. curInt := new(big.Int).Div(current.Num(), current.Denom())
  143. result := new(big.Int).Add(previous, curInt)
  144. result.Div(result, big.NewInt(1024))
  145. min := big.NewInt(125000)
  146. return ethutil.BigMax(min, result)
  147. }
  148. func (block *Block) BlockInfo() BlockInfo {
  149. bi := BlockInfo{}
  150. data, _ := ethutil.Config.Db.Get(append(block.Hash(), []byte("Info")...))
  151. bi.RlpDecode(data)
  152. return bi
  153. }
  154. func (self *Block) GetTransaction(hash []byte) *Transaction {
  155. for _, tx := range self.transactions {
  156. if bytes.Compare(tx.Hash(), hash) == 0 {
  157. return tx
  158. }
  159. }
  160. return nil
  161. }
  162. // Sync the block's state and contract respectively
  163. func (block *Block) Sync() {
  164. block.state.Sync()
  165. }
  166. func (block *Block) Undo() {
  167. // Sync the block state itself
  168. block.state.Reset()
  169. }
  170. /////// Block Encoding
  171. func (block *Block) rlpReceipts() interface{} {
  172. // Marshal the transactions of this block
  173. encR := make([]interface{}, len(block.receipts))
  174. for i, r := range block.receipts {
  175. // Cast it to a string (safe)
  176. encR[i] = r.RlpData()
  177. }
  178. return encR
  179. }
  180. func (block *Block) rlpUncles() interface{} {
  181. // Marshal the transactions of this block
  182. uncles := make([]interface{}, len(block.Uncles))
  183. for i, uncle := range block.Uncles {
  184. // Cast it to a string (safe)
  185. uncles[i] = uncle.header()
  186. }
  187. return uncles
  188. }
  189. func (block *Block) SetUncles(uncles []*Block) {
  190. block.Uncles = uncles
  191. block.UncleSha = crypto.Sha3(ethutil.Encode(block.rlpUncles()))
  192. }
  193. func (self *Block) SetReceipts(receipts Receipts) {
  194. self.receipts = receipts
  195. self.ReceiptSha = DeriveSha(receipts)
  196. self.LogsBloom = CreateBloom(self)
  197. }
  198. func (self *Block) SetTransactions(txs Transactions) {
  199. self.transactions = txs
  200. self.TxSha = DeriveSha(txs)
  201. }
  202. func (block *Block) Value() *ethutil.Value {
  203. return ethutil.NewValue([]interface{}{block.header(), block.transactions, block.rlpUncles()})
  204. }
  205. func (block *Block) RlpEncode() []byte {
  206. // Encode a slice interface which contains the header and the list of
  207. // transactions.
  208. return block.Value().Encode()
  209. }
  210. func (block *Block) RlpDecode(data []byte) {
  211. rlpValue := ethutil.NewValueFromBytes(data)
  212. block.RlpValueDecode(rlpValue)
  213. }
  214. func (block *Block) RlpValueDecode(decoder *ethutil.Value) {
  215. block.setHeader(decoder.Get(0))
  216. // Tx list might be empty if this is an uncle. Uncles only have their
  217. // header set.
  218. if decoder.Get(1).IsNil() == false { // Yes explicitness
  219. //receipts := decoder.Get(1)
  220. //block.receipts = make([]*Receipt, receipts.Len())
  221. txs := decoder.Get(1)
  222. block.transactions = make(Transactions, txs.Len())
  223. for i := 0; i < txs.Len(); i++ {
  224. block.transactions[i] = NewTransactionFromValue(txs.Get(i))
  225. //receipt := NewRecieptFromValue(receipts.Get(i))
  226. //block.transactions[i] = receipt.Tx
  227. //block.receipts[i] = receipt
  228. }
  229. }
  230. if decoder.Get(2).IsNil() == false { // Yes explicitness
  231. uncles := decoder.Get(2)
  232. block.Uncles = make([]*Block, uncles.Len())
  233. for i := 0; i < uncles.Len(); i++ {
  234. block.Uncles[i] = NewUncleBlockFromValue(uncles.Get(i))
  235. }
  236. }
  237. }
  238. func (self *Block) setHeader(header *ethutil.Value) {
  239. self.PrevHash = header.Get(0).Bytes()
  240. self.UncleSha = header.Get(1).Bytes()
  241. self.Coinbase = header.Get(2).Bytes()
  242. self.state = state.New(trie.New(ethutil.Config.Db, header.Get(3).Val))
  243. self.TxSha = header.Get(4).Bytes()
  244. self.ReceiptSha = header.Get(5).Bytes()
  245. self.LogsBloom = header.Get(6).Bytes()
  246. self.Difficulty = header.Get(7).BigInt()
  247. self.Number = header.Get(8).BigInt()
  248. self.MinGasPrice = header.Get(9).BigInt()
  249. self.GasLimit = header.Get(10).BigInt()
  250. self.GasUsed = header.Get(11).BigInt()
  251. self.Time = int64(header.Get(12).BigInt().Uint64())
  252. self.Extra = header.Get(13).Str()
  253. self.Nonce = header.Get(14).Bytes()
  254. }
  255. func NewUncleBlockFromValue(header *ethutil.Value) *Block {
  256. block := &Block{}
  257. block.setHeader(header)
  258. return block
  259. }
  260. func (block *Block) Trie() *trie.Trie {
  261. return block.state.Trie
  262. }
  263. func (block *Block) GetRoot() interface{} {
  264. return block.state.Trie.Root
  265. }
  266. func (block *Block) Diff() *big.Int {
  267. return block.Difficulty
  268. }
  269. func (self *Block) Receipts() []*Receipt {
  270. return self.receipts
  271. }
  272. func (block *Block) miningHeader() []interface{} {
  273. return []interface{}{
  274. // Sha of the previous block
  275. block.PrevHash,
  276. // Sha of uncles
  277. block.UncleSha,
  278. // Coinbase address
  279. block.Coinbase,
  280. // root state
  281. block.state.Trie.Root,
  282. // tx root
  283. block.TxSha,
  284. // Sha of tx
  285. block.ReceiptSha,
  286. // Bloom
  287. block.LogsBloom,
  288. // Current block Difficulty
  289. block.Difficulty,
  290. // The block number
  291. block.Number,
  292. // Block minimum gas price
  293. block.MinGasPrice,
  294. // Block upper gas bound
  295. block.GasLimit,
  296. // Block gas used
  297. block.GasUsed,
  298. // Time the block was found?
  299. block.Time,
  300. // Extra data
  301. block.Extra,
  302. }
  303. }
  304. func (block *Block) header() []interface{} {
  305. return append(block.miningHeader(), block.Nonce)
  306. }
  307. func (block *Block) String() string {
  308. return fmt.Sprintf(`
  309. BLOCK(%x): Size: %v
  310. PrevHash: %x
  311. UncleSha: %x
  312. Coinbase: %x
  313. Root: %x
  314. TxSha %x
  315. ReceiptSha: %x
  316. Bloom: %x
  317. Difficulty: %v
  318. Number: %v
  319. MinGas: %v
  320. MaxLimit: %v
  321. GasUsed: %v
  322. Time: %v
  323. Extra: %v
  324. Nonce: %x
  325. NumTx: %v
  326. `,
  327. block.Hash(),
  328. block.Size(),
  329. block.PrevHash,
  330. block.UncleSha,
  331. block.Coinbase,
  332. block.state.Trie.Root,
  333. block.TxSha,
  334. block.ReceiptSha,
  335. block.LogsBloom,
  336. block.Difficulty,
  337. block.Number,
  338. block.MinGasPrice,
  339. block.GasLimit,
  340. block.GasUsed,
  341. block.Time,
  342. block.Extra,
  343. block.Nonce,
  344. len(block.transactions),
  345. )
  346. }
  347. func (self *Block) Size() ethutil.StorageSize {
  348. return ethutil.StorageSize(len(self.RlpEncode()))
  349. }
  350. // Implement RlpEncodable
  351. func (self *Block) RlpData() interface{} {
  352. return self.Value().Val
  353. }