github.com/zjj1991/quorum@v0.0.0-20190524123704-ae4b0a1e1a19/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/crypto/sha3" 35 "github.com/ethereum/go-ethereum/params" 36 "github.com/ethereum/go-ethereum/rlp" 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 // calcDifficultyConstantinople is the difficulty adjustment algorithm for Constantinople. 48 // It returns the difficulty that a new block should have when created at time given the 49 // parent block's time and difficulty. The calculation uses the Byzantium rules, but with 50 // bomb offset 5M. 51 // Specification EIP-1234: https://eips.ethereum.org/EIPS/eip-1234 52 calcDifficultyConstantinople = makeDifficultyCalculator(big.NewInt(5000000)) 53 54 // calcDifficultyByzantium is the difficulty adjustment algorithm. It returns 55 // the difficulty that a new block should have when created at time given the 56 // parent block's time and difficulty. The calculation uses the Byzantium rules. 57 // Specification EIP-649: https://eips.ethereum.org/EIPS/eip-649 58 calcDifficultyByzantium = makeDifficultyCalculator(big.NewInt(3000000)) 59 nanosecond2017Timestamp = mustParseRfc3339("2017-01-01T00:00:00+00:00").UnixNano() 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 func mustParseRfc3339(str string) time.Time { 79 time, err := time.Parse(time.RFC3339, str) 80 if err != nil { 81 panic("unexpected failure to parse rfc3339 timestamp: " + str) 82 } 83 return time 84 } 85 86 // Author implements consensus.Engine, returning the header's coinbase as the 87 // proof-of-work verified author of the block. 88 func (ethash *Ethash) Author(header *types.Header) (common.Address, error) { 89 return header.Coinbase, nil 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 if !chain.Config().IsQuorum { 259 if header.Time.Cmp(big.NewInt(time.Now().Add(allowedFutureBlockTime).Unix())) > 0 { 260 return consensus.ErrFutureBlock 261 } 262 } else { 263 // We disable future checking if we're in --raft mode. This is crucial 264 // because block validation in the raft setting needs to be deterministic. 265 // There is no forking of the chain, and we need each node to only perform 266 // validation as a pure function of block contents with respect to the 267 // previous database state. 268 // 269 // NOTE: whereas we are currently checking whether the timestamp field has 270 // nanosecond semantics to detect --raft mode, we could also use a special 271 // "raft" sentinel in the Extra field, or pass a boolean for raftMode from 272 // all call sites of this function. 273 if raftMode := time.Now().UnixNano() > nanosecond2017Timestamp; !raftMode { 274 if header.Time.Cmp(big.NewInt(time.Now().Unix())) > 0 { 275 return consensus.ErrFutureBlock 276 } 277 } 278 } 279 if header.Time.Cmp(parent.Time) <= 0 { 280 return errZeroBlockTime 281 } 282 // Verify the block's difficulty based in it's timestamp and parent's difficulty 283 expected := ethash.CalcDifficulty(chain, header.Time.Uint64(), parent) 284 285 if expected.Cmp(header.Difficulty) != 0 { 286 return fmt.Errorf("invalid difficulty: have %v, want %v", header.Difficulty, expected) 287 } 288 // Verify that the gas limit is <= 2^63-1 289 cap := uint64(0x7fffffffffffffff) 290 if header.GasLimit > cap { 291 return fmt.Errorf("invalid gasLimit: have %v, max %v", header.GasLimit, cap) 292 } 293 // Verify that the gasUsed is <= gasLimit 294 if header.GasUsed > header.GasLimit { 295 return fmt.Errorf("invalid gasUsed: have %d, gasLimit %d", header.GasUsed, header.GasLimit) 296 } 297 298 // Verify that the gas limit remains within allowed bounds 299 diff := int64(parent.GasLimit) - int64(header.GasLimit) 300 if diff < 0 { 301 diff *= -1 302 } 303 limit := parent.GasLimit / params.OriginalGasLimitBoundDivisor 304 305 if uint64(diff) >= limit || header.GasLimit < params.OriginnalMinGasLimit { 306 return fmt.Errorf("invalid gas limit: have %d, want %d += %d", header.GasLimit, parent.GasLimit, limit) 307 } 308 // Verify that the block number is parent's +1 309 if diff := new(big.Int).Sub(header.Number, parent.Number); diff.Cmp(big.NewInt(1)) != 0 { 310 return consensus.ErrInvalidNumber 311 } 312 // Verify the engine specific seal securing the block 313 if seal { 314 if err := ethash.VerifySeal(chain, header); err != nil { 315 return err 316 } 317 } 318 // If all checks passed, validate any special fields for hard forks 319 if err := misc.VerifyDAOHeaderExtraData(chain.Config(), header); err != nil { 320 return err 321 } 322 if err := misc.VerifyForkHashes(chain.Config(), header, uncle); err != nil { 323 return err 324 } 325 return nil 326 } 327 328 // CalcDifficulty is the difficulty adjustment algorithm. It returns 329 // the difficulty that a new block should have when created at time 330 // given the parent block's time and difficulty. 331 func (ethash *Ethash) CalcDifficulty(chain consensus.ChainReader, time uint64, parent *types.Header) *big.Int { 332 return CalcDifficulty(chain.Config(), time, parent) 333 } 334 335 // CalcDifficulty is the difficulty adjustment algorithm. It returns 336 // the difficulty that a new block should have when created at time 337 // given the parent block's time and difficulty. 338 func CalcDifficulty(config *params.ChainConfig, time uint64, parent *types.Header) *big.Int { 339 next := new(big.Int).Add(parent.Number, big1) 340 switch { 341 case config.IsConstantinople(next): 342 return calcDifficultyConstantinople(time, parent) 343 case config.IsByzantium(next): 344 return calcDifficultyByzantium(time, parent) 345 case config.IsHomestead(next): 346 return calcDifficultyHomestead(time, parent) 347 default: 348 return calcDifficultyFrontier(time, parent) 349 } 350 } 351 352 // Some weird constants to avoid constant memory allocs for them. 353 var ( 354 expDiffPeriod = big.NewInt(100000) 355 big1 = big.NewInt(1) 356 big2 = big.NewInt(2) 357 big9 = big.NewInt(9) 358 big10 = big.NewInt(10) 359 bigMinus99 = big.NewInt(-99) 360 ) 361 362 // makeDifficultyCalculator creates a difficultyCalculator with the given bomb-delay. 363 // the difficulty is calculated with Byzantium rules, which differs from Homestead in 364 // how uncles affect the calculation 365 func makeDifficultyCalculator(bombDelay *big.Int) func(time uint64, parent *types.Header) *big.Int { 366 // Note, the calculations below looks at the parent number, which is 1 below 367 // the block number. Thus we remove one from the delay given 368 bombDelayFromParent := new(big.Int).Sub(bombDelay, big1) 369 return func(time uint64, parent *types.Header) *big.Int { 370 // https://github.com/ethereum/EIPs/issues/100. 371 // algorithm: 372 // diff = (parent_diff + 373 // (parent_diff / 2048 * max((2 if len(parent.uncles) else 1) - ((timestamp - parent.timestamp) // 9), -99)) 374 // ) + 2^(periodCount - 2) 375 376 bigTime := new(big.Int).SetUint64(time) 377 bigParentTime := new(big.Int).Set(parent.Time) 378 379 // holds intermediate values to make the algo easier to read & audit 380 x := new(big.Int) 381 y := new(big.Int) 382 383 // (2 if len(parent_uncles) else 1) - (block_timestamp - parent_timestamp) // 9 384 x.Sub(bigTime, bigParentTime) 385 x.Div(x, big9) 386 if parent.UncleHash == types.EmptyUncleHash { 387 x.Sub(big1, x) 388 } else { 389 x.Sub(big2, x) 390 } 391 // max((2 if len(parent_uncles) else 1) - (block_timestamp - parent_timestamp) // 9, -99) 392 if x.Cmp(bigMinus99) < 0 { 393 x.Set(bigMinus99) 394 } 395 // parent_diff + (parent_diff / 2048 * max((2 if len(parent.uncles) else 1) - ((timestamp - parent.timestamp) // 9), -99)) 396 y.Div(parent.Difficulty, params.DifficultyBoundDivisor) 397 x.Mul(y, x) 398 x.Add(parent.Difficulty, x) 399 400 // minimum difficulty can ever be (before exponential factor) 401 if x.Cmp(params.MinimumDifficulty) < 0 { 402 x.Set(params.MinimumDifficulty) 403 } 404 // calculate a fake block number for the ice-age delay 405 // Specification: https://eips.ethereum.org/EIPS/eip-1234 406 fakeBlockNumber := new(big.Int) 407 if parent.Number.Cmp(bombDelayFromParent) >= 0 { 408 fakeBlockNumber = fakeBlockNumber.Sub(parent.Number, bombDelayFromParent) 409 } 410 // for the exponential factor 411 periodCount := fakeBlockNumber 412 periodCount.Div(periodCount, expDiffPeriod) 413 414 // the exponential factor, commonly referred to as "the bomb" 415 // diff = diff + 2^(periodCount - 2) 416 if periodCount.Cmp(big1) > 0 { 417 y.Sub(periodCount, big2) 418 y.Exp(big2, y, nil) 419 x.Add(x, y) 420 } 421 return x 422 } 423 } 424 425 // calcDifficultyHomestead is the difficulty adjustment algorithm. It returns 426 // the difficulty that a new block should have when created at time given the 427 // parent block's time and difficulty. The calculation uses the Homestead rules. 428 func calcDifficultyHomestead(time uint64, parent *types.Header) *big.Int { 429 // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-2.md 430 // algorithm: 431 // diff = (parent_diff + 432 // (parent_diff / 2048 * max(1 - (block_timestamp - parent_timestamp) // 10, -99)) 433 // ) + 2^(periodCount - 2) 434 435 bigTime := new(big.Int).SetUint64(time) 436 bigParentTime := new(big.Int).Set(parent.Time) 437 438 // holds intermediate values to make the algo easier to read & audit 439 x := new(big.Int) 440 y := new(big.Int) 441 442 // 1 - (block_timestamp - parent_timestamp) // 10 443 x.Sub(bigTime, bigParentTime) 444 x.Div(x, big10) 445 x.Sub(big1, x) 446 447 // max(1 - (block_timestamp - parent_timestamp) // 10, -99) 448 if x.Cmp(bigMinus99) < 0 { 449 x.Set(bigMinus99) 450 } 451 // (parent_diff + parent_diff // 2048 * max(1 - (block_timestamp - parent_timestamp) // 10, -99)) 452 y.Div(parent.Difficulty, params.DifficultyBoundDivisor) 453 x.Mul(y, x) 454 x.Add(parent.Difficulty, x) 455 456 // minimum difficulty can ever be (before exponential factor) 457 if x.Cmp(params.MinimumDifficulty) < 0 { 458 x.Set(params.MinimumDifficulty) 459 } 460 // for the exponential factor 461 periodCount := new(big.Int).Add(parent.Number, big1) 462 periodCount.Div(periodCount, expDiffPeriod) 463 464 // the exponential factor, commonly referred to as "the bomb" 465 // diff = diff + 2^(periodCount - 2) 466 if periodCount.Cmp(big1) > 0 { 467 y.Sub(periodCount, big2) 468 y.Exp(big2, y, nil) 469 x.Add(x, y) 470 } 471 return x 472 } 473 474 // calcDifficultyFrontier is the difficulty adjustment algorithm. It returns the 475 // difficulty that a new block should have when created at time given the parent 476 // block's time and difficulty. The calculation uses the Frontier rules. 477 func calcDifficultyFrontier(time uint64, parent *types.Header) *big.Int { 478 diff := new(big.Int) 479 adjust := new(big.Int).Div(parent.Difficulty, params.DifficultyBoundDivisor) 480 bigTime := new(big.Int) 481 bigParentTime := new(big.Int) 482 483 bigTime.SetUint64(time) 484 bigParentTime.Set(parent.Time) 485 486 if bigTime.Sub(bigTime, bigParentTime).Cmp(params.DurationLimit) < 0 { 487 diff.Add(parent.Difficulty, adjust) 488 } else { 489 diff.Sub(parent.Difficulty, adjust) 490 } 491 if diff.Cmp(params.MinimumDifficulty) < 0 { 492 diff.Set(params.MinimumDifficulty) 493 } 494 495 periodCount := new(big.Int).Add(parent.Number, big1) 496 periodCount.Div(periodCount, expDiffPeriod) 497 if periodCount.Cmp(big1) > 0 { 498 // diff = diff + 2^(periodCount - 2) 499 expDiff := periodCount.Sub(periodCount, big2) 500 expDiff.Exp(big2, expDiff, nil) 501 diff.Add(diff, expDiff) 502 diff = math.BigMax(diff, params.MinimumDifficulty) 503 } 504 return diff 505 } 506 507 // VerifySeal implements consensus.Engine, checking whether the given block satisfies 508 // the PoW difficulty requirements. 509 func (ethash *Ethash) VerifySeal(chain consensus.ChainReader, header *types.Header) error { 510 return ethash.verifySeal(chain, header, false) 511 } 512 513 // verifySeal checks whether a block satisfies the PoW difficulty requirements, 514 // either using the usual ethash cache for it, or alternatively using a full DAG 515 // to make remote mining fast. 516 func (ethash *Ethash) verifySeal(chain consensus.ChainReader, header *types.Header, fulldag bool) error { 517 isQuorum := chain != nil && chain.Config().IsQuorum 518 519 // If we're running a fake PoW, accept any seal as valid 520 if ethash.config.PowMode == ModeFake || ethash.config.PowMode == ModeFullFake { 521 time.Sleep(ethash.fakeDelay) 522 if ethash.fakeFail == header.Number.Uint64() { 523 return errInvalidPoW 524 } 525 return nil 526 } 527 // If we're running a shared PoW, delegate verification to it 528 if ethash.shared != nil { 529 return ethash.shared.verifySeal(chain, header, fulldag) 530 } 531 // Ensure that we have a valid difficulty for the block 532 if header.Difficulty.Sign() <= 0 { 533 return errInvalidDifficulty 534 } 535 // Recompute the digest and PoW values 536 number := header.Number.Uint64() 537 538 var ( 539 digest []byte 540 result []byte 541 ) 542 // If fast-but-heavy PoW verification was requested, use an ethash dataset 543 if fulldag { 544 dataset := ethash.dataset(number, true) 545 if dataset.generated() { 546 digest, result = hashimotoFull(dataset.dataset, ethash.SealHash(header).Bytes(), header.Nonce.Uint64()) 547 548 // Datasets are unmapped in a finalizer. Ensure that the dataset stays alive 549 // until after the call to hashimotoFull so it's not unmapped while being used. 550 runtime.KeepAlive(dataset) 551 } else { 552 // Dataset not yet generated, don't hang, use a cache instead 553 fulldag = false 554 } 555 } 556 // If slow-but-light PoW verification was requested (or DAG not yet ready), use an ethash cache 557 if !fulldag { 558 cache := ethash.cache(number) 559 560 size := datasetSize(number) 561 if ethash.config.PowMode == ModeTest { 562 size = 32 * 1024 563 } 564 digest, result = hashimotoLight(size, cache.cache, ethash.SealHash(header).Bytes(), header.Nonce.Uint64()) 565 566 // Caches are unmapped in a finalizer. Ensure that the cache stays alive 567 // until after the call to hashimotoLight so it's not unmapped while being used. 568 runtime.KeepAlive(cache) 569 } 570 // Verify the calculated values against the ones provided in the header 571 if !isQuorum && !bytes.Equal(header.MixDigest[:], digest) { 572 return errInvalidMixDigest 573 } 574 target := new(big.Int).Div(two256, header.Difficulty) 575 if new(big.Int).SetBytes(result).Cmp(target) > 0 { 576 if !isQuorum { 577 return errInvalidPoW 578 } 579 } 580 return nil 581 } 582 583 // Prepare implements consensus.Engine, initializing the difficulty field of a 584 // header to conform to the ethash protocol. The changes are done inline. 585 func (ethash *Ethash) Prepare(chain consensus.ChainReader, header *types.Header) error { 586 parent := chain.GetHeader(header.ParentHash, header.Number.Uint64()-1) 587 if parent == nil { 588 return consensus.ErrUnknownAncestor 589 } 590 header.Difficulty = ethash.CalcDifficulty(chain, header.Time.Uint64(), parent) 591 return nil 592 } 593 594 // Finalize implements consensus.Engine, accumulating the block and uncle rewards, 595 // setting the final state and assembling the block. 596 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) { 597 // Accumulate any block and uncle rewards and commit the final state root 598 AccumulateRewards(chain.Config(), state, header, uncles) 599 header.Root = state.IntermediateRoot(chain.Config().IsEIP158(header.Number)) 600 601 // Header seems complete, assemble into a block and return 602 return types.NewBlock(header, txs, uncles, receipts), nil 603 } 604 605 // SealHash returns the hash of a block prior to it being sealed. 606 func (ethash *Ethash) SealHash(header *types.Header) (hash common.Hash) { 607 hasher := sha3.NewKeccak256() 608 609 rlp.Encode(hasher, []interface{}{ 610 header.ParentHash, 611 header.UncleHash, 612 header.Coinbase, 613 header.Root, 614 header.TxHash, 615 header.ReceiptHash, 616 header.Bloom, 617 header.Difficulty, 618 header.Number, 619 header.GasLimit, 620 header.GasUsed, 621 header.Time, 622 header.Extra, 623 }) 624 hasher.Sum(hash[:0]) 625 return hash 626 } 627 628 // Some weird constants to avoid constant memory allocs for them. 629 var ( 630 big8 = big.NewInt(8) 631 big32 = big.NewInt(32) 632 ) 633 634 // AccumulateRewards credits the coinbase of the given block with the mining 635 // reward. The total reward consists of the static block reward and rewards for 636 // included uncles. The coinbase of each uncle block is also rewarded. 637 func AccumulateRewards(config *params.ChainConfig, state *state.StateDB, header *types.Header, uncles []*types.Header) { 638 // Select the correct block reward based on chain progression 639 blockReward := FrontierBlockReward 640 if config.IsByzantium(header.Number) { 641 blockReward = ByzantiumBlockReward 642 } 643 if config.IsConstantinople(header.Number) { 644 blockReward = ConstantinopleBlockReward 645 } 646 // Accumulate the rewards for the miner and any included uncles 647 reward := new(big.Int).Set(blockReward) 648 r := new(big.Int) 649 for _, uncle := range uncles { 650 r.Add(uncle.Number, big8) 651 r.Sub(r, header.Number) 652 r.Mul(r, blockReward) 653 r.Div(r, big8) 654 state.AddBalance(uncle.Coinbase, r) 655 656 r.Div(blockReward, big32) 657 reward.Add(reward, r) 658 } 659 state.AddBalance(header.Coinbase, reward) 660 }