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