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