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