consensus.go 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726
  1. // Copyright 2017 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 ethash
  17. import (
  18. "bytes"
  19. "errors"
  20. "fmt"
  21. "math/big"
  22. "runtime"
  23. "time"
  24. mapset "github.com/deckarep/golang-set"
  25. "github.com/ethereum/go-ethereum/common"
  26. "github.com/ethereum/go-ethereum/common/math"
  27. "github.com/ethereum/go-ethereum/consensus"
  28. "github.com/ethereum/go-ethereum/consensus/misc"
  29. "github.com/ethereum/go-ethereum/core/state"
  30. "github.com/ethereum/go-ethereum/core/types"
  31. "github.com/ethereum/go-ethereum/params"
  32. "github.com/ethereum/go-ethereum/rlp"
  33. "github.com/ethereum/go-ethereum/trie"
  34. "golang.org/x/crypto/sha3"
  35. )
  36. // Ethash proof-of-work protocol constants.
  37. var (
  38. FrontierBlockReward = big.NewInt(5e+18) // Block reward in wei for successfully mining a block
  39. ByzantiumBlockReward = big.NewInt(3e+18) // Block reward in wei for successfully mining a block upward from Byzantium
  40. ConstantinopleBlockReward = big.NewInt(2e+18) // Block reward in wei for successfully mining a block upward from Constantinople
  41. maxUncles = 2 // Maximum number of uncles allowed in a single block
  42. allowedFutureBlockTimeSeconds = int64(15) // Max seconds from current time allowed for blocks, before they're considered future blocks
  43. // calcDifficultyEip5133 is the difficulty adjustment algorithm as specified by EIP 5133.
  44. // It offsets the bomb a total of 11.4M blocks.
  45. // Specification EIP-5133: https://eips.ethereum.org/EIPS/eip-5133
  46. calcDifficultyEip5133 = makeDifficultyCalculator(big.NewInt(11_400_000))
  47. // calcDifficultyEip4345 is the difficulty adjustment algorithm as specified by EIP 4345.
  48. // It offsets the bomb a total of 10.7M blocks.
  49. // Specification EIP-4345: https://eips.ethereum.org/EIPS/eip-4345
  50. calcDifficultyEip4345 = makeDifficultyCalculator(big.NewInt(10_700_000))
  51. // calcDifficultyEip3554 is the difficulty adjustment algorithm as specified by EIP 3554.
  52. // It offsets the bomb a total of 9.7M blocks.
  53. // Specification EIP-3554: https://eips.ethereum.org/EIPS/eip-3554
  54. calcDifficultyEip3554 = makeDifficultyCalculator(big.NewInt(9700000))
  55. // calcDifficultyEip2384 is the difficulty adjustment algorithm as specified by EIP 2384.
  56. // It offsets the bomb 4M blocks from Constantinople, so in total 9M blocks.
  57. // Specification EIP-2384: https://eips.ethereum.org/EIPS/eip-2384
  58. calcDifficultyEip2384 = makeDifficultyCalculator(big.NewInt(9000000))
  59. // calcDifficultyConstantinople is the difficulty adjustment algorithm for Constantinople.
  60. // It returns the difficulty that a new block should have when created at time given the
  61. // parent block's time and difficulty. The calculation uses the Byzantium rules, but with
  62. // bomb offset 5M.
  63. // Specification EIP-1234: https://eips.ethereum.org/EIPS/eip-1234
  64. calcDifficultyConstantinople = makeDifficultyCalculator(big.NewInt(5000000))
  65. // calcDifficultyByzantium is the difficulty adjustment algorithm. It returns
  66. // the difficulty that a new block should have when created at time given the
  67. // parent block's time and difficulty. The calculation uses the Byzantium rules.
  68. // Specification EIP-649: https://eips.ethereum.org/EIPS/eip-649
  69. calcDifficultyByzantium = makeDifficultyCalculator(big.NewInt(3000000))
  70. )
  71. // Various error messages to mark blocks invalid. These should be private to
  72. // prevent engine specific errors from being referenced in the remainder of the
  73. // codebase, inherently breaking if the engine is swapped out. Please put common
  74. // error types into the consensus package.
  75. var (
  76. errOlderBlockTime = errors.New("timestamp older than parent")
  77. errTooManyUncles = errors.New("too many uncles")
  78. errDuplicateUncle = errors.New("duplicate uncle")
  79. errUncleIsAncestor = errors.New("uncle is ancestor")
  80. errDanglingUncle = errors.New("uncle's parent is not ancestor")
  81. errInvalidDifficulty = errors.New("non-positive difficulty")
  82. errInvalidMixDigest = errors.New("invalid mix digest")
  83. errInvalidPoW = errors.New("invalid proof-of-work")
  84. )
  85. // Author implements consensus.Engine, returning the header's coinbase as the
  86. // proof-of-work verified author of the block.
  87. func (ethash *Ethash) Author(header *types.Header) (common.Address, error) {
  88. return header.Coinbase, nil
  89. }
  90. // VerifyHeader checks whether a header conforms to the consensus rules of the
  91. // stock Ethereum ethash engine.
  92. func (ethash *Ethash) VerifyHeader(chain consensus.ChainHeaderReader, header *types.Header, seal bool) error {
  93. // If we're running a full engine faking, accept any input as valid
  94. if ethash.config.PowMode == ModeFullFake {
  95. return nil
  96. }
  97. // Short circuit if the header is known, or its parent not
  98. number := header.Number.Uint64()
  99. if chain.GetHeader(header.Hash(), number) != nil {
  100. return nil
  101. }
  102. parent := chain.GetHeader(header.ParentHash, number-1)
  103. if parent == nil {
  104. return consensus.ErrUnknownAncestor
  105. }
  106. // Sanity checks passed, do a proper verification
  107. return ethash.verifyHeader(chain, header, parent, false, seal, time.Now().Unix())
  108. }
  109. // VerifyHeaders is similar to VerifyHeader, but verifies a batch of headers
  110. // concurrently. The method returns a quit channel to abort the operations and
  111. // a results channel to retrieve the async verifications.
  112. func (ethash *Ethash) VerifyHeaders(chain consensus.ChainHeaderReader, headers []*types.Header, seals []bool) (chan<- struct{}, <-chan error) {
  113. // If we're running a full engine faking, accept any input as valid
  114. if ethash.config.PowMode == ModeFullFake || len(headers) == 0 {
  115. abort, results := make(chan struct{}), make(chan error, len(headers))
  116. for i := 0; i < len(headers); i++ {
  117. results <- nil
  118. }
  119. return abort, results
  120. }
  121. // Spawn as many workers as allowed threads
  122. workers := runtime.GOMAXPROCS(0)
  123. if len(headers) < workers {
  124. workers = len(headers)
  125. }
  126. // Create a task channel and spawn the verifiers
  127. var (
  128. inputs = make(chan int)
  129. done = make(chan int, workers)
  130. errors = make([]error, len(headers))
  131. abort = make(chan struct{})
  132. unixNow = time.Now().Unix()
  133. )
  134. for i := 0; i < workers; i++ {
  135. go func() {
  136. for index := range inputs {
  137. errors[index] = ethash.verifyHeaderWorker(chain, headers, seals, index, unixNow)
  138. done <- index
  139. }
  140. }()
  141. }
  142. errorsOut := make(chan error, len(headers))
  143. go func() {
  144. defer close(inputs)
  145. var (
  146. in, out = 0, 0
  147. checked = make([]bool, len(headers))
  148. inputs = inputs
  149. )
  150. for {
  151. select {
  152. case inputs <- in:
  153. if in++; in == len(headers) {
  154. // Reached end of headers. Stop sending to workers.
  155. inputs = nil
  156. }
  157. case index := <-done:
  158. for checked[index] = true; checked[out]; out++ {
  159. errorsOut <- errors[out]
  160. if out == len(headers)-1 {
  161. return
  162. }
  163. }
  164. case <-abort:
  165. return
  166. }
  167. }
  168. }()
  169. return abort, errorsOut
  170. }
  171. func (ethash *Ethash) verifyHeaderWorker(chain consensus.ChainHeaderReader, headers []*types.Header, seals []bool, index int, unixNow int64) error {
  172. var parent *types.Header
  173. if index == 0 {
  174. parent = chain.GetHeader(headers[0].ParentHash, headers[0].Number.Uint64()-1)
  175. } else if headers[index-1].Hash() == headers[index].ParentHash {
  176. parent = headers[index-1]
  177. }
  178. if parent == nil {
  179. return consensus.ErrUnknownAncestor
  180. }
  181. return ethash.verifyHeader(chain, headers[index], parent, false, seals[index], unixNow)
  182. }
  183. // VerifyUncles verifies that the given block's uncles conform to the consensus
  184. // rules of the stock Ethereum ethash engine.
  185. func (ethash *Ethash) VerifyUncles(chain consensus.ChainReader, block *types.Block) error {
  186. // If we're running a full engine faking, accept any input as valid
  187. if ethash.config.PowMode == ModeFullFake {
  188. return nil
  189. }
  190. // Verify that there are at most 2 uncles included in this block
  191. if len(block.Uncles()) > maxUncles {
  192. return errTooManyUncles
  193. }
  194. if len(block.Uncles()) == 0 {
  195. return nil
  196. }
  197. // Gather the set of past uncles and ancestors
  198. uncles, ancestors := mapset.NewSet(), make(map[common.Hash]*types.Header)
  199. number, parent := block.NumberU64()-1, block.ParentHash()
  200. for i := 0; i < 7; i++ {
  201. ancestorHeader := chain.GetHeader(parent, number)
  202. if ancestorHeader == nil {
  203. break
  204. }
  205. ancestors[parent] = ancestorHeader
  206. // If the ancestor doesn't have any uncles, we don't have to iterate them
  207. if ancestorHeader.UncleHash != types.EmptyUncleHash {
  208. // Need to add those uncles to the banned list too
  209. ancestor := chain.GetBlock(parent, number)
  210. if ancestor == nil {
  211. break
  212. }
  213. for _, uncle := range ancestor.Uncles() {
  214. uncles.Add(uncle.Hash())
  215. }
  216. }
  217. parent, number = ancestorHeader.ParentHash, number-1
  218. }
  219. ancestors[block.Hash()] = block.Header()
  220. uncles.Add(block.Hash())
  221. // Verify each of the uncles that it's recent, but not an ancestor
  222. for _, uncle := range block.Uncles() {
  223. // Make sure every uncle is rewarded only once
  224. hash := uncle.Hash()
  225. if uncles.Contains(hash) {
  226. return errDuplicateUncle
  227. }
  228. uncles.Add(hash)
  229. // Make sure the uncle has a valid ancestry
  230. if ancestors[hash] != nil {
  231. return errUncleIsAncestor
  232. }
  233. if ancestors[uncle.ParentHash] == nil || uncle.ParentHash == block.ParentHash() {
  234. return errDanglingUncle
  235. }
  236. if err := ethash.verifyHeader(chain, uncle, ancestors[uncle.ParentHash], true, true, time.Now().Unix()); err != nil {
  237. return err
  238. }
  239. }
  240. return nil
  241. }
  242. // verifyHeader checks whether a header conforms to the consensus rules of the
  243. // stock Ethereum ethash engine.
  244. // See YP section 4.3.4. "Block Header Validity"
  245. func (ethash *Ethash) verifyHeader(chain consensus.ChainHeaderReader, header, parent *types.Header, uncle bool, seal bool, unixNow int64) error {
  246. // Ensure that the header's extra-data section is of a reasonable size
  247. if uint64(len(header.Extra)) > params.MaximumExtraDataSize {
  248. return fmt.Errorf("extra-data too long: %d > %d", len(header.Extra), params.MaximumExtraDataSize)
  249. }
  250. // Verify the header's timestamp
  251. if !uncle {
  252. if header.Time > uint64(unixNow+allowedFutureBlockTimeSeconds) {
  253. return consensus.ErrFutureBlock
  254. }
  255. }
  256. if header.Time <= parent.Time {
  257. return errOlderBlockTime
  258. }
  259. // Verify the block's difficulty based on its timestamp and parent's difficulty
  260. expected := ethash.CalcDifficulty(chain, header.Time, parent)
  261. if expected.Cmp(header.Difficulty) != 0 {
  262. return fmt.Errorf("invalid difficulty: have %v, want %v", header.Difficulty, expected)
  263. }
  264. // Verify that the gas limit is <= 2^63-1
  265. if header.GasLimit > params.MaxGasLimit {
  266. return fmt.Errorf("invalid gasLimit: have %v, max %v", header.GasLimit, params.MaxGasLimit)
  267. }
  268. // Verify that the gasUsed is <= gasLimit
  269. if header.GasUsed > header.GasLimit {
  270. return fmt.Errorf("invalid gasUsed: have %d, gasLimit %d", header.GasUsed, header.GasLimit)
  271. }
  272. // Verify the block's gas usage and (if applicable) verify the base fee.
  273. if !chain.Config().IsLondon(header.Number) {
  274. // Verify BaseFee not present before EIP-1559 fork.
  275. if header.BaseFee != nil {
  276. return fmt.Errorf("invalid baseFee before fork: have %d, expected 'nil'", header.BaseFee)
  277. }
  278. if err := misc.VerifyGaslimit(parent.GasLimit, header.GasLimit); err != nil {
  279. return err
  280. }
  281. } else if err := misc.VerifyEip1559Header(chain.Config(), parent, header); err != nil {
  282. // Verify the header's EIP-1559 attributes.
  283. return err
  284. }
  285. // Verify that the block number is parent's +1
  286. if diff := new(big.Int).Sub(header.Number, parent.Number); diff.Cmp(big.NewInt(1)) != 0 {
  287. return consensus.ErrInvalidNumber
  288. }
  289. // Verify the engine specific seal securing the block
  290. if seal {
  291. if err := ethash.verifySeal(chain, header, false); err != nil {
  292. return err
  293. }
  294. }
  295. // If all checks passed, validate any special fields for hard forks
  296. if err := misc.VerifyDAOHeaderExtraData(chain.Config(), header); err != nil {
  297. return err
  298. }
  299. if err := misc.VerifyForkHashes(chain.Config(), header, uncle); err != nil {
  300. return err
  301. }
  302. return nil
  303. }
  304. // CalcDifficulty is the difficulty adjustment algorithm. It returns
  305. // the difficulty that a new block should have when created at time
  306. // given the parent block's time and difficulty.
  307. func (ethash *Ethash) CalcDifficulty(chain consensus.ChainHeaderReader, time uint64, parent *types.Header) *big.Int {
  308. return CalcDifficulty(chain.Config(), time, parent)
  309. }
  310. // CalcDifficulty is the difficulty adjustment algorithm. It returns
  311. // the difficulty that a new block should have when created at time
  312. // given the parent block's time and difficulty.
  313. func CalcDifficulty(config *params.ChainConfig, time uint64, parent *types.Header) *big.Int {
  314. next := new(big.Int).Add(parent.Number, big1)
  315. switch {
  316. case config.IsEthPoWFork(next):
  317. if config.EthPoWForkBlock != nil && big.NewInt(0).Add(config.EthPoWForkBlock, big.NewInt(2048)).Cmp(next) == 0 {
  318. return params.ETHWStartDifficulty //Reset difficulty
  319. }
  320. if config.EthPoWForkBlock != nil && config.EthPoWForkBlock.Cmp(next) == 0 {
  321. return big.NewInt(1) //Reset
  322. }
  323. return calcDifficultyEthPoW(time, parent)
  324. case config.IsGrayGlacier(next):
  325. return calcDifficultyEip5133(time, parent)
  326. case config.IsArrowGlacier(next):
  327. return calcDifficultyEip4345(time, parent)
  328. case config.IsLondon(next):
  329. return calcDifficultyEip3554(time, parent)
  330. case config.IsMuirGlacier(next):
  331. return calcDifficultyEip2384(time, parent)
  332. case config.IsConstantinople(next):
  333. return calcDifficultyConstantinople(time, parent)
  334. case config.IsByzantium(next):
  335. return calcDifficultyByzantium(time, parent)
  336. case config.IsHomestead(next):
  337. return calcDifficultyHomestead(time, parent)
  338. default:
  339. return calcDifficultyFrontier(time, parent)
  340. }
  341. }
  342. // Some weird constants to avoid constant memory allocs for them.
  343. var (
  344. expDiffPeriod = big.NewInt(100000)
  345. big1 = big.NewInt(1)
  346. big2 = big.NewInt(2)
  347. big9 = big.NewInt(9)
  348. big10 = big.NewInt(10)
  349. bigMinus99 = big.NewInt(-99)
  350. )
  351. // calcDifficultyEthPOW creates a difficultyCalculator with the origin Proof-of-work (PoW).
  352. // Remain old calculations & deleted fakeBlockNumber
  353. func calcDifficultyEthPoW(time uint64, parent *types.Header) *big.Int {
  354. // Note, the calculations below looks at the parent number, which is 1 below
  355. // the block number. Thus we remove one from the delay given
  356. // https://github.com/ethereum/EIPs/issues/100.
  357. // algorithm:
  358. // diff = (parent_diff +
  359. // (parent_diff / 2048 * max((2 if len(parent.uncles) else 1) - ((timestamp - parent.timestamp) // 9), -99))
  360. // ) + 2^(periodCount - 2)
  361. bigTime := new(big.Int).SetUint64(time)
  362. bigParentTime := new(big.Int).SetUint64(parent.Time)
  363. // holds intermediate values to make the algo easier to read & audit
  364. x := new(big.Int)
  365. y := new(big.Int)
  366. // (2 if len(parent_uncles) else 1) - (block_timestamp - parent_timestamp) // 9
  367. x.Sub(bigTime, bigParentTime)
  368. x.Div(x, big9)
  369. if parent.UncleHash == types.EmptyUncleHash {
  370. x.Sub(big1, x)
  371. } else {
  372. x.Sub(big2, x)
  373. }
  374. // max((2 if len(parent_uncles) else 1) - (block_timestamp - parent_timestamp) // 9, -99)
  375. if x.Cmp(bigMinus99) < 0 {
  376. x.Set(bigMinus99)
  377. }
  378. // parent_diff + (parent_diff / 2048 * max((2 if len(parent.uncles) else 1) - ((timestamp - parent.timestamp) // 9), -99))
  379. y.Div(parent.Difficulty, params.DifficultyBoundDivisor)
  380. x.Mul(y, x)
  381. x.Add(parent.Difficulty, x)
  382. // minimum difficulty can ever be (before exponential factor)
  383. if x.Cmp(params.MinimumDifficulty) < 0 {
  384. x.Set(params.MinimumDifficulty)
  385. }
  386. return x
  387. }
  388. // makeDifficultyCalculator creates a difficultyCalculator with the given bomb-delay.
  389. // the difficulty is calculated with Byzantium rules, which differs from Homestead in
  390. // how uncles affect the calculation
  391. func makeDifficultyCalculator(bombDelay *big.Int) func(time uint64, parent *types.Header) *big.Int {
  392. // Note, the calculations below looks at the parent number, which is 1 below
  393. // the block number. Thus we remove one from the delay given
  394. bombDelayFromParent := new(big.Int).Sub(bombDelay, big1)
  395. return func(time uint64, parent *types.Header) *big.Int {
  396. // https://github.com/ethereum/EIPs/issues/100.
  397. // algorithm:
  398. // diff = (parent_diff +
  399. // (parent_diff / 2048 * max((2 if len(parent.uncles) else 1) - ((timestamp - parent.timestamp) // 9), -99))
  400. // ) + 2^(periodCount - 2)
  401. bigTime := new(big.Int).SetUint64(time)
  402. bigParentTime := new(big.Int).SetUint64(parent.Time)
  403. // holds intermediate values to make the algo easier to read & audit
  404. x := new(big.Int)
  405. y := new(big.Int)
  406. // (2 if len(parent_uncles) else 1) - (block_timestamp - parent_timestamp) // 9
  407. x.Sub(bigTime, bigParentTime)
  408. x.Div(x, big9)
  409. if parent.UncleHash == types.EmptyUncleHash {
  410. x.Sub(big1, x)
  411. } else {
  412. x.Sub(big2, x)
  413. }
  414. // max((2 if len(parent_uncles) else 1) - (block_timestamp - parent_timestamp) // 9, -99)
  415. if x.Cmp(bigMinus99) < 0 {
  416. x.Set(bigMinus99)
  417. }
  418. // parent_diff + (parent_diff / 2048 * max((2 if len(parent.uncles) else 1) - ((timestamp - parent.timestamp) // 9), -99))
  419. y.Div(parent.Difficulty, params.DifficultyBoundDivisor)
  420. x.Mul(y, x)
  421. x.Add(parent.Difficulty, x)
  422. // minimum difficulty can ever be (before exponential factor)
  423. if x.Cmp(params.MinimumDifficulty) < 0 {
  424. x.Set(params.MinimumDifficulty)
  425. }
  426. // calculate a fake block number for the ice-age delay
  427. // Specification: https://eips.ethereum.org/EIPS/eip-1234
  428. fakeBlockNumber := new(big.Int)
  429. if parent.Number.Cmp(bombDelayFromParent) >= 0 {
  430. fakeBlockNumber = fakeBlockNumber.Sub(parent.Number, bombDelayFromParent)
  431. }
  432. // for the exponential factor
  433. periodCount := fakeBlockNumber
  434. periodCount.Div(periodCount, expDiffPeriod)
  435. // the exponential factor, commonly referred to as "the bomb"
  436. // diff = diff + 2^(periodCount - 2)
  437. if periodCount.Cmp(big1) > 0 {
  438. y.Sub(periodCount, big2)
  439. y.Exp(big2, y, nil)
  440. x.Add(x, y)
  441. }
  442. return x
  443. }
  444. }
  445. // calcDifficultyHomestead is the difficulty adjustment algorithm. It returns
  446. // the difficulty that a new block should have when created at time given the
  447. // parent block's time and difficulty. The calculation uses the Homestead rules.
  448. func calcDifficultyHomestead(time uint64, parent *types.Header) *big.Int {
  449. // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-2.md
  450. // algorithm:
  451. // diff = (parent_diff +
  452. // (parent_diff / 2048 * max(1 - (block_timestamp - parent_timestamp) // 10, -99))
  453. // ) + 2^(periodCount - 2)
  454. bigTime := new(big.Int).SetUint64(time)
  455. bigParentTime := new(big.Int).SetUint64(parent.Time)
  456. // holds intermediate values to make the algo easier to read & audit
  457. x := new(big.Int)
  458. y := new(big.Int)
  459. // 1 - (block_timestamp - parent_timestamp) // 10
  460. x.Sub(bigTime, bigParentTime)
  461. x.Div(x, big10)
  462. x.Sub(big1, x)
  463. // max(1 - (block_timestamp - parent_timestamp) // 10, -99)
  464. if x.Cmp(bigMinus99) < 0 {
  465. x.Set(bigMinus99)
  466. }
  467. // (parent_diff + parent_diff // 2048 * max(1 - (block_timestamp - parent_timestamp) // 10, -99))
  468. y.Div(parent.Difficulty, params.DifficultyBoundDivisor)
  469. x.Mul(y, x)
  470. x.Add(parent.Difficulty, x)
  471. // minimum difficulty can ever be (before exponential factor)
  472. if x.Cmp(params.MinimumDifficulty) < 0 {
  473. x.Set(params.MinimumDifficulty)
  474. }
  475. // for the exponential factor
  476. periodCount := new(big.Int).Add(parent.Number, big1)
  477. periodCount.Div(periodCount, expDiffPeriod)
  478. // the exponential factor, commonly referred to as "the bomb"
  479. // diff = diff + 2^(periodCount - 2)
  480. if periodCount.Cmp(big1) > 0 {
  481. y.Sub(periodCount, big2)
  482. y.Exp(big2, y, nil)
  483. x.Add(x, y)
  484. }
  485. return x
  486. }
  487. // calcDifficultyFrontier is the difficulty adjustment algorithm. It returns the
  488. // difficulty that a new block should have when created at time given the parent
  489. // block's time and difficulty. The calculation uses the Frontier rules.
  490. func calcDifficultyFrontier(time uint64, parent *types.Header) *big.Int {
  491. diff := new(big.Int)
  492. adjust := new(big.Int).Div(parent.Difficulty, params.DifficultyBoundDivisor)
  493. bigTime := new(big.Int)
  494. bigParentTime := new(big.Int)
  495. bigTime.SetUint64(time)
  496. bigParentTime.SetUint64(parent.Time)
  497. if bigTime.Sub(bigTime, bigParentTime).Cmp(params.DurationLimit) < 0 {
  498. diff.Add(parent.Difficulty, adjust)
  499. } else {
  500. diff.Sub(parent.Difficulty, adjust)
  501. }
  502. if diff.Cmp(params.MinimumDifficulty) < 0 {
  503. diff.Set(params.MinimumDifficulty)
  504. }
  505. periodCount := new(big.Int).Add(parent.Number, big1)
  506. periodCount.Div(periodCount, expDiffPeriod)
  507. if periodCount.Cmp(big1) > 0 {
  508. // diff = diff + 2^(periodCount - 2)
  509. expDiff := periodCount.Sub(periodCount, big2)
  510. expDiff.Exp(big2, expDiff, nil)
  511. diff.Add(diff, expDiff)
  512. diff = math.BigMax(diff, params.MinimumDifficulty)
  513. }
  514. return diff
  515. }
  516. // Exported for fuzzing
  517. var FrontierDifficultyCalculator = calcDifficultyFrontier
  518. var HomesteadDifficultyCalculator = calcDifficultyHomestead
  519. var DynamicDifficultyCalculator = makeDifficultyCalculator
  520. // verifySeal checks whether a block satisfies the PoW difficulty requirements,
  521. // either using the usual ethash cache for it, or alternatively using a full DAG
  522. // to make remote mining fast.
  523. func (ethash *Ethash) verifySeal(chain consensus.ChainHeaderReader, header *types.Header, fulldag bool) error {
  524. // If we're running a fake PoW, accept any seal as valid
  525. if ethash.config.PowMode == ModeFake || ethash.config.PowMode == ModeFullFake {
  526. time.Sleep(ethash.fakeDelay)
  527. if ethash.fakeFail == header.Number.Uint64() {
  528. return errInvalidPoW
  529. }
  530. return nil
  531. }
  532. // If we're running a shared PoW, delegate verification to it
  533. if ethash.shared != nil {
  534. return ethash.shared.verifySeal(chain, header, fulldag)
  535. }
  536. // Ensure that we have a valid difficulty for the block
  537. if header.Difficulty.Sign() <= 0 {
  538. return errInvalidDifficulty
  539. }
  540. // Recompute the digest and PoW values
  541. number := header.Number.Uint64()
  542. var (
  543. digest []byte
  544. result []byte
  545. )
  546. // If fast-but-heavy PoW verification was requested, use an ethash dataset
  547. if fulldag {
  548. dataset := ethash.dataset(number, true)
  549. if dataset.generated() {
  550. digest, result = hashimotoFull(dataset.dataset, ethash.SealHash(header).Bytes(), header.Nonce.Uint64())
  551. // Datasets are unmapped in a finalizer. Ensure that the dataset stays alive
  552. // until after the call to hashimotoFull so it's not unmapped while being used.
  553. runtime.KeepAlive(dataset)
  554. } else {
  555. // Dataset not yet generated, don't hang, use a cache instead
  556. fulldag = false
  557. }
  558. }
  559. // If slow-but-light PoW verification was requested (or DAG not yet ready), use an ethash cache
  560. if !fulldag {
  561. cache := ethash.cache(number)
  562. size := datasetSize(number)
  563. if ethash.config.PowMode == ModeTest {
  564. size = 32 * 1024
  565. }
  566. digest, result = hashimotoLight(size, cache.cache, ethash.SealHash(header).Bytes(), header.Nonce.Uint64())
  567. // Caches are unmapped in a finalizer. Ensure that the cache stays alive
  568. // until after the call to hashimotoLight so it's not unmapped while being used.
  569. runtime.KeepAlive(cache)
  570. }
  571. // Verify the calculated values against the ones provided in the header
  572. if !bytes.Equal(header.MixDigest[:], digest) {
  573. return errInvalidMixDigest
  574. }
  575. target := new(big.Int).Div(two256, header.Difficulty)
  576. if new(big.Int).SetBytes(result).Cmp(target) > 0 {
  577. return errInvalidPoW
  578. }
  579. return nil
  580. }
  581. // Prepare implements consensus.Engine, initializing the difficulty field of a
  582. // header to conform to the ethash protocol. The changes are done inline.
  583. func (ethash *Ethash) Prepare(chain consensus.ChainHeaderReader, header *types.Header) error {
  584. parent := chain.GetHeader(header.ParentHash, header.Number.Uint64()-1)
  585. if parent == nil {
  586. return consensus.ErrUnknownAncestor
  587. }
  588. header.Difficulty = ethash.CalcDifficulty(chain, header.Time, parent)
  589. return nil
  590. }
  591. // Finalize implements consensus.Engine, accumulating the block and uncle rewards,
  592. // setting the final state on the header
  593. func (ethash *Ethash) Finalize(chain consensus.ChainHeaderReader, header *types.Header, state *state.StateDB, txs []*types.Transaction, uncles []*types.Header) {
  594. // Accumulate any block and uncle rewards and commit the final state root
  595. accumulateRewards(chain.Config(), state, header, uncles)
  596. header.Root = state.IntermediateRoot(chain.Config().IsEIP158(header.Number))
  597. }
  598. // FinalizeAndAssemble implements consensus.Engine, accumulating the block and
  599. // uncle rewards, setting the final state and assembling the block.
  600. func (ethash *Ethash) FinalizeAndAssemble(chain consensus.ChainHeaderReader, header *types.Header, state *state.StateDB, txs []*types.Transaction, uncles []*types.Header, receipts []*types.Receipt) (*types.Block, error) {
  601. // Finalize block
  602. ethash.Finalize(chain, header, state, txs, uncles)
  603. // Header seems complete, assemble into a block and return
  604. return types.NewBlock(header, txs, uncles, receipts, trie.NewStackTrie(nil)), nil
  605. }
  606. // SealHash returns the hash of a block prior to it being sealed.
  607. func (ethash *Ethash) SealHash(header *types.Header) (hash common.Hash) {
  608. hasher := sha3.NewLegacyKeccak256()
  609. enc := []interface{}{
  610. header.ParentHash,
  611. header.UncleHash,
  612. header.Coinbase,
  613. header.Root,
  614. header.TxHash,
  615. header.ReceiptHash,
  616. header.Bloom,
  617. header.Difficulty,
  618. header.Number,
  619. header.GasLimit,
  620. header.GasUsed,
  621. header.Time,
  622. header.Extra,
  623. }
  624. if header.BaseFee != nil {
  625. enc = append(enc, header.BaseFee)
  626. }
  627. rlp.Encode(hasher, enc)
  628. hasher.Sum(hash[:0])
  629. return hash
  630. }
  631. // Some weird constants to avoid constant memory allocs for them.
  632. var (
  633. big8 = big.NewInt(8)
  634. big32 = big.NewInt(32)
  635. )
  636. // AccumulateRewards credits the coinbase of the given block with the mining
  637. // reward. The total reward consists of the static block reward and rewards for
  638. // included uncles. The coinbase of each uncle block is also rewarded.
  639. func accumulateRewards(config *params.ChainConfig, state *state.StateDB, header *types.Header, uncles []*types.Header) {
  640. // Select the correct block reward based on chain progression
  641. blockReward := FrontierBlockReward
  642. if config.IsByzantium(header.Number) {
  643. blockReward = ByzantiumBlockReward
  644. }
  645. if config.IsConstantinople(header.Number) {
  646. blockReward = ConstantinopleBlockReward
  647. }
  648. // Accumulate the rewards for the miner and any included uncles
  649. reward := new(big.Int).Set(blockReward)
  650. r := new(big.Int)
  651. for _, uncle := range uncles {
  652. r.Add(uncle.Number, big8)
  653. r.Sub(r, header.Number)
  654. r.Mul(r, blockReward)
  655. r.Div(r, big8)
  656. state.AddBalance(uncle.Coinbase, r)
  657. r.Div(blockReward, big32)
  658. reward.Add(reward, r)
  659. }
  660. state.AddBalance(header.Coinbase, reward)
  661. }