chain_util.go 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179
  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. "time"
  21. "github.com/ethereum/go-ethereum/common"
  22. "github.com/ethereum/go-ethereum/core/types"
  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. blockHashPre = []byte("block-hash-")
  30. blockNumPre = []byte("block-num-")
  31. ExpDiffPeriod = big.NewInt(100000)
  32. )
  33. // CalcDifficulty is the difficulty adjustment algorithm. It returns
  34. // the difficulty that a new block b should have when created at time
  35. // given the parent block's time and difficulty.
  36. func CalcDifficulty(time, parentTime uint64, parentNumber, parentDiff *big.Int) *big.Int {
  37. diff := new(big.Int)
  38. adjust := new(big.Int).Div(parentDiff, params.DifficultyBoundDivisor)
  39. bigTime := new(big.Int)
  40. bigParentTime := new(big.Int)
  41. bigTime.SetUint64(time)
  42. bigParentTime.SetUint64(parentTime)
  43. if bigTime.Sub(bigTime, bigParentTime).Cmp(params.DurationLimit) < 0 {
  44. diff.Add(parentDiff, adjust)
  45. } else {
  46. diff.Sub(parentDiff, adjust)
  47. }
  48. if diff.Cmp(params.MinimumDifficulty) < 0 {
  49. diff = params.MinimumDifficulty
  50. }
  51. periodCount := new(big.Int).Add(parentNumber, common.Big1)
  52. periodCount.Div(periodCount, ExpDiffPeriod)
  53. if periodCount.Cmp(common.Big1) > 0 {
  54. // diff = diff + 2^(periodCount - 2)
  55. expDiff := periodCount.Sub(periodCount, common.Big2)
  56. expDiff.Exp(common.Big2, expDiff, nil)
  57. diff.Add(diff, expDiff)
  58. diff = common.BigMax(diff, params.MinimumDifficulty)
  59. }
  60. return diff
  61. }
  62. // CalcTD computes the total difficulty of block.
  63. func CalcTD(block, parent *types.Block) *big.Int {
  64. if parent == nil {
  65. return block.Difficulty()
  66. }
  67. d := block.Difficulty()
  68. d.Add(d, parent.Td)
  69. return d
  70. }
  71. // CalcGasLimit computes the gas limit of the next block after parent.
  72. // The result may be modified by the caller.
  73. // This is miner strategy, not consensus protocol.
  74. func CalcGasLimit(parent *types.Block) *big.Int {
  75. // contrib = (parentGasUsed * 3 / 2) / 1024
  76. contrib := new(big.Int).Mul(parent.GasUsed(), big.NewInt(3))
  77. contrib = contrib.Div(contrib, big.NewInt(2))
  78. contrib = contrib.Div(contrib, params.GasLimitBoundDivisor)
  79. // decay = parentGasLimit / 1024 -1
  80. decay := new(big.Int).Div(parent.GasLimit(), params.GasLimitBoundDivisor)
  81. decay.Sub(decay, big.NewInt(1))
  82. /*
  83. strategy: gasLimit of block-to-mine is set based on parent's
  84. gasUsed value. if parentGasUsed > parentGasLimit * (2/3) then we
  85. increase it, otherwise lower it (or leave it unchanged if it's right
  86. at that usage) the amount increased/decreased depends on how far away
  87. from parentGasLimit * (2/3) parentGasUsed is.
  88. */
  89. gl := new(big.Int).Sub(parent.GasLimit(), decay)
  90. gl = gl.Add(gl, contrib)
  91. gl.Set(common.BigMax(gl, params.MinGasLimit))
  92. // however, if we're now below the target (GenesisGasLimit) we increase the
  93. // limit as much as we can (parentGasLimit / 1024 -1)
  94. if gl.Cmp(params.GenesisGasLimit) < 0 {
  95. gl.Add(parent.GasLimit(), decay)
  96. gl.Set(common.BigMin(gl, params.GenesisGasLimit))
  97. }
  98. return gl
  99. }
  100. // GetBlockByHash returns the block corresponding to the hash or nil if not found
  101. func GetBlockByHash(db common.Database, hash common.Hash) *types.Block {
  102. data, _ := db.Get(append(blockHashPre, hash[:]...))
  103. if len(data) == 0 {
  104. return nil
  105. }
  106. var block types.StorageBlock
  107. if err := rlp.Decode(bytes.NewReader(data), &block); err != nil {
  108. glog.V(logger.Error).Infof("invalid block RLP for hash %x: %v", hash, err)
  109. return nil
  110. }
  111. return (*types.Block)(&block)
  112. }
  113. // GetBlockByHash returns the canonical block by number or nil if not found
  114. func GetBlockByNumber(db common.Database, number uint64) *types.Block {
  115. key, _ := db.Get(append(blockNumPre, big.NewInt(int64(number)).Bytes()...))
  116. if len(key) == 0 {
  117. return nil
  118. }
  119. return GetBlockByHash(db, common.BytesToHash(key))
  120. }
  121. // WriteCanonNumber writes the canonical hash for the given block
  122. func WriteCanonNumber(db common.Database, block *types.Block) error {
  123. key := append(blockNumPre, block.Number().Bytes()...)
  124. err := db.Put(key, block.Hash().Bytes())
  125. if err != nil {
  126. return err
  127. }
  128. return nil
  129. }
  130. // WriteHead force writes the current head
  131. func WriteHead(db common.Database, block *types.Block) error {
  132. err := WriteCanonNumber(db, block)
  133. if err != nil {
  134. return err
  135. }
  136. err = db.Put([]byte("LastBlock"), block.Hash().Bytes())
  137. if err != nil {
  138. return err
  139. }
  140. return nil
  141. }
  142. // WriteBlock writes a block to the database
  143. func WriteBlock(db common.Database, block *types.Block) error {
  144. tstart := time.Now()
  145. enc, _ := rlp.EncodeToBytes((*types.StorageBlock)(block))
  146. key := append(blockHashPre, block.Hash().Bytes()...)
  147. err := db.Put(key, enc)
  148. if err != nil {
  149. glog.Fatal("db write fail:", err)
  150. return err
  151. }
  152. if glog.V(logger.Debug) {
  153. glog.Infof("wrote block #%v %s. Took %v\n", block.Number(), common.PP(block.Hash().Bytes()), time.Since(tstart))
  154. }
  155. return nil
  156. }