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