github.com/Blockdaemon/celo-blockchain@v0.0.0-20200129231733-e667f6b08419/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/istanbul" 32 "github.com/ethereum/go-ethereum/consensus/misc" 33 "github.com/ethereum/go-ethereum/core/state" 34 "github.com/ethereum/go-ethereum/core/types" 35 "github.com/ethereum/go-ethereum/params" 36 "github.com/ethereum/go-ethereum/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 errLargeBlockTime = errors.New("timestamp too big") 68 errZeroBlockTime = errors.New("timestamp equals parent's") 69 errTooManyUncles = errors.New("too many uncles") 70 errDuplicateUncle = errors.New("duplicate uncle") 71 errUncleIsAncestor = errors.New("uncle is ancestor") 72 errDanglingUncle = errors.New("uncle's parent is not ancestor") 73 errInvalidDifficulty = errors.New("non-positive difficulty") 74 errInvalidMixDigest = errors.New("invalid mix digest") 75 errInvalidPoW = errors.New("invalid proof-of-work") 76 ) 77 78 // Author implements consensus.Engine, returning the header's coinbase as the 79 // proof-of-work verified author of the block. 80 func (ethash *Ethash) Author(header *types.Header) (common.Address, error) { 81 return header.Coinbase, nil 82 } 83 84 func (ethash *Ethash) GetValidators(blockNumber *big.Int, headerHash common.Hash) []istanbul.Validator { 85 return []istanbul.Validator{} 86 } 87 88 func (ethash *Ethash) EpochSize() uint64 { 89 return 0 90 } 91 92 // VerifyHeader checks whether a header conforms to the consensus rules of the 93 // stock Ethereum ethash engine. 94 func (ethash *Ethash) VerifyHeader(chain consensus.ChainReader, header *types.Header, seal bool) error { 95 // If we're running a full engine faking, accept any input as valid 96 if ethash.config.PowMode == ModeFullFake { 97 return nil 98 } 99 // Short circuit if the header is known, or it's parent not 100 number := header.Number.Uint64() 101 if chain.GetHeader(header.Hash(), number) != nil { 102 return nil 103 } 104 parent := chain.GetHeader(header.ParentHash, number-1) 105 if parent == nil { 106 return consensus.ErrUnknownAncestor 107 } 108 // Sanity checks passed, do a proper verification 109 return ethash.verifyHeader(chain, header, parent, false, seal) 110 } 111 112 // VerifyHeaders is similar to VerifyHeader, but verifies a batch of headers 113 // concurrently. The method returns a quit channel to abort the operations and 114 // a results channel to retrieve the async verifications. 115 func (ethash *Ethash) VerifyHeaders(chain consensus.ChainReader, headers []*types.Header, seals []bool) (chan<- struct{}, <-chan error) { 116 // If we're running a full engine faking, accept any input as valid 117 if ethash.config.PowMode == ModeFullFake || len(headers) == 0 { 118 abort, results := make(chan struct{}), make(chan error, len(headers)) 119 for i := 0; i < len(headers); i++ { 120 results <- nil 121 } 122 return abort, results 123 } 124 125 // Spawn as many workers as allowed threads 126 workers := runtime.GOMAXPROCS(0) 127 if len(headers) < workers { 128 workers = len(headers) 129 } 130 131 // Create a task channel and spawn the verifiers 132 var ( 133 inputs = make(chan int) 134 done = make(chan int, workers) 135 errors = make([]error, len(headers)) 136 abort = make(chan struct{}) 137 ) 138 for i := 0; i < workers; i++ { 139 go func() { 140 for index := range inputs { 141 errors[index] = ethash.verifyHeaderWorker(chain, headers, seals, index) 142 done <- index 143 } 144 }() 145 } 146 147 errorsOut := make(chan error, len(headers)) 148 go func() { 149 defer close(inputs) 150 var ( 151 in, out = 0, 0 152 checked = make([]bool, len(headers)) 153 inputs = inputs 154 ) 155 for { 156 select { 157 case inputs <- in: 158 if in++; in == len(headers) { 159 // Reached end of headers. Stop sending to workers. 160 inputs = nil 161 } 162 case index := <-done: 163 for checked[index] = true; checked[out]; out++ { 164 errorsOut <- errors[out] 165 if out == len(headers)-1 { 166 return 167 } 168 } 169 case <-abort: 170 return 171 } 172 } 173 }() 174 return abort, errorsOut 175 } 176 177 func (ethash *Ethash) verifyHeaderWorker(chain consensus.ChainReader, headers []*types.Header, seals []bool, index int) error { 178 var parent *types.Header 179 if index == 0 { 180 parent = chain.GetHeader(headers[0].ParentHash, headers[0].Number.Uint64()-1) 181 } else if headers[index-1].Hash() == headers[index].ParentHash { 182 parent = headers[index-1] 183 } 184 if parent == nil { 185 return consensus.ErrUnknownAncestor 186 } 187 if chain.GetHeader(headers[index].Hash(), headers[index].Number.Uint64()) != nil { 188 return nil // known block 189 } 190 return ethash.verifyHeader(chain, headers[index], parent, false, seals[index]) 191 } 192 193 // VerifyUncles verifies that the given block's uncles conform to the consensus 194 // rules of the stock Ethereum ethash engine. 195 func (ethash *Ethash) VerifyUncles(chain consensus.ChainReader, block *types.Block) error { 196 // If we're running a full engine faking, accept any input as valid 197 if ethash.config.PowMode == ModeFullFake { 198 return nil 199 } 200 // Verify that there are at most 2 uncles included in this block 201 if len(block.Uncles()) > maxUncles { 202 return errTooManyUncles 203 } 204 // Gather the set of past uncles and ancestors 205 uncles, ancestors := mapset.NewSet(), make(map[common.Hash]*types.Header) 206 207 number, parent := block.NumberU64()-1, block.ParentHash() 208 for i := 0; i < 7; i++ { 209 ancestor := chain.GetBlock(parent, number) 210 if ancestor == nil { 211 break 212 } 213 ancestors[ancestor.Hash()] = ancestor.Header() 214 for _, uncle := range ancestor.Uncles() { 215 uncles.Add(uncle.Hash()) 216 } 217 parent, number = ancestor.ParentHash(), number-1 218 } 219 ancestors[block.Hash()] = block.Header() 220 uncles.Add(block.Hash()) 221 222 // Verify each of the uncles that it's recent, but not an ancestor 223 for _, uncle := range block.Uncles() { 224 // Make sure every uncle is rewarded only once 225 hash := uncle.Hash() 226 if uncles.Contains(hash) { 227 return errDuplicateUncle 228 } 229 uncles.Add(hash) 230 231 // Make sure the uncle has a valid ancestry 232 if ancestors[hash] != nil { 233 return errUncleIsAncestor 234 } 235 if ancestors[uncle.ParentHash] == nil || uncle.ParentHash == block.ParentHash() { 236 return errDanglingUncle 237 } 238 if err := ethash.verifyHeader(chain, uncle, ancestors[uncle.ParentHash], true, true); err != nil { 239 return err 240 } 241 } 242 return nil 243 } 244 245 // verifyHeader checks whether a header conforms to the consensus rules of the 246 // stock Ethereum ethash engine. 247 // See YP section 4.3.4. "Block Header Validity" 248 func (ethash *Ethash) verifyHeader(chain consensus.ChainReader, header, parent *types.Header, uncle bool, seal bool) error { 249 // Ensure that the header's extra-data section is of a reasonable size 250 if uint64(len(header.Extra)) > params.MaximumExtraDataSize { 251 return fmt.Errorf("extra-data too long: %d > %d", len(header.Extra), params.MaximumExtraDataSize) 252 } 253 // Verify the header's timestamp 254 if uncle { 255 if header.Time.Cmp(math.MaxBig256) > 0 { 256 return errLargeBlockTime 257 } 258 } else { 259 if header.Time.Cmp(big.NewInt(time.Now().Add(allowedFutureBlockTime).Unix())) > 0 { 260 return consensus.ErrFutureBlock 261 } 262 } 263 if header.Time.Cmp(parent.Time) <= 0 { 264 return errZeroBlockTime 265 } 266 // Verify the block's difficulty based in it's timestamp and parent's difficulty 267 expected := ethash.CalcDifficulty(chain, header.Time.Uint64(), parent) 268 269 if expected.Cmp(header.Difficulty) != 0 { 270 return fmt.Errorf("invalid difficulty: have %v, want %v", header.Difficulty, expected) 271 } 272 // Verify that the gas limit is <= 2^63-1 273 cap := uint64(0x7fffffffffffffff) 274 if header.GasLimit > cap { 275 return fmt.Errorf("invalid gasLimit: have %v, max %v", header.GasLimit, cap) 276 } 277 // Verify that the gasUsed is <= gasLimit 278 if header.GasUsed > header.GasLimit { 279 return fmt.Errorf("invalid gasUsed: have %d, gasLimit %d", header.GasUsed, header.GasLimit) 280 } 281 282 // Verify that the gas limit remains within allowed bounds 283 diff := int64(parent.GasLimit) - int64(header.GasLimit) 284 if diff < 0 { 285 diff *= -1 286 } 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.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).Set(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).Set(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.Set(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.Uint64(), parent) 567 return nil 568 } 569 570 // Finalize implements consensus.Engine, accumulating the block and uncle rewards, 571 // setting the final state and assembling the block. 572 func (ethash *Ethash) Finalize(chain consensus.ChainReader, header *types.Header, state *state.StateDB, txs []*types.Transaction, uncles []*types.Header, receipts []*types.Receipt, randomness *types.Randomness) (*types.Block, error) { 573 // Accumulate any block and uncle rewards and commit the final state root 574 accumulateRewards(chain.Config(), state, header, uncles) 575 header.Root = state.IntermediateRoot(chain.Config().IsEIP158(header.Number)) 576 577 // Header seems complete, assemble into a block and return 578 return types.NewBlock(header, txs, uncles, receipts, randomness), nil 579 } 580 581 // SealHash returns the hash of a block prior to it being sealed. 582 func (ethash *Ethash) SealHash(header *types.Header) (hash common.Hash) { 583 hasher := sha3.NewLegacyKeccak256() 584 585 rlp.Encode(hasher, []interface{}{ 586 header.ParentHash, 587 header.UncleHash, 588 header.Coinbase, 589 header.Root, 590 header.TxHash, 591 header.ReceiptHash, 592 header.Bloom, 593 header.Difficulty, 594 header.Number, 595 header.GasLimit, 596 header.GasUsed, 597 header.Time, 598 header.Extra, 599 }) 600 hasher.Sum(hash[:0]) 601 return hash 602 } 603 604 // Some weird constants to avoid constant memory allocs for them. 605 var ( 606 big8 = big.NewInt(8) 607 big32 = big.NewInt(32) 608 ) 609 610 // AccumulateRewards credits the coinbase of the given block with the mining 611 // reward. The total reward consists of the static block reward and rewards for 612 // included uncles. The coinbase of each uncle block is also rewarded. 613 func accumulateRewards(config *params.ChainConfig, state *state.StateDB, header *types.Header, uncles []*types.Header) { 614 // Select the correct block reward based on chain progression 615 blockReward := FrontierBlockReward 616 if config.IsByzantium(header.Number) { 617 blockReward = ByzantiumBlockReward 618 } 619 if config.IsConstantinople(header.Number) { 620 blockReward = ConstantinopleBlockReward 621 } 622 // Accumulate the rewards for the miner and any included uncles 623 reward := new(big.Int).Set(blockReward) 624 r := new(big.Int) 625 for _, uncle := range uncles { 626 r.Add(uncle.Number, big8) 627 r.Sub(r, header.Number) 628 r.Mul(r, blockReward) 629 r.Div(r, big8) 630 state.AddBalance(uncle.Coinbase, r) 631 632 r.Div(blockReward, big32) 633 reward.Add(reward, r) 634 } 635 state.AddBalance(header.Coinbase, reward) 636 }