github.com/kivutar/go-ethereum@v1.7.4-0.20180117074026-6fdb126e9630/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 "github.com/ethereum/go-ethereum/common" 28 "github.com/ethereum/go-ethereum/common/math" 29 "github.com/ethereum/go-ethereum/consensus" 30 "github.com/ethereum/go-ethereum/consensus/misc" 31 "github.com/ethereum/go-ethereum/core/state" 32 "github.com/ethereum/go-ethereum/core/types" 33 "github.com/ethereum/go-ethereum/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 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, ancestors := set.New(), make(map[common.Hash]*types.Header) 182 183 number, parent := block.NumberU64()-1, block.ParentHash() 184 for i := 0; i < 7; i++ { 185 ancestor := chain.GetBlock(parent, number) 186 if ancestor == nil { 187 break 188 } 189 ancestors[ancestor.Hash()] = ancestor.Header() 190 for _, uncle := range ancestor.Uncles() { 191 uncles.Add(uncle.Hash()) 192 } 193 parent, number = ancestor.ParentHash(), number-1 194 } 195 ancestors[block.Hash()] = block.Header() 196 uncles.Add(block.Hash()) 197 198 // Verify each of the uncles that it's recent, but not an ancestor 199 for _, uncle := range block.Uncles() { 200 // Make sure every uncle is rewarded only once 201 hash := uncle.Hash() 202 if uncles.Has(hash) { 203 return errDuplicateUncle 204 } 205 uncles.Add(hash) 206 207 // Make sure the uncle has a valid ancestry 208 if ancestors[hash] != nil { 209 return errUncleIsAncestor 210 } 211 if ancestors[uncle.ParentHash] == nil || uncle.ParentHash == block.ParentHash() { 212 return errDanglingUncle 213 } 214 if err := ethash.verifyHeader(chain, uncle, ancestors[uncle.ParentHash], true, true); err != nil { 215 return err 216 } 217 } 218 return nil 219 } 220 221 // verifyHeader checks whether a header conforms to the consensus rules of the 222 // stock Ethereum ethash engine. 223 // See YP section 4.3.4. "Block Header Validity" 224 func (ethash *Ethash) verifyHeader(chain consensus.ChainReader, header, parent *types.Header, uncle bool, seal bool) error { 225 // Ensure that the header's extra-data section is of a reasonable size 226 if uint64(len(header.Extra)) > params.MaximumExtraDataSize { 227 return fmt.Errorf("extra-data too long: %d > %d", len(header.Extra), params.MaximumExtraDataSize) 228 } 229 // Verify the header's timestamp 230 if uncle { 231 if header.Time.Cmp(math.MaxBig256) > 0 { 232 return errLargeBlockTime 233 } 234 } else { 235 if header.Time.Cmp(big.NewInt(time.Now().Add(allowedFutureBlockTime).Unix())) > 0 { 236 return consensus.ErrFutureBlock 237 } 238 } 239 if header.Time.Cmp(parent.Time) <= 0 { 240 return errZeroBlockTime 241 } 242 // Verify the block's difficulty based in it's timestamp and parent's difficulty 243 expected := ethash.CalcDifficulty(chain, header.Time.Uint64(), parent) 244 245 if expected.Cmp(header.Difficulty) != 0 { 246 return fmt.Errorf("invalid difficulty: have %v, want %v", header.Difficulty, expected) 247 } 248 // Verify that the gas limit is <= 2^63-1 249 cap := uint64(0x7fffffffffffffff) 250 if header.GasLimit > cap { 251 return fmt.Errorf("invalid gasLimit: have %v, max %v", header.GasLimit, cap) 252 } 253 // Verify that the gasUsed is <= gasLimit 254 if header.GasUsed > header.GasLimit { 255 return fmt.Errorf("invalid gasUsed: have %d, gasLimit %d", header.GasUsed, header.GasLimit) 256 } 257 258 // Verify that the gas limit remains within allowed bounds 259 diff := int64(parent.GasLimit) - int64(header.GasLimit) 260 if diff < 0 { 261 diff *= -1 262 } 263 limit := parent.GasLimit / params.GasLimitBoundDivisor 264 265 if uint64(diff) >= limit || header.GasLimit < params.MinGasLimit { 266 return fmt.Errorf("invalid gas limit: have %d, want %d += %d", header.GasLimit, parent.GasLimit, limit) 267 } 268 // Verify that the block number is parent's +1 269 if diff := new(big.Int).Sub(header.Number, parent.Number); diff.Cmp(big.NewInt(1)) != 0 { 270 return consensus.ErrInvalidNumber 271 } 272 // Verify the engine specific seal securing the block 273 if seal { 274 if err := ethash.VerifySeal(chain, header); err != nil { 275 return err 276 } 277 } 278 // If all checks passed, validate any special fields for hard forks 279 if err := misc.VerifyDAOHeaderExtraData(chain.Config(), header); err != nil { 280 return err 281 } 282 if err := misc.VerifyForkHashes(chain.Config(), header, uncle); err != nil { 283 return err 284 } 285 return nil 286 } 287 288 // CalcDifficulty is the difficulty adjustment algorithm. It returns 289 // the difficulty that a new block should have when created at time 290 // given the parent block's time and difficulty. 291 func (ethash *Ethash) CalcDifficulty(chain consensus.ChainReader, time uint64, parent *types.Header) *big.Int { 292 return CalcDifficulty(chain.Config(), time, parent) 293 } 294 295 // CalcDifficulty is the difficulty adjustment algorithm. It returns 296 // the difficulty that a new block should have when created at time 297 // given the parent block's time and difficulty. 298 func CalcDifficulty(config *params.ChainConfig, time uint64, parent *types.Header) *big.Int { 299 next := new(big.Int).Add(parent.Number, big1) 300 switch { 301 case config.IsByzantium(next): 302 return calcDifficultyByzantium(time, parent) 303 case config.IsHomestead(next): 304 return calcDifficultyHomestead(time, parent) 305 default: 306 return calcDifficultyFrontier(time, parent) 307 } 308 } 309 310 // Some weird constants to avoid constant memory allocs for them. 311 var ( 312 expDiffPeriod = big.NewInt(100000) 313 big1 = big.NewInt(1) 314 big2 = big.NewInt(2) 315 big9 = big.NewInt(9) 316 big10 = big.NewInt(10) 317 bigMinus99 = big.NewInt(-99) 318 big2999999 = big.NewInt(2999999) 319 ) 320 321 // calcDifficultyByzantium is the difficulty adjustment algorithm. It returns 322 // the difficulty that a new block should have when created at time given the 323 // parent block's time and difficulty. The calculation uses the Byzantium rules. 324 func calcDifficultyByzantium(time uint64, parent *types.Header) *big.Int { 325 // https://github.com/ethereum/EIPs/issues/100. 326 // algorithm: 327 // diff = (parent_diff + 328 // (parent_diff / 2048 * max((2 if len(parent.uncles) else 1) - ((timestamp - parent.timestamp) // 9), -99)) 329 // ) + 2^(periodCount - 2) 330 331 bigTime := new(big.Int).SetUint64(time) 332 bigParentTime := new(big.Int).Set(parent.Time) 333 334 // holds intermediate values to make the algo easier to read & audit 335 x := new(big.Int) 336 y := new(big.Int) 337 338 // (2 if len(parent_uncles) else 1) - (block_timestamp - parent_timestamp) // 9 339 x.Sub(bigTime, bigParentTime) 340 x.Div(x, big9) 341 if parent.UncleHash == types.EmptyUncleHash { 342 x.Sub(big1, x) 343 } else { 344 x.Sub(big2, x) 345 } 346 // max((2 if len(parent_uncles) else 1) - (block_timestamp - parent_timestamp) // 9, -99) 347 if x.Cmp(bigMinus99) < 0 { 348 x.Set(bigMinus99) 349 } 350 // parent_diff + (parent_diff / 2048 * max((2 if len(parent.uncles) else 1) - ((timestamp - parent.timestamp) // 9), -99)) 351 y.Div(parent.Difficulty, params.DifficultyBoundDivisor) 352 x.Mul(y, x) 353 x.Add(parent.Difficulty, x) 354 355 // minimum difficulty can ever be (before exponential factor) 356 if x.Cmp(params.MinimumDifficulty) < 0 { 357 x.Set(params.MinimumDifficulty) 358 } 359 // calculate a fake block numer for the ice-age delay: 360 // https://github.com/ethereum/EIPs/pull/669 361 // fake_block_number = min(0, block.number - 3_000_000 362 fakeBlockNumber := new(big.Int) 363 if parent.Number.Cmp(big2999999) >= 0 { 364 fakeBlockNumber = fakeBlockNumber.Sub(parent.Number, big2999999) // Note, parent is 1 less than the actual block number 365 } 366 // for the exponential factor 367 periodCount := fakeBlockNumber 368 periodCount.Div(periodCount, expDiffPeriod) 369 370 // the exponential factor, commonly referred to as "the bomb" 371 // diff = diff + 2^(periodCount - 2) 372 if periodCount.Cmp(big1) > 0 { 373 y.Sub(periodCount, big2) 374 y.Exp(big2, y, nil) 375 x.Add(x, y) 376 } 377 return x 378 } 379 380 // calcDifficultyHomestead is the difficulty adjustment algorithm. It returns 381 // the difficulty that a new block should have when created at time given the 382 // parent block's time and difficulty. The calculation uses the Homestead rules. 383 func calcDifficultyHomestead(time uint64, parent *types.Header) *big.Int { 384 // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-2.md 385 // algorithm: 386 // diff = (parent_diff + 387 // (parent_diff / 2048 * max(1 - (block_timestamp - parent_timestamp) // 10, -99)) 388 // ) + 2^(periodCount - 2) 389 390 bigTime := new(big.Int).SetUint64(time) 391 bigParentTime := new(big.Int).Set(parent.Time) 392 393 // holds intermediate values to make the algo easier to read & audit 394 x := new(big.Int) 395 y := new(big.Int) 396 397 // 1 - (block_timestamp - parent_timestamp) // 10 398 x.Sub(bigTime, bigParentTime) 399 x.Div(x, big10) 400 x.Sub(big1, x) 401 402 // max(1 - (block_timestamp - parent_timestamp) // 10, -99) 403 if x.Cmp(bigMinus99) < 0 { 404 x.Set(bigMinus99) 405 } 406 // (parent_diff + parent_diff // 2048 * max(1 - (block_timestamp - parent_timestamp) // 10, -99)) 407 y.Div(parent.Difficulty, params.DifficultyBoundDivisor) 408 x.Mul(y, x) 409 x.Add(parent.Difficulty, x) 410 411 // minimum difficulty can ever be (before exponential factor) 412 if x.Cmp(params.MinimumDifficulty) < 0 { 413 x.Set(params.MinimumDifficulty) 414 } 415 // for the exponential factor 416 periodCount := new(big.Int).Add(parent.Number, big1) 417 periodCount.Div(periodCount, expDiffPeriod) 418 419 // the exponential factor, commonly referred to as "the bomb" 420 // diff = diff + 2^(periodCount - 2) 421 if periodCount.Cmp(big1) > 0 { 422 y.Sub(periodCount, big2) 423 y.Exp(big2, y, nil) 424 x.Add(x, y) 425 } 426 return x 427 } 428 429 // calcDifficultyFrontier is the difficulty adjustment algorithm. It returns the 430 // difficulty that a new block should have when created at time given the parent 431 // block's time and difficulty. The calculation uses the Frontier rules. 432 func calcDifficultyFrontier(time uint64, parent *types.Header) *big.Int { 433 diff := new(big.Int) 434 adjust := new(big.Int).Div(parent.Difficulty, params.DifficultyBoundDivisor) 435 bigTime := new(big.Int) 436 bigParentTime := new(big.Int) 437 438 bigTime.SetUint64(time) 439 bigParentTime.Set(parent.Time) 440 441 if bigTime.Sub(bigTime, bigParentTime).Cmp(params.DurationLimit) < 0 { 442 diff.Add(parent.Difficulty, adjust) 443 } else { 444 diff.Sub(parent.Difficulty, adjust) 445 } 446 if diff.Cmp(params.MinimumDifficulty) < 0 { 447 diff.Set(params.MinimumDifficulty) 448 } 449 450 periodCount := new(big.Int).Add(parent.Number, big1) 451 periodCount.Div(periodCount, expDiffPeriod) 452 if periodCount.Cmp(big1) > 0 { 453 // diff = diff + 2^(periodCount - 2) 454 expDiff := periodCount.Sub(periodCount, big2) 455 expDiff.Exp(big2, expDiff, nil) 456 diff.Add(diff, expDiff) 457 diff = math.BigMax(diff, params.MinimumDifficulty) 458 } 459 return diff 460 } 461 462 // VerifySeal implements consensus.Engine, checking whether the given block satisfies 463 // the PoW difficulty requirements. 464 func (ethash *Ethash) VerifySeal(chain consensus.ChainReader, header *types.Header) error { 465 // If we're running a fake PoW, accept any seal as valid 466 if ethash.config.PowMode == ModeFake || ethash.config.PowMode == ModeFullFake { 467 time.Sleep(ethash.fakeDelay) 468 if ethash.fakeFail == header.Number.Uint64() { 469 return errInvalidPoW 470 } 471 return nil 472 } 473 // If we're running a shared PoW, delegate verification to it 474 if ethash.shared != nil { 475 return ethash.shared.VerifySeal(chain, header) 476 } 477 // Sanity check that the block number is below the lookup table size (60M blocks) 478 number := header.Number.Uint64() 479 if number/epochLength >= uint64(len(cacheSizes)) { 480 // Go < 1.7 cannot calculate new cache/dataset sizes (no fast prime check) 481 return errNonceOutOfRange 482 } 483 // Ensure that we have a valid difficulty for the block 484 if header.Difficulty.Sign() <= 0 { 485 return errInvalidDifficulty 486 } 487 // Recompute the digest and PoW value and verify against the header 488 cache := ethash.cache(number) 489 490 size := datasetSize(number) 491 if ethash.config.PowMode == ModeTest { 492 size = 32 * 1024 493 } 494 digest, result := hashimotoLight(size, cache, header.HashNoNonce().Bytes(), header.Nonce.Uint64()) 495 if !bytes.Equal(header.MixDigest[:], digest) { 496 return errInvalidMixDigest 497 } 498 target := new(big.Int).Div(maxUint256, header.Difficulty) 499 if new(big.Int).SetBytes(result).Cmp(target) > 0 { 500 return errInvalidPoW 501 } 502 return nil 503 } 504 505 // Prepare implements consensus.Engine, initializing the difficulty field of a 506 // header to conform to the ethash protocol. The changes are done inline. 507 func (ethash *Ethash) Prepare(chain consensus.ChainReader, header *types.Header) error { 508 parent := chain.GetHeader(header.ParentHash, header.Number.Uint64()-1) 509 if parent == nil { 510 return consensus.ErrUnknownAncestor 511 } 512 header.Difficulty = ethash.CalcDifficulty(chain, header.Time.Uint64(), parent) 513 return nil 514 } 515 516 // Finalize implements consensus.Engine, accumulating the block and uncle rewards, 517 // setting the final state and assembling the block. 518 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) { 519 // Accumulate any block and uncle rewards and commit the final state root 520 accumulateRewards(chain.Config(), state, header, uncles) 521 header.Root = state.IntermediateRoot(chain.Config().IsEIP158(header.Number)) 522 523 // Header seems complete, assemble into a block and return 524 return types.NewBlock(header, txs, uncles, receipts), nil 525 } 526 527 // Some weird constants to avoid constant memory allocs for them. 528 var ( 529 big8 = big.NewInt(8) 530 big32 = big.NewInt(32) 531 ) 532 533 // AccumulateRewards credits the coinbase of the given block with the mining 534 // reward. The total reward consists of the static block reward and rewards for 535 // included uncles. The coinbase of each uncle block is also rewarded. 536 func accumulateRewards(config *params.ChainConfig, state *state.StateDB, header *types.Header, uncles []*types.Header) { 537 // Select the correct block reward based on chain progression 538 blockReward := FrontierBlockReward 539 if config.IsByzantium(header.Number) { 540 blockReward = ByzantiumBlockReward 541 } 542 // Accumulate the rewards for the miner and any included uncles 543 reward := new(big.Int).Set(blockReward) 544 r := new(big.Int) 545 for _, uncle := range uncles { 546 r.Add(uncle.Number, big8) 547 r.Sub(r, header.Number) 548 r.Mul(r, blockReward) 549 r.Div(r, big8) 550 state.AddBalance(uncle.Coinbase, r) 551 552 r.Div(blockReward, big32) 553 reward.Add(reward, r) 554 } 555 state.AddBalance(header.Coinbase, reward) 556 }