chain_util.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  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. "math/big"
  20. "github.com/ethereum/go-ethereum/common"
  21. "github.com/ethereum/go-ethereum/core/types"
  22. "github.com/ethereum/go-ethereum/ethdb"
  23. "github.com/ethereum/go-ethereum/logger"
  24. "github.com/ethereum/go-ethereum/logger/glog"
  25. "github.com/ethereum/go-ethereum/params"
  26. "github.com/ethereum/go-ethereum/rlp"
  27. )
  28. var (
  29. headHeaderKey = []byte("LastHeader")
  30. headBlockKey = []byte("LastBlock")
  31. blockPrefix = []byte("block-")
  32. blockNumPrefix = []byte("block-num-")
  33. headerSuffix = []byte("-header")
  34. bodySuffix = []byte("-body")
  35. tdSuffix = []byte("-td")
  36. ExpDiffPeriod = big.NewInt(100000)
  37. blockHashPre = []byte("block-hash-") // [deprecated by eth/63]
  38. )
  39. // CalcDifficulty is the difficulty adjustment algorithm. It returns
  40. // the difficulty that a new block b should have when created at time
  41. // given the parent block's time and difficulty.
  42. func CalcDifficulty(time, parentTime uint64, parentNumber, parentDiff *big.Int) *big.Int {
  43. diff := new(big.Int)
  44. adjust := new(big.Int).Div(parentDiff, params.DifficultyBoundDivisor)
  45. bigTime := new(big.Int)
  46. bigParentTime := new(big.Int)
  47. bigTime.SetUint64(time)
  48. bigParentTime.SetUint64(parentTime)
  49. if bigTime.Sub(bigTime, bigParentTime).Cmp(params.DurationLimit) < 0 {
  50. diff.Add(parentDiff, adjust)
  51. } else {
  52. diff.Sub(parentDiff, adjust)
  53. }
  54. if diff.Cmp(params.MinimumDifficulty) < 0 {
  55. diff = params.MinimumDifficulty
  56. }
  57. periodCount := new(big.Int).Add(parentNumber, common.Big1)
  58. periodCount.Div(periodCount, ExpDiffPeriod)
  59. if periodCount.Cmp(common.Big1) > 0 {
  60. // diff = diff + 2^(periodCount - 2)
  61. expDiff := periodCount.Sub(periodCount, common.Big2)
  62. expDiff.Exp(common.Big2, expDiff, nil)
  63. diff.Add(diff, expDiff)
  64. diff = common.BigMax(diff, params.MinimumDifficulty)
  65. }
  66. return diff
  67. }
  68. // CalcGasLimit computes the gas limit of the next block after parent.
  69. // The result may be modified by the caller.
  70. // This is miner strategy, not consensus protocol.
  71. func CalcGasLimit(parent *types.Block) *big.Int {
  72. // contrib = (parentGasUsed * 3 / 2) / 1024
  73. contrib := new(big.Int).Mul(parent.GasUsed(), big.NewInt(3))
  74. contrib = contrib.Div(contrib, big.NewInt(2))
  75. contrib = contrib.Div(contrib, params.GasLimitBoundDivisor)
  76. // decay = parentGasLimit / 1024 -1
  77. decay := new(big.Int).Div(parent.GasLimit(), params.GasLimitBoundDivisor)
  78. decay.Sub(decay, big.NewInt(1))
  79. /*
  80. strategy: gasLimit of block-to-mine is set based on parent's
  81. gasUsed value. if parentGasUsed > parentGasLimit * (2/3) then we
  82. increase it, otherwise lower it (or leave it unchanged if it's right
  83. at that usage) the amount increased/decreased depends on how far away
  84. from parentGasLimit * (2/3) parentGasUsed is.
  85. */
  86. gl := new(big.Int).Sub(parent.GasLimit(), decay)
  87. gl = gl.Add(gl, contrib)
  88. gl.Set(common.BigMax(gl, params.MinGasLimit))
  89. // however, if we're now below the target (GenesisGasLimit) we increase the
  90. // limit as much as we can (parentGasLimit / 1024 -1)
  91. if gl.Cmp(params.GenesisGasLimit) < 0 {
  92. gl.Add(parent.GasLimit(), decay)
  93. gl.Set(common.BigMin(gl, params.GenesisGasLimit))
  94. }
  95. return gl
  96. }
  97. // GetCanonicalHash retrieves a hash assigned to a canonical block number.
  98. func GetCanonicalHash(db ethdb.Database, number uint64) common.Hash {
  99. data, _ := db.Get(append(blockNumPrefix, big.NewInt(int64(number)).Bytes()...))
  100. if len(data) == 0 {
  101. return common.Hash{}
  102. }
  103. return common.BytesToHash(data)
  104. }
  105. // GetHeadHeaderHash retrieves the hash of the current canonical head block's
  106. // header. The difference between this and GetHeadBlockHash is that whereas the
  107. // last block hash is only updated upon a full block import, the last header
  108. // hash is updated already at header import, allowing head tracking for the
  109. // fast synchronization mechanism.
  110. func GetHeadHeaderHash(db ethdb.Database) common.Hash {
  111. data, _ := db.Get(headHeaderKey)
  112. if len(data) == 0 {
  113. return common.Hash{}
  114. }
  115. return common.BytesToHash(data)
  116. }
  117. // GetHeadBlockHash retrieves the hash of the current canonical head block.
  118. func GetHeadBlockHash(db ethdb.Database) common.Hash {
  119. data, _ := db.Get(headBlockKey)
  120. if len(data) == 0 {
  121. return common.Hash{}
  122. }
  123. return common.BytesToHash(data)
  124. }
  125. // GetHeaderRLP retrieves a block header in its raw RLP database encoding, or nil
  126. // if the header's not found.
  127. func GetHeaderRLP(db ethdb.Database, hash common.Hash) rlp.RawValue {
  128. data, _ := db.Get(append(append(blockPrefix, hash[:]...), headerSuffix...))
  129. return data
  130. }
  131. // GetHeader retrieves the block header corresponding to the hash, nil if none
  132. // found.
  133. func GetHeader(db ethdb.Database, hash common.Hash) *types.Header {
  134. data := GetHeaderRLP(db, hash)
  135. if len(data) == 0 {
  136. return nil
  137. }
  138. header := new(types.Header)
  139. if err := rlp.Decode(bytes.NewReader(data), header); err != nil {
  140. glog.V(logger.Error).Infof("invalid block header RLP for hash %x: %v", hash, err)
  141. return nil
  142. }
  143. return header
  144. }
  145. // GetBodyRLP retrieves the block body (transactions and uncles) in RLP encoding.
  146. func GetBodyRLP(db ethdb.Database, hash common.Hash) rlp.RawValue {
  147. data, _ := db.Get(append(append(blockPrefix, hash[:]...), bodySuffix...))
  148. return data
  149. }
  150. // GetBody retrieves the block body (transactons, uncles) corresponding to the
  151. // hash, nil if none found.
  152. func GetBody(db ethdb.Database, hash common.Hash) *types.Body {
  153. data := GetBodyRLP(db, hash)
  154. if len(data) == 0 {
  155. return nil
  156. }
  157. body := new(types.Body)
  158. if err := rlp.Decode(bytes.NewReader(data), body); err != nil {
  159. glog.V(logger.Error).Infof("invalid block body RLP for hash %x: %v", hash, err)
  160. return nil
  161. }
  162. return body
  163. }
  164. // GetTd retrieves a block's total difficulty corresponding to the hash, nil if
  165. // none found.
  166. func GetTd(db ethdb.Database, hash common.Hash) *big.Int {
  167. data, _ := db.Get(append(append(blockPrefix, hash.Bytes()...), tdSuffix...))
  168. if len(data) == 0 {
  169. return nil
  170. }
  171. td := new(big.Int)
  172. if err := rlp.Decode(bytes.NewReader(data), td); err != nil {
  173. glog.V(logger.Error).Infof("invalid block total difficulty RLP for hash %x: %v", hash, err)
  174. return nil
  175. }
  176. return td
  177. }
  178. // GetBlock retrieves an entire block corresponding to the hash, assembling it
  179. // back from the stored header and body.
  180. func GetBlock(db ethdb.Database, hash common.Hash) *types.Block {
  181. // Retrieve the block header and body contents
  182. header := GetHeader(db, hash)
  183. if header == nil {
  184. return nil
  185. }
  186. body := GetBody(db, hash)
  187. if body == nil {
  188. return nil
  189. }
  190. // Reassemble the block and return
  191. return types.NewBlockWithHeader(header).WithBody(body.Transactions, body.Uncles)
  192. }
  193. // WriteCanonicalHash stores the canonical hash for the given block number.
  194. func WriteCanonicalHash(db ethdb.Database, hash common.Hash, number uint64) error {
  195. key := append(blockNumPrefix, big.NewInt(int64(number)).Bytes()...)
  196. if err := db.Put(key, hash.Bytes()); err != nil {
  197. glog.Fatalf("failed to store number to hash mapping into database: %v", err)
  198. return err
  199. }
  200. return nil
  201. }
  202. // WriteHeadHeaderHash stores the head header's hash.
  203. func WriteHeadHeaderHash(db ethdb.Database, hash common.Hash) error {
  204. if err := db.Put(headHeaderKey, hash.Bytes()); err != nil {
  205. glog.Fatalf("failed to store last header's hash into database: %v", err)
  206. return err
  207. }
  208. return nil
  209. }
  210. // WriteHeadBlockHash stores the head block's hash.
  211. func WriteHeadBlockHash(db ethdb.Database, hash common.Hash) error {
  212. if err := db.Put(headBlockKey, hash.Bytes()); err != nil {
  213. glog.Fatalf("failed to store last block's hash into database: %v", err)
  214. return err
  215. }
  216. return nil
  217. }
  218. // WriteHeader serializes a block header into the database.
  219. func WriteHeader(db ethdb.Database, header *types.Header) error {
  220. data, err := rlp.EncodeToBytes(header)
  221. if err != nil {
  222. return err
  223. }
  224. key := append(append(blockPrefix, header.Hash().Bytes()...), headerSuffix...)
  225. if err := db.Put(key, data); err != nil {
  226. glog.Fatalf("failed to store header into database: %v", err)
  227. return err
  228. }
  229. glog.V(logger.Debug).Infof("stored header #%v [%x…]", header.Number, header.Hash().Bytes()[:4])
  230. return nil
  231. }
  232. // WriteBody serializes the body of a block into the database.
  233. func WriteBody(db ethdb.Database, hash common.Hash, body *types.Body) error {
  234. data, err := rlp.EncodeToBytes(body)
  235. if err != nil {
  236. return err
  237. }
  238. key := append(append(blockPrefix, hash.Bytes()...), bodySuffix...)
  239. if err := db.Put(key, data); err != nil {
  240. glog.Fatalf("failed to store block body into database: %v", err)
  241. return err
  242. }
  243. glog.V(logger.Debug).Infof("stored block body [%x…]", hash.Bytes()[:4])
  244. return nil
  245. }
  246. // WriteTd serializes the total difficulty of a block into the database.
  247. func WriteTd(db ethdb.Database, hash common.Hash, td *big.Int) error {
  248. data, err := rlp.EncodeToBytes(td)
  249. if err != nil {
  250. return err
  251. }
  252. key := append(append(blockPrefix, hash.Bytes()...), tdSuffix...)
  253. if err := db.Put(key, data); err != nil {
  254. glog.Fatalf("failed to store block total difficulty into database: %v", err)
  255. return err
  256. }
  257. glog.V(logger.Debug).Infof("stored block total difficulty [%x…]: %v", hash.Bytes()[:4], td)
  258. return nil
  259. }
  260. // WriteBlock serializes a block into the database, header and body separately.
  261. func WriteBlock(db ethdb.Database, block *types.Block) error {
  262. // Store the body first to retain database consistency
  263. if err := WriteBody(db, block.Hash(), &types.Body{block.Transactions(), block.Uncles()}); err != nil {
  264. return err
  265. }
  266. // Store the header too, signaling full block ownership
  267. if err := WriteHeader(db, block.Header()); err != nil {
  268. return err
  269. }
  270. return nil
  271. }
  272. // DeleteCanonicalHash removes the number to hash canonical mapping.
  273. func DeleteCanonicalHash(db ethdb.Database, number uint64) {
  274. db.Delete(append(blockNumPrefix, big.NewInt(int64(number)).Bytes()...))
  275. }
  276. // DeleteHeader removes all block header data associated with a hash.
  277. func DeleteHeader(db ethdb.Database, hash common.Hash) {
  278. db.Delete(append(append(blockPrefix, hash.Bytes()...), headerSuffix...))
  279. }
  280. // DeleteBody removes all block body data associated with a hash.
  281. func DeleteBody(db ethdb.Database, hash common.Hash) {
  282. db.Delete(append(append(blockPrefix, hash.Bytes()...), bodySuffix...))
  283. }
  284. // DeleteTd removes all block total difficulty data associated with a hash.
  285. func DeleteTd(db ethdb.Database, hash common.Hash) {
  286. db.Delete(append(append(blockPrefix, hash.Bytes()...), tdSuffix...))
  287. }
  288. // DeleteBlock removes all block data associated with a hash.
  289. func DeleteBlock(db ethdb.Database, hash common.Hash) {
  290. DeleteHeader(db, hash)
  291. DeleteBody(db, hash)
  292. DeleteTd(db, hash)
  293. }
  294. // [deprecated by eth/63]
  295. // GetBlockByHashOld returns the old combined block corresponding to the hash
  296. // or nil if not found. This method is only used by the upgrade mechanism to
  297. // access the old combined block representation. It will be dropped after the
  298. // network transitions to eth/63.
  299. func GetBlockByHashOld(db ethdb.Database, hash common.Hash) *types.Block {
  300. data, _ := db.Get(append(blockHashPre, hash[:]...))
  301. if len(data) == 0 {
  302. return nil
  303. }
  304. var block types.StorageBlock
  305. if err := rlp.Decode(bytes.NewReader(data), &block); err != nil {
  306. glog.V(logger.Error).Infof("invalid block RLP for hash %x: %v", hash, err)
  307. return nil
  308. }
  309. return (*types.Block)(&block)
  310. }