github.com/etherbanking/go-etherbanking@v1.7.1-0.20181009210156-cf649bca5aba/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/etherbanking/go-etherbanking/common" 28 "github.com/etherbanking/go-etherbanking/common/math" 29 "github.com/etherbanking/go-etherbanking/consensus" 30 "github.com/etherbanking/go-etherbanking/consensus/misc" 31 "github.com/etherbanking/go-etherbanking/core/state" 32 "github.com/etherbanking/go-etherbanking/core/types" 33 "github.com/etherbanking/go-etherbanking/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(1e+14) // 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 eip998BlockReward *big.Int = big.NewInt(0) 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.fakeFull { 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.fakeFull || 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.fakeFull { 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().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 := CalcDifficulty(chain.Config(), header.Time.Uint64(), parent) 244 if expected.Cmp(header.Difficulty) != 0 { 245 return fmt.Errorf("invalid difficulty: have %v, want %v", header.Difficulty, expected) 246 } 247 // Verify that the gas limit is <= 2^63-1 248 if header.GasLimit.Cmp(math.MaxBig63) > 0 { 249 return fmt.Errorf("invalid gasLimit: have %v, max %v", header.GasLimit, math.MaxBig63) 250 } 251 // Verify that the gasUsed is <= gasLimit 252 if header.GasUsed.Cmp(header.GasLimit) > 0 { 253 return fmt.Errorf("invalid gasUsed: have %v, gasLimit %v", header.GasUsed, header.GasLimit) 254 } 255 256 // Verify that the gas limit remains within allowed bounds 257 diff := new(big.Int).Set(parent.GasLimit) 258 diff = diff.Sub(diff, header.GasLimit) 259 diff.Abs(diff) 260 261 limit := new(big.Int).Set(parent.GasLimit) 262 limit = limit.Div(limit, params.GasLimitBoundDivisor) 263 264 if diff.Cmp(limit) >= 0 || header.GasLimit.Cmp(params.MinGasLimit) < 0 { 265 return fmt.Errorf("invalid gas limit: have %v, want %v += %v", header.GasLimit, parent.GasLimit, limit) 266 } 267 // Verify that the block number is parent's +1 268 if diff := new(big.Int).Sub(header.Number, parent.Number); diff.Cmp(big.NewInt(1)) != 0 { 269 return consensus.ErrInvalidNumber 270 } 271 // Verify the engine specific seal securing the block 272 if seal { 273 if err := ethash.VerifySeal(chain, header); err != nil { 274 return err 275 } 276 } 277 // If all checks passed, validate any special fields for hard forks 278 if err := misc.VerifyDAOHeaderExtraData(chain.Config(), header); err != nil { 279 return err 280 } 281 if err := misc.VerifyForkHashes(chain.Config(), header, uncle); err != nil { 282 return err 283 } 284 return nil 285 } 286 287 // CalcDifficulty is the difficulty adjustment algorithm. It returns 288 // the difficulty that a new block should have when created at time 289 // given the parent block's time and difficulty. 290 // TODO (karalabe): Move the chain maker into this package and make this private! 291 func CalcDifficulty(config *params.ChainConfig, time uint64, parent *types.Header) *big.Int { 292 next := new(big.Int).Add(parent.Number, big1) 293 switch { 294 case config.IsByzantium(next): 295 return calcDifficultyByzantium(time, parent) 296 case config.IsHomestead(next): 297 return calcDifficultyHomestead(time, parent) 298 default: 299 return calcDifficultyFrontier(time, parent) 300 } 301 } 302 303 // Some weird constants to avoid constant memory allocs for them. 304 var ( 305 expDiffPeriod = big.NewInt(100000) 306 big1 = big.NewInt(1) 307 big2 = big.NewInt(2) 308 big9 = big.NewInt(9) 309 big10 = big.NewInt(10) 310 bigMinus99 = big.NewInt(-99) 311 big2999999 = big.NewInt(2999999) 312 ) 313 314 // calcDifficultyByzantium is the difficulty adjustment algorithm. It returns 315 // the difficulty that a new block should have when created at time given the 316 // parent block's time and difficulty. The calculation uses the Byzantium rules. 317 func calcDifficultyByzantium(time uint64, parent *types.Header) *big.Int { 318 // https://github.com/ethereum/EIPs/issues/100. 319 // algorithm: 320 // diff = (parent_diff + 321 // (parent_diff / 2048 * max((2 if len(parent.uncles) else 1) - ((timestamp - parent.timestamp) // 9), -99)) 322 // ) + 2^(periodCount - 2) 323 324 bigTime := new(big.Int).SetUint64(time) 325 bigParentTime := new(big.Int).Set(parent.Time) 326 327 // holds intermediate values to make the algo easier to read & audit 328 x := new(big.Int) 329 y := new(big.Int) 330 331 // (2 if len(parent_uncles) else 1) - (block_timestamp - parent_timestamp) // 9 332 x.Sub(bigTime, bigParentTime) 333 x.Div(x, big9) 334 if parent.UncleHash == types.EmptyUncleHash { 335 x.Sub(big1, x) 336 } else { 337 x.Sub(big2, x) 338 } 339 // max((2 if len(parent_uncles) else 1) - (block_timestamp - parent_timestamp) // 9, -99) 340 if x.Cmp(bigMinus99) < 0 { 341 x.Set(bigMinus99) 342 } 343 // (parent_diff + parent_diff // 2048 * max(1 - (block_timestamp - parent_timestamp) // 10, -99)) 344 y.Div(parent.Difficulty, params.DifficultyBoundDivisor) 345 x.Mul(y, x) 346 x.Add(parent.Difficulty, x) 347 348 // minimum difficulty can ever be (before exponential factor) 349 if x.Cmp(params.MinimumDifficulty) < 0 { 350 x.Set(params.MinimumDifficulty) 351 } 352 // calculate a fake block numer for the ice-age delay: 353 // https://github.com/ethereum/EIPs/pull/669 354 // fake_block_number = min(0, block.number - 3_000_000 355 fakeBlockNumber := new(big.Int) 356 if parent.Number.Cmp(big2999999) >= 0 { 357 fakeBlockNumber = fakeBlockNumber.Sub(parent.Number, big2999999) // Note, parent is 1 less than the actual block number 358 } 359 // for the exponential factor 360 periodCount := fakeBlockNumber 361 periodCount.Div(periodCount, expDiffPeriod) 362 363 // the exponential factor, commonly referred to as "the bomb" 364 // diff = diff + 2^(periodCount - 2) 365 if periodCount.Cmp(big1) > 0 { 366 y.Sub(periodCount, big2) 367 y.Exp(big2, y, nil) 368 x.Add(x, y) 369 } 370 return x 371 } 372 373 // calcDifficultyHomestead is the difficulty adjustment algorithm. It returns 374 // the difficulty that a new block should have when created at time given the 375 // parent block's time and difficulty. The calculation uses the Homestead rules. 376 func calcDifficultyHomestead(time uint64, parent *types.Header) *big.Int { 377 // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-2.mediawiki 378 // algorithm: 379 // diff = (parent_diff + 380 // (parent_diff / 2048 * max(1 - (block_timestamp - parent_timestamp) // 10, -99)) 381 // ) + 2^(periodCount - 2) 382 383 bigTime := new(big.Int).SetUint64(time) 384 bigParentTime := new(big.Int).Set(parent.Time) 385 386 // holds intermediate values to make the algo easier to read & audit 387 x := new(big.Int) 388 y := new(big.Int) 389 390 // 1 - (block_timestamp - parent_timestamp) // 10 391 x.Sub(bigTime, bigParentTime) 392 x.Div(x, big10) 393 x.Sub(big1, x) 394 395 // max(1 - (block_timestamp - parent_timestamp) // 10, -99) 396 if x.Cmp(bigMinus99) < 0 { 397 x.Set(bigMinus99) 398 } 399 // (parent_diff + parent_diff // 2048 * max(1 - (block_timestamp - parent_timestamp) // 10, -99)) 400 y.Div(parent.Difficulty, params.DifficultyBoundDivisor) 401 x.Mul(y, x) 402 x.Add(parent.Difficulty, x) 403 404 // minimum difficulty can ever be (before exponential factor) 405 if x.Cmp(params.MinimumDifficulty) < 0 { 406 x.Set(params.MinimumDifficulty) 407 } 408 // for the exponential factor 409 periodCount := new(big.Int).Add(parent.Number, big1) 410 periodCount.Div(periodCount, expDiffPeriod) 411 412 // the exponential factor, commonly referred to as "the bomb" 413 // diff = diff + 2^(periodCount - 2) 414 if periodCount.Cmp(big1) > 0 { 415 y.Sub(periodCount, big2) 416 y.Exp(big2, y, nil) 417 x.Add(x, y) 418 } 419 return x 420 } 421 422 // calcDifficultyFrontier is the difficulty adjustment algorithm. It returns the 423 // difficulty that a new block should have when created at time given the parent 424 // block's time and difficulty. The calculation uses the Frontier rules. 425 func calcDifficultyFrontier(time uint64, parent *types.Header) *big.Int { 426 diff := new(big.Int) 427 adjust := new(big.Int).Div(parent.Difficulty, params.DifficultyBoundDivisor) 428 bigTime := new(big.Int) 429 bigParentTime := new(big.Int) 430 431 bigTime.SetUint64(time) 432 bigParentTime.Set(parent.Time) 433 434 if bigTime.Sub(bigTime, bigParentTime).Cmp(params.DurationLimit) < 0 { 435 diff.Add(parent.Difficulty, adjust) 436 } else { 437 diff.Sub(parent.Difficulty, adjust) 438 } 439 if diff.Cmp(params.MinimumDifficulty) < 0 { 440 diff.Set(params.MinimumDifficulty) 441 } 442 443 periodCount := new(big.Int).Add(parent.Number, big1) 444 periodCount.Div(periodCount, expDiffPeriod) 445 if periodCount.Cmp(big1) > 0 { 446 // diff = diff + 2^(periodCount - 2) 447 expDiff := periodCount.Sub(periodCount, big2) 448 expDiff.Exp(big2, expDiff, nil) 449 diff.Add(diff, expDiff) 450 diff = math.BigMax(diff, params.MinimumDifficulty) 451 } 452 return diff 453 } 454 455 // VerifySeal implements consensus.Engine, checking whether the given block satisfies 456 // the PoW difficulty requirements. 457 func (ethash *Ethash) VerifySeal(chain consensus.ChainReader, header *types.Header) error { 458 // If we're running a fake PoW, accept any seal as valid 459 if ethash.fakeMode { 460 time.Sleep(ethash.fakeDelay) 461 if ethash.fakeFail == header.Number.Uint64() { 462 return errInvalidPoW 463 } 464 return nil 465 } 466 // If we're running a shared PoW, delegate verification to it 467 if ethash.shared != nil { 468 return ethash.shared.VerifySeal(chain, header) 469 } 470 // Sanity check that the block number is below the lookup table size (60M blocks) 471 number := header.Number.Uint64() 472 if number/epochLength >= uint64(len(cacheSizes)) { 473 // Go < 1.7 cannot calculate new cache/dataset sizes (no fast prime check) 474 return errNonceOutOfRange 475 } 476 // Ensure that we have a valid difficulty for the block 477 if header.Difficulty.Sign() <= 0 { 478 return errInvalidDifficulty 479 } 480 // Recompute the digest and PoW value and verify against the header 481 cache := ethash.cache(number) 482 483 size := datasetSize(number) 484 if ethash.tester { 485 size = 32 * 1024 486 } 487 digest, result := hashimotoLight(size, cache, header.HashNoNonce().Bytes(), header.Nonce.Uint64()) 488 if !bytes.Equal(header.MixDigest[:], digest) { 489 return errInvalidMixDigest 490 } 491 target := new(big.Int).Div(maxUint256, header.Difficulty) 492 if new(big.Int).SetBytes(result).Cmp(target) > 0 { 493 return errInvalidPoW 494 } 495 return nil 496 } 497 498 // Prepare implements consensus.Engine, initializing the difficulty field of a 499 // header to conform to the ethash protocol. The changes are done inline. 500 func (ethash *Ethash) Prepare(chain consensus.ChainReader, header *types.Header) error { 501 parent := chain.GetHeader(header.ParentHash, header.Number.Uint64()-1) 502 if parent == nil { 503 return consensus.ErrUnknownAncestor 504 } 505 header.Difficulty = CalcDifficulty(chain.Config(), header.Time.Uint64(), parent) 506 507 return nil 508 } 509 510 // Finalize implements consensus.Engine, accumulating the block and uncle rewards, 511 // setting the final state and assembling the block. 512 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) { 513 // Accumulate any block and uncle rewards and commit the final state root 514 AccumulateRewards(chain.Config(), state, header, uncles) 515 header.Root = state.IntermediateRoot(chain.Config().IsEIP158(header.Number)) 516 517 // Header seems complete, assemble into a block and return 518 return types.NewBlock(header, txs, uncles, receipts), nil 519 } 520 521 // Some weird constants to avoid constant memory allocs for them. 522 var ( 523 big8 = big.NewInt(8) 524 big32 = big.NewInt(32) 525 ) 526 527 // AccumulateRewards credits the coinbase of the given block with the mining 528 // reward. The total reward consists of the static block reward and rewards for 529 // included uncles. The coinbase of each uncle block is also rewarded. 530 // TODO (karalabe): Move the chain maker into this package and make this private! 531 func AccumulateRewards(config *params.ChainConfig, state *state.StateDB, header *types.Header, uncles []*types.Header) { 532 // Select the correct block reward based on chain progression 533 blockReward := frontierBlockReward 534 if config.IsByzantium(header.Number) { 535 blockReward = byzantiumBlockReward 536 } 537 538 if config.IsEIP998(header.Number){ 539 blockReward = eip998BlockReward 540 } 541 // Accumulate the rewards for the miner and any included uncles 542 reward := new(big.Int).Set(blockReward) 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 state.AddBalance(header.Coinbase, reward) 555 }