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