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