consensus.go 24 KB

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