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