chain_util.go 14 KB

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