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