github.com/ebakus/go-ebakus@v1.0.5-0.20200520105415-dbccef9ec421/consensus/ethash/consensus.go (about) 1 // Copyright 2019 The ebakus/go-ebakus Authors 2 // This file is part of the ebakus/go-ebakus library. 3 // 4 // The ebakus/go-ebakus 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 ebakus/go-ebakus 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 ebakus/go-ebakus library. If not, see <http://www.gnu.org/licenses/>. 16 17 package ethash 18 19 import ( 20 "errors" 21 "fmt" 22 "math/big" 23 "runtime" 24 "time" 25 26 "github.com/ebakus/go-ebakus/common" 27 "github.com/ebakus/go-ebakus/common/math" 28 "github.com/ebakus/go-ebakus/consensus" 29 "github.com/ebakus/go-ebakus/consensus/misc" 30 "github.com/ebakus/go-ebakus/core/state" 31 "github.com/ebakus/go-ebakus/core/types" 32 "github.com/ebakus/go-ebakus/params" 33 "github.com/ebakus/go-ebakus/rlp" 34 "github.com/ebakus/ebakusdb" 35 "golang.org/x/crypto/sha3" 36 ) 37 38 // Ethash proof-of-work protocol constants. 39 var ( 40 FrontierBlockReward = big.NewInt(5e+18) // Block reward in wei for successfully mining a block 41 ByzantiumBlockReward = big.NewInt(3e+18) // Block reward in wei for successfully mining a block upward from Byzantium 42 ConstantinopleBlockReward = big.NewInt(2e+18) // Block reward in wei for successfully mining a block upward from Constantinople 43 allowedFutureBlockTime = 15 * time.Second // Max time from current time allowed for blocks, before they're considered future blocks 44 45 // calcDifficultyByzantium is the difficulty adjustment algorithm. It returns 46 // the difficulty that a new block should have when created at time given the 47 // parent block's time and difficulty. The calculation uses the Byzantium rules. 48 // Specification EIP-649: https://eips.ethereum.org/EIPS/eip-649 49 calcDifficultyByzantium = makeDifficultyCalculator(big.NewInt(3000000)) 50 ) 51 52 // Various error messages to mark blocks invalid. These should be private to 53 // prevent engine specific errors from being referenced in the remainder of the 54 // codebase, inherently breaking if the engine is swapped out. Please put common 55 // error types into the consensus package. 56 var ( 57 errZeroBlockTime = errors.New("timestamp equals parent's") 58 errTooManyUncles = errors.New("too many uncles") 59 errDuplicateUncle = errors.New("duplicate uncle") 60 errUncleIsAncestor = errors.New("uncle is ancestor") 61 errDanglingUncle = errors.New("uncle's parent is not ancestor") 62 errInvalidDifficulty = errors.New("non-positive difficulty") 63 errInvalidMixDigest = errors.New("invalid mix digest") 64 errInvalidPoW = errors.New("invalid proof-of-work") 65 errOutOfRange = errors.New("block cache overflow") 66 ) 67 68 // Author implements consensus.Engine, returning the header's coinbase as the 69 // proof-of-work verified author of the block. 70 func (ethash *Ethash) Author(header *types.Header) (common.Address, error) { 71 return common.Address{}, nil 72 } 73 74 // VerifyHeader checks whether a header conforms to the consensus rules of the 75 // stock Ebakus ethash engine. 76 func (ethash *Ethash) VerifyHeader(chain consensus.ChainReader, header *types.Header, seal bool) error { 77 // If we're running a full engine faking, accept any input as valid 78 if ethash.config.PowMode == ModeFullFake { 79 return nil 80 } 81 // Short circuit if the header is known, or its parent not 82 number := header.Number.Uint64() 83 if chain.GetHeader(header.Hash(), number) != nil { 84 return nil 85 } 86 parent := chain.GetHeader(header.ParentHash, number-1) 87 if parent == nil { 88 return consensus.ErrUnknownAncestor 89 } 90 // Sanity checks passed, do a proper verification 91 return ethash.verifyHeader(chain, header, parent, false, seal) 92 } 93 94 // VerifyHeaders is similar to VerifyHeader, but verifies a batch of headers 95 // concurrently. The method returns a quit channel to abort the operations and 96 // a results channel to retrieve the async verifications. 97 func (ethash *Ethash) VerifyHeaders(chain consensus.ChainReader, headers []*types.Header, seals []bool) (chan<- struct{}, <-chan error) { 98 // If we're running a full engine faking, accept any input as valid 99 if ethash.config.PowMode == ModeFullFake || len(headers) == 0 { 100 abort, results := make(chan struct{}), make(chan error, len(headers)) 101 for i := 0; i < len(headers); i++ { 102 results <- nil 103 } 104 return abort, results 105 } 106 107 // Spawn as many workers as allowed threads 108 workers := runtime.GOMAXPROCS(0) 109 if len(headers) < workers { 110 workers = len(headers) 111 } 112 113 // Create a task channel and spawn the verifiers 114 var ( 115 inputs = make(chan int) 116 done = make(chan int, workers) 117 errors = make([]error, len(headers)) 118 abort = make(chan struct{}) 119 ) 120 for i := 0; i < workers; i++ { 121 go func() { 122 for index := range inputs { 123 errors[index] = ethash.verifyHeaderWorker(chain, headers, seals, index) 124 done <- index 125 } 126 }() 127 } 128 129 errorsOut := make(chan error, len(headers)) 130 go func() { 131 defer close(inputs) 132 var ( 133 in, out = 0, 0 134 checked = make([]bool, len(headers)) 135 inputs = inputs 136 ) 137 for { 138 select { 139 case inputs <- in: 140 if in++; in == len(headers) { 141 // Reached end of headers. Stop sending to workers. 142 inputs = nil 143 } 144 case index := <-done: 145 for checked[index] = true; checked[out]; out++ { 146 errorsOut <- errors[out] 147 if out == len(headers)-1 { 148 return 149 } 150 } 151 case <-abort: 152 return 153 } 154 } 155 }() 156 return abort, errorsOut 157 } 158 159 func (ethash *Ethash) verifyHeaderWorker(chain consensus.ChainReader, headers []*types.Header, seals []bool, index int) error { 160 var parent *types.Header 161 if index == 0 { 162 parent = chain.GetHeader(headers[0].ParentHash, headers[0].Number.Uint64()-1) 163 } else if headers[index-1].Hash() == headers[index].ParentHash { 164 parent = headers[index-1] 165 } 166 if parent == nil { 167 return consensus.ErrUnknownAncestor 168 } 169 if chain.GetHeader(headers[index].Hash(), headers[index].Number.Uint64()) != nil { 170 return nil // known block 171 } 172 return ethash.verifyHeader(chain, headers[index], parent, false, seals[index]) 173 } 174 175 // VerifyBlock verifies that the given block's uncles conform to the consensus 176 // rules of the stock Ebakus ethash engine. 177 func (ethash *Ethash) VerifyBlock(chain consensus.ChainReader, block *types.Block) error { 178 // If we're running a full engine faking, accept any input as valid 179 if ethash.config.PowMode == ModeFullFake { 180 return nil 181 } 182 183 // Gather the ancestors 184 ancestors := 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 parent, number = ancestor.ParentHash(), number-1 194 } 195 ancestors[block.Hash()] = block.Header() 196 197 return nil 198 } 199 200 // verifyHeader checks whether a header conforms to the consensus rules of the 201 // stock Ebakus ethash engine. 202 // See YP section 4.3.4. "Block Header Validity" 203 func (ethash *Ethash) verifyHeader(chain consensus.ChainReader, header, parent *types.Header, uncle bool, seal bool) error { 204 // Ensure that the header's extra-data section is of a reasonable size 205 // Verify the header's timestamp 206 if !uncle { 207 if header.Time > uint64(time.Now().Add(allowedFutureBlockTime).Unix()) { 208 return consensus.ErrFutureBlock 209 } 210 } 211 if header.Time <= parent.Time { 212 return errZeroBlockTime 213 } 214 215 // Verify that the gas limit is <= 2^63-1 216 cap := uint64(0x7fffffffffffffff) 217 if header.GasLimit > cap { 218 return fmt.Errorf("invalid gasLimit: have %v, max %v", header.GasLimit, cap) 219 } 220 // Verify that the gasUsed is <= gasLimit 221 if header.GasUsed > header.GasLimit { 222 return fmt.Errorf("invalid gasUsed: have %d, gasLimit %d", header.GasUsed, header.GasLimit) 223 } 224 225 // Verify that the gas limit remains within allowed bounds 226 diff := int64(parent.GasLimit) - int64(header.GasLimit) 227 if diff < 0 { 228 diff *= -1 229 } 230 limit := parent.GasLimit / params.GasLimitBoundDivisor 231 232 if uint64(diff) >= limit || header.GasLimit < params.MinGasLimit { 233 return fmt.Errorf("invalid gas limit: have %d, want %d += %d", header.GasLimit, parent.GasLimit, limit) 234 } 235 // Verify that the block number is parent's +1 236 if diff := new(big.Int).Sub(header.Number, parent.Number); diff.Cmp(big.NewInt(1)) != 0 { 237 return consensus.ErrInvalidNumber 238 } 239 // Verify the engine specific seal securing the block 240 if seal { 241 if err := ethash.VerifySeal(chain, header); err != nil { 242 return err 243 } 244 } 245 if err := misc.VerifyForkHashes(chain.Config(), header, uncle); err != nil { 246 return err 247 } 248 return nil 249 } 250 251 // CalcDifficulty is the difficulty adjustment algorithm. It returns 252 // the difficulty that a new block should have when created at time 253 // given the parent block's time and difficulty. 254 func (ethash *Ethash) CalcDifficulty(chain consensus.ChainReader, time uint64, parent *types.Header) *big.Int { 255 return CalcDifficulty(chain.Config(), time, parent) 256 } 257 258 // CalcDifficulty is the difficulty adjustment algorithm. It returns 259 // the difficulty that a new block should have when created at time 260 // given the parent block's time and difficulty. 261 func CalcDifficulty(config *params.ChainConfig, time uint64, parent *types.Header) *big.Int { 262 return calcDifficultyByzantium(time, parent) 263 } 264 265 // Some weird constants to avoid constant memory allocs for them. 266 var ( 267 expDiffPeriod = big.NewInt(100000) 268 big1 = big.NewInt(1) 269 big2 = big.NewInt(2) 270 big9 = big.NewInt(9) 271 big10 = big.NewInt(10) 272 bigMinus99 = big.NewInt(-99) 273 ) 274 275 // makeDifficultyCalculator creates a difficultyCalculator with the given bomb-delay. 276 // the difficulty is calculated with Byzantium rules, which differs from Homestead in 277 // how uncles affect the calculation 278 func makeDifficultyCalculator(bombDelay *big.Int) func(time uint64, parent *types.Header) *big.Int { 279 // Note, the calculations below looks at the parent number, which is 1 below 280 // the block number. Thus we remove one from the delay given 281 bombDelayFromParent := new(big.Int).Sub(bombDelay, big1) 282 return func(time uint64, parent *types.Header) *big.Int { 283 // https://github.com/ethereum/EIPs/issues/100. 284 // algorithm: 285 // diff = (parent_diff + 286 // (parent_diff / 2048 * max((2 if len(parent.uncles) else 1) - ((timestamp - parent.timestamp) // 9), -99)) 287 // ) + 2^(periodCount - 2) 288 289 bigTime := new(big.Int).SetUint64(time) 290 bigParentTime := new(big.Int).SetUint64(parent.Time) 291 292 // holds intermediate values to make the algo easier to read & audit 293 x := new(big.Int) 294 y := new(big.Int) 295 296 // (2 if len(parent_uncles) else 1) - (block_timestamp - parent_timestamp) // 9 297 x.Sub(bigTime, bigParentTime) 298 x.Div(x, big9) 299 x.Sub(big1, x) 300 301 // max((2 if len(parent_uncles) else 1) - (block_timestamp - parent_timestamp) // 9, -99) 302 if x.Cmp(bigMinus99) < 0 { 303 x.Set(bigMinus99) 304 } 305 // parent_diff + (parent_diff / 2048 * max((2 if len(parent.uncles) else 1) - ((timestamp - parent.timestamp) // 9), -99)) 306 // y.Div(parent.Difficulty, params.DifficultyBoundDivisor) 307 // x.Mul(y, x) 308 // x.Add(parent.Difficulty, x) 309 310 // minimum difficulty can ever be (before exponential factor) 311 if x.Cmp(params.MinimumDifficulty) < 0 { 312 x.Set(params.MinimumDifficulty) 313 } 314 // calculate a fake block number for the ice-age delay 315 // Specification: https://eips.ethereum.org/EIPS/eip-1234 316 fakeBlockNumber := new(big.Int) 317 if parent.Number.Cmp(bombDelayFromParent) >= 0 { 318 fakeBlockNumber = fakeBlockNumber.Sub(parent.Number, bombDelayFromParent) 319 } 320 // for the exponential factor 321 periodCount := fakeBlockNumber 322 periodCount.Div(periodCount, expDiffPeriod) 323 324 // the exponential factor, commonly referred to as "the bomb" 325 // diff = diff + 2^(periodCount - 2) 326 if periodCount.Cmp(big1) > 0 { 327 y.Sub(periodCount, big2) 328 y.Exp(big2, y, nil) 329 x.Add(x, y) 330 } 331 return x 332 } 333 } 334 335 // calcDifficultyHomestead is the difficulty adjustment algorithm. It returns 336 // the difficulty that a new block should have when created at time given the 337 // parent block's time and difficulty. The calculation uses the Homestead rules. 338 func calcDifficultyHomestead(time uint64, parent *types.Header) *big.Int { 339 // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-2.md 340 // algorithm: 341 // diff = (parent_diff + 342 // (parent_diff / 2048 * max(1 - (block_timestamp - parent_timestamp) // 10, -99)) 343 // ) + 2^(periodCount - 2) 344 345 bigTime := new(big.Int).SetUint64(time) 346 bigParentTime := new(big.Int).SetUint64(parent.Time) 347 348 // holds intermediate values to make the algo easier to read & audit 349 x := new(big.Int) 350 y := new(big.Int) 351 352 // 1 - (block_timestamp - parent_timestamp) // 10 353 x.Sub(bigTime, bigParentTime) 354 x.Div(x, big10) 355 x.Sub(big1, x) 356 357 // max(1 - (block_timestamp - parent_timestamp) // 10, -99) 358 if x.Cmp(bigMinus99) < 0 { 359 x.Set(bigMinus99) 360 } 361 // (parent_diff + parent_diff // 2048 * max(1 - (block_timestamp - parent_timestamp) // 10, -99)) 362 //y.Div(parent.Difficulty, params.DifficultyBoundDivisor) 363 //x.Mul(y, x) 364 //x.Add(parent.Difficulty, x) 365 366 // minimum difficulty can ever be (before exponential factor) 367 if x.Cmp(params.MinimumDifficulty) < 0 { 368 x.Set(params.MinimumDifficulty) 369 } 370 // for the exponential factor 371 periodCount := new(big.Int).Add(parent.Number, big1) 372 periodCount.Div(periodCount, expDiffPeriod) 373 374 // the exponential factor, commonly referred to as "the bomb" 375 // diff = diff + 2^(periodCount - 2) 376 if periodCount.Cmp(big1) > 0 { 377 y.Sub(periodCount, big2) 378 y.Exp(big2, y, nil) 379 x.Add(x, y) 380 } 381 return x 382 } 383 384 // calcDifficultyFrontier is the difficulty adjustment algorithm. It returns the 385 // difficulty that a new block should have when created at time given the parent 386 // block's time and difficulty. The calculation uses the Frontier rules. 387 func calcDifficultyFrontier(time uint64, parent *types.Header) *big.Int { 388 diff := new(big.Int) 389 //adjust := new(big.Int).Div(parent.Difficulty, params.DifficultyBoundDivisor) 390 bigTime := new(big.Int) 391 bigParentTime := new(big.Int) 392 393 bigTime.SetUint64(time) 394 bigParentTime.SetUint64(parent.Time) 395 396 if diff.Cmp(params.MinimumDifficulty) < 0 { 397 diff.Set(params.MinimumDifficulty) 398 } 399 400 periodCount := new(big.Int).Add(parent.Number, big1) 401 periodCount.Div(periodCount, expDiffPeriod) 402 if periodCount.Cmp(big1) > 0 { 403 // diff = diff + 2^(periodCount - 2) 404 expDiff := periodCount.Sub(periodCount, big2) 405 expDiff.Exp(big2, expDiff, nil) 406 diff.Add(diff, expDiff) 407 diff = math.BigMax(diff, params.MinimumDifficulty) 408 } 409 return diff 410 } 411 412 // VerifySeal implements consensus.Engine, checking whether the given block satisfies 413 // the PoW difficulty requirements. 414 func (ethash *Ethash) VerifySeal(chain consensus.ChainReader, header *types.Header) error { 415 return ethash.verifySeal(chain, header, false) 416 } 417 418 // verifySeal checks whether a block satisfies the PoW difficulty requirements, 419 // either using the usual ethash cache for it, or alternatively using a full DAG 420 // to make remote mining fast. 421 func (ethash *Ethash) verifySeal(chain consensus.ChainReader, header *types.Header, fulldag bool) error { 422 // If we're running a fake PoW, accept any seal as valid 423 if ethash.config.PowMode == ModeFake || ethash.config.PowMode == ModeFullFake { 424 time.Sleep(ethash.fakeDelay) 425 if ethash.fakeFail == header.Number.Uint64() { 426 return errInvalidPoW 427 } 428 return nil 429 } 430 // If we're running a shared PoW, delegate verification to it 431 if ethash.shared != nil { 432 return ethash.shared.verifySeal(chain, header, fulldag) 433 } 434 // Sanity check that the block number is below the lookup table size (60M blocks) 435 number := header.Number.Uint64() 436 if number/epochLength >= maxEpoch { 437 // Go < 1.7 cannot calculate new cache/dataset sizes (no fast prime check) 438 return errOutOfRange 439 } 440 441 cache := ethash.cache(number) 442 runtime.KeepAlive(cache) 443 444 return nil 445 } 446 447 // Prepare implements consensus.Engine, initializing the difficulty field of a 448 // header to conform to the ethash protocol. The changes are done inline. 449 func (ethash *Ethash) Prepare(chain consensus.ChainReader, stop <-chan struct{}) (*types.Block, *types.Header, error) { 450 return nil, nil, nil 451 } 452 453 // Finalize implements consensus.Engine, accumulating the block and uncle rewards, 454 // setting the final state on the header 455 func (ethash *Ethash) Finalize(chain consensus.ChainReader, header *types.Header, state *state.StateDB, ebakusState *ebakusdb.Snapshot, coinbase common.Address, txs []*types.Transaction) { 456 // Accumulate any block and uncle rewards and commit the final state root 457 accumulateRewards(chain.Config(), state, header) 458 header.Root = state.IntermediateRoot(chain.Config().IsEIP158(header.Number)) 459 } 460 461 // FinalizeAndAssemble implements consensus.Engine, accumulating the block and 462 // uncle rewards, setting the final state and assembling the block. 463 func (ethash *Ethash) FinalizeAndAssemble(chain consensus.ChainReader, header *types.Header, state *state.StateDB, ebakusState *ebakusdb.Snapshot, coinbase common.Address, txs []*types.Transaction, receipts []*types.Receipt) (*types.Block, error) { 464 // Accumulate any block and uncle rewards and commit the final state root 465 accumulateRewards(chain.Config(), state, header) 466 header.Root = state.IntermediateRoot(chain.Config().IsEIP158(header.Number)) 467 468 // Header seems complete, assemble into a block and return 469 return types.NewBlock(header, txs, receipts, nil), nil 470 } 471 472 // SealHash returns the hash of a block prior to it being sealed. 473 func (ethash *Ethash) SealHash(header *types.Header) (hash common.Hash) { 474 hasher := sha3.NewLegacyKeccak256() 475 476 rlp.Encode(hasher, []interface{}{ 477 header.ParentHash, 478 header.Root, 479 header.TxHash, 480 header.ReceiptHash, 481 header.Bloom, 482 header.Number, 483 header.GasLimit, 484 header.GasUsed, 485 header.Time, 486 }) 487 hasher.Sum(hash[:0]) 488 return hash 489 } 490 491 // Some weird constants to avoid constant memory allocs for them. 492 var ( 493 big8 = big.NewInt(8) 494 big32 = big.NewInt(32) 495 ) 496 497 // AccumulateRewards credits the coinbase of the given block with the mining 498 // reward. The total reward consists of the static block reward and rewards for 499 // included uncles. The coinbase of each uncle block is also rewarded. 500 func accumulateRewards(config *params.ChainConfig, state *state.StateDB, header *types.Header) { 501 /* 502 // Select the correct block reward based on chain progression 503 blockReward := FrontierBlockReward 504 if config.IsByzantium(header.Number) { 505 blockReward = ByzantiumBlockReward 506 } 507 if config.IsConstantinople(header.Number) { 508 blockReward = ConstantinopleBlockReward 509 } 510 // Accumulate the rewards for the miner and any included uncles 511 reward := new(big.Int).Set(blockReward) 512 513 state.AddBalance(header.Coinbase, reward) 514 */ 515 }