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