chain_util.go 12 KB

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