github.com/cranelv/ethereum_mpc@v0.0.0-20191031014521-23aeb1415092/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 "github.com/ethereum/go-ethereum/log" 36 ) 37 38 // Ethash proof-of-work protocol constants. 39 var ( 40 FrontierBlockReward *big.Int = big.NewInt(5e+18) // Block reward in wei for successfully mining a block 41 ByzantiumBlockReward *big.Int = big.NewInt(3e+18) // Block reward in wei for successfully mining a block upward from Byzantium 42 maxUncles = 2 // Maximum number of uncles allowed in a single block 43 allowedFutureBlockTime = 15 * time.Second // Max time from current time allowed for blocks, before they're considered future blocks 44 ) 45 46 // Various error messages to mark blocks invalid. These should be private to 47 // prevent engine specific errors from being referenced in the remainder of the 48 // codebase, inherently breaking if the engine is swapped out. Please put common 49 // error types into the consensus package. 50 var ( 51 errLargeBlockTime = errors.New("timestamp too big") 52 errZeroBlockTime = errors.New("timestamp equals parent's") 53 errTooManyUncles = errors.New("too many uncles") 54 errDuplicateUncle = errors.New("duplicate uncle") 55 errUncleIsAncestor = errors.New("uncle is ancestor") 56 errDanglingUncle = errors.New("uncle's parent is not ancestor") 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 logger := log.New("CalcDifficulty block", parent.Number) 300 next := new(big.Int).Add(parent.Number, big1) 301 switch { 302 case config.IsByzantium(next): 303 logger.Info("config.IsByzantium") 304 return calcDifficultyByzantium(time, parent) 305 case config.IsHomestead(next): 306 logger.Info("config.IsHomestead") 307 return calcDifficultyHomestead(time, parent) 308 default: 309 logger.Info("config.IsHomestead") 310 return calcDifficultyFrontier(time, parent) 311 } 312 } 313 314 // Some weird constants to avoid constant memory allocs for them. 315 var ( 316 expDiffPeriod = big.NewInt(100000) 317 big1 = big.NewInt(1) 318 big2 = big.NewInt(2) 319 big9 = big.NewInt(9) 320 big10 = big.NewInt(10) 321 bigMinus99 = big.NewInt(-99) 322 big2999999 = big.NewInt(2999999) 323 ) 324 325 // calcDifficultyByzantium is the difficulty adjustment algorithm. It returns 326 // the difficulty that a new block should have when created at time given the 327 // parent block's time and difficulty. The calculation uses the Byzantium rules. 328 func calcDifficultyByzantium(time uint64, parent *types.Header) *big.Int { 329 // https://github.com/ethereum/EIPs/issues/100. 330 // algorithm: 331 // diff = (parent_diff + 332 // (parent_diff / 2048 * max((2 if len(parent.uncles) else 1) - ((timestamp - parent.timestamp) // 9), -99)) 333 // ) + 2^(periodCount - 2) 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 // (2 if len(parent_uncles) else 1) - (block_timestamp - parent_timestamp) // 9 341 x.Sub(bigTime, bigParentTime) 342 z := new(big.Int).Set(x) 343 x.Div(x, params.DurationLimit) 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((2 if len(parent.uncles) else 1) - ((timestamp - parent.timestamp) // 9), -99)) 354 y.Div(parent.Difficulty, params.DifficultyBoundDivisor) 355 if y.Sign() ==0 { 356 y = big1 357 } 358 x.Mul(y, x) 359 x.Add(parent.Difficulty, x) 360 // minimum difficulty can ever be (before exponential factor) 361 if x.Cmp(params.MinimumDifficulty) < 0 { 362 x.Set(params.MinimumDifficulty) 363 } 364 365 log.Info("CalcDifficulty","blockNumber",parent.Number,"time",z,"diff",x) 366 return x 367 } 368 369 // calcDifficultyHomestead is the difficulty adjustment algorithm. It returns 370 // the difficulty that a new block should have when created at time given the 371 // parent block's time and difficulty. The calculation uses the Homestead rules. 372 func calcDifficultyHomestead(time uint64, parent *types.Header) *big.Int { 373 // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-2.md 374 // algorithm: 375 // diff = (parent_diff + 376 // (parent_diff / 2048 * max(1 - (block_timestamp - parent_timestamp) // 10, -99)) 377 // ) + 2^(periodCount - 2) 378 379 bigTime := new(big.Int).SetUint64(time) 380 bigParentTime := new(big.Int).Set(parent.Time) 381 382 // holds intermediate values to make the algo easier to read & audit 383 x := new(big.Int) 384 y := new(big.Int) 385 386 // 1 - (block_timestamp - parent_timestamp) // 10 387 x.Sub(bigTime, bigParentTime) 388 x.Div(x, big10) 389 x.Sub(big1, x) 390 391 // max(1 - (block_timestamp - parent_timestamp) // 10, -99) 392 if x.Cmp(bigMinus99) < 0 { 393 x.Set(bigMinus99) 394 } 395 // (parent_diff + parent_diff // 2048 * max(1 - (block_timestamp - parent_timestamp) // 10, -99)) 396 y.Div(parent.Difficulty, params.DifficultyBoundDivisor) 397 x.Mul(y, x) 398 x.Add(parent.Difficulty, x) 399 400 // minimum difficulty can ever be (before exponential factor) 401 if x.Cmp(params.MinimumDifficulty) < 0 { 402 x.Set(params.MinimumDifficulty) 403 } 404 // for the exponential factor 405 periodCount := new(big.Int).Add(parent.Number, big1) 406 periodCount.Div(periodCount, expDiffPeriod) 407 408 // the exponential factor, commonly referred to as "the bomb" 409 // diff = diff + 2^(periodCount - 2) 410 if periodCount.Cmp(big1) > 0 { 411 y.Sub(periodCount, big2) 412 y.Exp(big2, y, nil) 413 x.Add(x, y) 414 } 415 return x 416 } 417 418 // calcDifficultyFrontier is the difficulty adjustment algorithm. It returns the 419 // difficulty that a new block should have when created at time given the parent 420 // block's time and difficulty. The calculation uses the Frontier rules. 421 func calcDifficultyFrontier(time uint64, parent *types.Header) *big.Int { 422 diff := new(big.Int) 423 adjust := new(big.Int).Div(parent.Difficulty, params.DifficultyBoundDivisor) 424 bigTime := new(big.Int) 425 bigParentTime := new(big.Int) 426 427 bigTime.SetUint64(time) 428 bigParentTime.Set(parent.Time) 429 430 if bigTime.Sub(bigTime, bigParentTime).Cmp(params.DurationLimit) < 0 { 431 diff.Add(parent.Difficulty, adjust) 432 } else { 433 diff.Sub(parent.Difficulty, adjust) 434 } 435 if diff.Cmp(params.MinimumDifficulty) < 0 { 436 diff.Set(params.MinimumDifficulty) 437 } 438 439 periodCount := new(big.Int).Add(parent.Number, big1) 440 periodCount.Div(periodCount, expDiffPeriod) 441 if periodCount.Cmp(big1) > 0 { 442 // diff = diff + 2^(periodCount - 2) 443 expDiff := periodCount.Sub(periodCount, big2) 444 expDiff.Exp(big2, expDiff, nil) 445 diff.Add(diff, expDiff) 446 diff = math.BigMax(diff, params.MinimumDifficulty) 447 } 448 return diff 449 } 450 451 // VerifySeal implements consensus.Engine, checking whether the given block satisfies 452 // the PoW difficulty requirements. 453 func (ethash *Ethash) VerifySeal(chain consensus.ChainReader, header *types.Header) error { 454 // If we're running a fake PoW, accept any seal as valid 455 if ethash.config.PowMode == ModeFake || ethash.config.PowMode == ModeFullFake { 456 time.Sleep(ethash.fakeDelay) 457 if ethash.fakeFail == header.Number.Uint64() { 458 return errInvalidPoW 459 } 460 return nil 461 } 462 // If we're running a shared PoW, delegate verification to it 463 if ethash.shared != nil { 464 return ethash.shared.VerifySeal(chain, header) 465 } 466 // Ensure that we have a valid difficulty for the block 467 if header.Difficulty.Sign() <= 0 { 468 return errInvalidDifficulty 469 } 470 // Recompute the digest and PoW value and verify against the header 471 // number := header.Number.Uint64() 472 473 // cache := ethash.cache(number) 474 // size := datasetSize(number) 475 // if ethash.config.PowMode == ModeTest { 476 // size = 32 * 1024 477 // } 478 digest, result := hashimotoLight(32, nil, header.HashNoNonce().Bytes(), header.Nonce.Uint64()) 479 // Caches are unmapped in a finalizer. Ensure that the cache stays live 480 // until after the call to hashimotoLight so it's not unmapped while being used. 481 // runtime.KeepAlive(cache) 482 483 if !bytes.Equal(header.MixDigest[:], digest) { 484 return errInvalidMixDigest 485 } 486 target := new(big.Int).Div(maxUint256, header.Difficulty) 487 if new(big.Int).SetBytes(result).Cmp(target) > 0 { 488 return errInvalidPoW 489 } 490 return nil 491 } 492 493 // Prepare implements consensus.Engine, initializing the difficulty field of a 494 // header to conform to the ethash protocol. The changes are done inline. 495 func (ethash *Ethash) Prepare(chain consensus.ChainReader, header *types.Header) error { 496 parent := chain.GetHeader(header.ParentHash, header.Number.Uint64()-1) 497 if parent == nil { 498 return consensus.ErrUnknownAncestor 499 } 500 header.Difficulty = ethash.CalcDifficulty(chain, header.Time.Uint64(), parent) 501 return nil 502 } 503 504 // Finalize implements consensus.Engine, accumulating the block and uncle rewards, 505 // setting the final state and assembling the block. 506 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) { 507 // Accumulate any block and uncle rewards and commit the final state root 508 accumulateRewards(chain.Config(), state, header, uncles) 509 header.Root = state.IntermediateRoot(chain.Config().IsEIP158(header.Number)) 510 // Header seems complete, assemble into a block and return 511 return types.NewBlock(header, txs, uncles, receipts), nil 512 } 513 514 // Some weird constants to avoid constant memory allocs for them. 515 var ( 516 big8 = big.NewInt(8) 517 big32 = big.NewInt(32) 518 ) 519 520 // AccumulateRewards credits the coinbase of the given block with the mining 521 // reward. The total reward consists of the static block reward and rewards for 522 // included uncles. The coinbase of each uncle block is also rewarded. 523 func accumulateRewards(config *params.ChainConfig, state *state.StateDB, header *types.Header, uncles []*types.Header) { 524 // Select the correct block reward based on chain progression 525 blockReward := FrontierBlockReward 526 if config.IsByzantium(header.Number) { 527 blockReward = ByzantiumBlockReward 528 } 529 // Accumulate the rewards for the miner and any included uncles 530 reward := new(big.Int).Set(blockReward) 531 r := new(big.Int) 532 for _, uncle := range uncles { 533 r.Add(uncle.Number, big8) 534 r.Sub(r, header.Number) 535 r.Mul(r, blockReward) 536 r.Div(r, big8) 537 state.AddBalance(uncle.Coinbase, r) 538 539 r.Div(blockReward, big32) 540 reward.Add(reward, r) 541 } 542 state.AddBalance(header.Coinbase, reward) 543 }