chain_util.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392
  1. // Copyright 2015 The go-ethereum Authors
  2. // This file is part of the go-ethereum library.
  3. //
  4. // The go-ethereum library is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Lesser General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // The go-ethereum library is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Lesser General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Lesser General Public License
  15. // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
  16. package core
  17. import (
  18. "bytes"
  19. "encoding/binary"
  20. "fmt"
  21. "math/big"
  22. "github.com/ethereum/go-ethereum/common"
  23. "github.com/ethereum/go-ethereum/core/types"
  24. "github.com/ethereum/go-ethereum/ethdb"
  25. "github.com/ethereum/go-ethereum/logger"
  26. "github.com/ethereum/go-ethereum/logger/glog"
  27. "github.com/ethereum/go-ethereum/params"
  28. "github.com/ethereum/go-ethereum/rlp"
  29. )
  30. var (
  31. headHeaderKey = []byte("LastHeader")
  32. headBlockKey = []byte("LastBlock")
  33. blockPrefix = []byte("block-")
  34. blockNumPrefix = []byte("block-num-")
  35. headerSuffix = []byte("-header")
  36. bodySuffix = []byte("-body")
  37. tdSuffix = []byte("-td")
  38. ExpDiffPeriod = big.NewInt(100000)
  39. blockHashPre = []byte("block-hash-") // [deprecated by eth/63]
  40. mipmapPre = []byte("mipmap-log-bloom-")
  41. MIPMapLevels = []uint64{1000000, 500000, 100000, 50000, 1000}
  42. )
  43. // CalcDifficulty is the difficulty adjustment algorithm. It returns
  44. // the difficulty that a new block b should have when created at time
  45. // given the parent block's time and difficulty.
  46. func CalcDifficulty(time, parentTime uint64, parentNumber, parentDiff *big.Int) *big.Int {
  47. diff := new(big.Int)
  48. adjust := new(big.Int).Div(parentDiff, params.DifficultyBoundDivisor)
  49. bigTime := new(big.Int)
  50. bigParentTime := new(big.Int)
  51. bigTime.SetUint64(time)
  52. bigParentTime.SetUint64(parentTime)
  53. if bigTime.Sub(bigTime, bigParentTime).Cmp(params.DurationLimit) < 0 {
  54. diff.Add(parentDiff, adjust)
  55. } else {
  56. diff.Sub(parentDiff, adjust)
  57. }
  58. if diff.Cmp(params.MinimumDifficulty) < 0 {
  59. diff = params.MinimumDifficulty
  60. }
  61. periodCount := new(big.Int).Add(parentNumber, common.Big1)
  62. periodCount.Div(periodCount, ExpDiffPeriod)
  63. if periodCount.Cmp(common.Big1) > 0 {
  64. // diff = diff + 2^(periodCount - 2)
  65. expDiff := periodCount.Sub(periodCount, common.Big2)
  66. expDiff.Exp(common.Big2, expDiff, nil)
  67. diff.Add(diff, expDiff)
  68. diff = common.BigMax(diff, params.MinimumDifficulty)
  69. }
  70. return diff
  71. }
  72. // CalcGasLimit computes the gas limit of the next block after parent.
  73. // The result may be modified by the caller.
  74. // This is miner strategy, not consensus protocol.
  75. func CalcGasLimit(parent *types.Block) *big.Int {
  76. // contrib = (parentGasUsed * 3 / 2) / 1024
  77. contrib := new(big.Int).Mul(parent.GasUsed(), big.NewInt(3))
  78. contrib = contrib.Div(contrib, big.NewInt(2))
  79. contrib = contrib.Div(contrib, params.GasLimitBoundDivisor)
  80. // decay = parentGasLimit / 1024 -1
  81. decay := new(big.Int).Div(parent.GasLimit(), params.GasLimitBoundDivisor)
  82. decay.Sub(decay, big.NewInt(1))
  83. /*
  84. strategy: gasLimit of block-to-mine is set based on parent's
  85. gasUsed value. if parentGasUsed > parentGasLimit * (2/3) then we
  86. increase it, otherwise lower it (or leave it unchanged if it's right
  87. at that usage) the amount increased/decreased depends on how far away
  88. from parentGasLimit * (2/3) parentGasUsed is.
  89. */
  90. gl := new(big.Int).Sub(parent.GasLimit(), decay)
  91. gl = gl.Add(gl, contrib)
  92. gl.Set(common.BigMax(gl, params.MinGasLimit))
  93. // however, if we're now below the target (GenesisGasLimit) we increase the
  94. // limit as much as we can (parentGasLimit / 1024 -1)
  95. if gl.Cmp(params.GenesisGasLimit) < 0 {
  96. gl.Add(parent.GasLimit(), decay)
  97. gl.Set(common.BigMin(gl, params.GenesisGasLimit))
  98. }
  99. return gl
  100. }
  101. // GetCanonicalHash retrieves a hash assigned to a canonical block number.
  102. func GetCanonicalHash(db ethdb.Database, number uint64) common.Hash {
  103. data, _ := db.Get(append(blockNumPrefix, big.NewInt(int64(number)).Bytes()...))
  104. if len(data) == 0 {
  105. return common.Hash{}
  106. }
  107. return common.BytesToHash(data)
  108. }
  109. // GetHeadHeaderHash retrieves the hash of the current canonical head block's
  110. // header. The difference between this and GetHeadBlockHash is that whereas the
  111. // last block hash is only updated upon a full block import, the last header
  112. // hash is updated already at header import, allowing head tracking for the
  113. // fast synchronization mechanism.
  114. func GetHeadHeaderHash(db ethdb.Database) common.Hash {
  115. data, _ := db.Get(headHeaderKey)
  116. if len(data) == 0 {
  117. return common.Hash{}
  118. }
  119. return common.BytesToHash(data)
  120. }
  121. // GetHeadBlockHash retrieves the hash of the current canonical head block.
  122. func GetHeadBlockHash(db ethdb.Database) common.Hash {
  123. data, _ := db.Get(headBlockKey)
  124. if len(data) == 0 {
  125. return common.Hash{}
  126. }
  127. return common.BytesToHash(data)
  128. }
  129. // GetHeaderRLP retrieves a block header in its raw RLP database encoding, or nil
  130. // if the header's not found.
  131. func GetHeaderRLP(db ethdb.Database, hash common.Hash) rlp.RawValue {
  132. data, _ := db.Get(append(append(blockPrefix, hash[:]...), headerSuffix...))
  133. return data
  134. }
  135. // GetHeader retrieves the block header corresponding to the hash, nil if none
  136. // found.
  137. func GetHeader(db ethdb.Database, hash common.Hash) *types.Header {
  138. data := GetHeaderRLP(db, hash)
  139. if len(data) == 0 {
  140. return nil
  141. }
  142. header := new(types.Header)
  143. if err := rlp.Decode(bytes.NewReader(data), header); err != nil {
  144. glog.V(logger.Error).Infof("invalid block header RLP for hash %x: %v", hash, err)
  145. return nil
  146. }
  147. return header
  148. }
  149. // GetBodyRLP retrieves the block body (transactions and uncles) in RLP encoding.
  150. func GetBodyRLP(db ethdb.Database, hash common.Hash) rlp.RawValue {
  151. data, _ := db.Get(append(append(blockPrefix, hash[:]...), bodySuffix...))
  152. return data
  153. }
  154. // GetBody retrieves the block body (transactons, uncles) corresponding to the
  155. // hash, nil if none found.
  156. func GetBody(db ethdb.Database, hash common.Hash) *types.Body {
  157. data := GetBodyRLP(db, hash)
  158. if len(data) == 0 {
  159. return nil
  160. }
  161. body := new(types.Body)
  162. if err := rlp.Decode(bytes.NewReader(data), body); err != nil {
  163. glog.V(logger.Error).Infof("invalid block body RLP for hash %x: %v", hash, err)
  164. return nil
  165. }
  166. return body
  167. }
  168. // GetTd retrieves a block's total difficulty corresponding to the hash, nil if
  169. // none found.
  170. func GetTd(db ethdb.Database, hash common.Hash) *big.Int {
  171. data, _ := db.Get(append(append(blockPrefix, hash.Bytes()...), tdSuffix...))
  172. if len(data) == 0 {
  173. return nil
  174. }
  175. td := new(big.Int)
  176. if err := rlp.Decode(bytes.NewReader(data), td); err != nil {
  177. glog.V(logger.Error).Infof("invalid block total difficulty RLP for hash %x: %v", hash, err)
  178. return nil
  179. }
  180. return td
  181. }
  182. // GetBlock retrieves an entire block corresponding to the hash, assembling it
  183. // back from the stored header and body.
  184. func GetBlock(db ethdb.Database, hash common.Hash) *types.Block {
  185. // Retrieve the block header and body contents
  186. header := GetHeader(db, hash)
  187. if header == nil {
  188. return nil
  189. }
  190. body := GetBody(db, hash)
  191. if body == nil {
  192. return nil
  193. }
  194. // Reassemble the block and return
  195. return types.NewBlockWithHeader(header).WithBody(body.Transactions, body.Uncles)
  196. }
  197. // WriteCanonicalHash stores the canonical hash for the given block number.
  198. func WriteCanonicalHash(db ethdb.Database, hash common.Hash, number uint64) error {
  199. key := append(blockNumPrefix, big.NewInt(int64(number)).Bytes()...)
  200. if err := db.Put(key, hash.Bytes()); err != nil {
  201. glog.Fatalf("failed to store number to hash mapping into database: %v", err)
  202. return err
  203. }
  204. return nil
  205. }
  206. // WriteHeadHeaderHash stores the head header's hash.
  207. func WriteHeadHeaderHash(db ethdb.Database, hash common.Hash) error {
  208. if err := db.Put(headHeaderKey, hash.Bytes()); err != nil {
  209. glog.Fatalf("failed to store last header's hash into database: %v", err)
  210. return err
  211. }
  212. return nil
  213. }
  214. // WriteHeadBlockHash stores the head block's hash.
  215. func WriteHeadBlockHash(db ethdb.Database, hash common.Hash) error {
  216. if err := db.Put(headBlockKey, hash.Bytes()); err != nil {
  217. glog.Fatalf("failed to store last block's hash into database: %v", err)
  218. return err
  219. }
  220. return nil
  221. }
  222. // WriteHeader serializes a block header into the database.
  223. func WriteHeader(db ethdb.Database, header *types.Header) error {
  224. data, err := rlp.EncodeToBytes(header)
  225. if err != nil {
  226. return err
  227. }
  228. key := append(append(blockPrefix, header.Hash().Bytes()...), headerSuffix...)
  229. if err := db.Put(key, data); err != nil {
  230. glog.Fatalf("failed to store header into database: %v", err)
  231. return err
  232. }
  233. glog.V(logger.Debug).Infof("stored header #%v [%x…]", header.Number, header.Hash().Bytes()[:4])
  234. return nil
  235. }
  236. // WriteBody serializes the body of a block into the database.
  237. func WriteBody(db ethdb.Database, hash common.Hash, body *types.Body) error {
  238. data, err := rlp.EncodeToBytes(body)
  239. if err != nil {
  240. return err
  241. }
  242. key := append(append(blockPrefix, hash.Bytes()...), bodySuffix...)
  243. if err := db.Put(key, data); err != nil {
  244. glog.Fatalf("failed to store block body into database: %v", err)
  245. return err
  246. }
  247. glog.V(logger.Debug).Infof("stored block body [%x…]", hash.Bytes()[:4])
  248. return nil
  249. }
  250. // WriteTd serializes the total difficulty of a block into the database.
  251. func WriteTd(db ethdb.Database, hash common.Hash, td *big.Int) error {
  252. data, err := rlp.EncodeToBytes(td)
  253. if err != nil {
  254. return err
  255. }
  256. key := append(append(blockPrefix, hash.Bytes()...), tdSuffix...)
  257. if err := db.Put(key, data); err != nil {
  258. glog.Fatalf("failed to store block total difficulty into database: %v", err)
  259. return err
  260. }
  261. glog.V(logger.Debug).Infof("stored block total difficulty [%x…]: %v", hash.Bytes()[:4], td)
  262. return nil
  263. }
  264. // WriteBlock serializes a block into the database, header and body separately.
  265. func WriteBlock(db ethdb.Database, block *types.Block) error {
  266. // Store the body first to retain database consistency
  267. if err := WriteBody(db, block.Hash(), &types.Body{block.Transactions(), block.Uncles()}); err != nil {
  268. return err
  269. }
  270. // Store the header too, signaling full block ownership
  271. if err := WriteHeader(db, block.Header()); err != nil {
  272. return err
  273. }
  274. return nil
  275. }
  276. // DeleteCanonicalHash removes the number to hash canonical mapping.
  277. func DeleteCanonicalHash(db ethdb.Database, number uint64) {
  278. db.Delete(append(blockNumPrefix, big.NewInt(int64(number)).Bytes()...))
  279. }
  280. // DeleteHeader removes all block header data associated with a hash.
  281. func DeleteHeader(db ethdb.Database, hash common.Hash) {
  282. db.Delete(append(append(blockPrefix, hash.Bytes()...), headerSuffix...))
  283. }
  284. // DeleteBody removes all block body data associated with a hash.
  285. func DeleteBody(db ethdb.Database, hash common.Hash) {
  286. db.Delete(append(append(blockPrefix, hash.Bytes()...), bodySuffix...))
  287. }
  288. // DeleteTd removes all block total difficulty data associated with a hash.
  289. func DeleteTd(db ethdb.Database, hash common.Hash) {
  290. db.Delete(append(append(blockPrefix, hash.Bytes()...), tdSuffix...))
  291. }
  292. // DeleteBlock removes all block data associated with a hash.
  293. func DeleteBlock(db ethdb.Database, hash common.Hash) {
  294. DeleteHeader(db, hash)
  295. DeleteBody(db, hash)
  296. DeleteTd(db, hash)
  297. }
  298. // [deprecated by eth/63]
  299. // GetBlockByHashOld returns the old combined block corresponding to the hash
  300. // or nil if not found. This method is only used by the upgrade mechanism to
  301. // access the old combined block representation. It will be dropped after the
  302. // network transitions to eth/63.
  303. func GetBlockByHashOld(db ethdb.Database, hash common.Hash) *types.Block {
  304. data, _ := db.Get(append(blockHashPre, hash[:]...))
  305. if len(data) == 0 {
  306. return nil
  307. }
  308. var block types.StorageBlock
  309. if err := rlp.Decode(bytes.NewReader(data), &block); err != nil {
  310. glog.V(logger.Error).Infof("invalid block RLP for hash %x: %v", hash, err)
  311. return nil
  312. }
  313. return (*types.Block)(&block)
  314. }
  315. // returns a formatted MIP mapped key by adding prefix, canonical number and level
  316. //
  317. // ex. fn(98, 1000) = (prefix || 1000 || 0)
  318. func mipmapKey(num, level uint64) []byte {
  319. lkey := make([]byte, 8)
  320. binary.BigEndian.PutUint64(lkey, level)
  321. key := new(big.Int).SetUint64(num / level * level)
  322. return append(mipmapPre, append(lkey, key.Bytes()...)...)
  323. }
  324. // WriteMapmapBloom writes each address included in the receipts' logs to the
  325. // MIP bloom bin.
  326. func WriteMipmapBloom(db ethdb.Database, number uint64, receipts types.Receipts) error {
  327. batch := db.NewBatch()
  328. for _, level := range MIPMapLevels {
  329. key := mipmapKey(number, level)
  330. bloomDat, _ := db.Get(key)
  331. bloom := types.BytesToBloom(bloomDat)
  332. for _, receipt := range receipts {
  333. for _, log := range receipt.Logs() {
  334. bloom.Add(log.Address.Big())
  335. }
  336. }
  337. batch.Put(key, bloom.Bytes())
  338. }
  339. if err := batch.Write(); err != nil {
  340. return fmt.Errorf("mipmap write fail for: %d: %v", number, err)
  341. }
  342. return nil
  343. }
  344. // GetMipmapBloom returns a bloom filter using the number and level as input
  345. // parameters. For available levels see MIPMapLevels.
  346. func GetMipmapBloom(db ethdb.Database, number, level uint64) types.Bloom {
  347. bloomDat, _ := db.Get(mipmapKey(number, level))
  348. return types.BytesToBloom(bloomDat)
  349. }