github.com/ethereumproject/go-ethereum@v5.5.2+incompatible/core/block_validator.go (about) 1 // Copyright 2015 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 core 18 19 import ( 20 "fmt" 21 "math/big" 22 "time" 23 24 "github.com/ethereumproject/go-ethereum/common" 25 "github.com/ethereumproject/go-ethereum/core/state" 26 "github.com/ethereumproject/go-ethereum/core/types" 27 "github.com/ethereumproject/go-ethereum/logger/glog" 28 "github.com/ethereumproject/go-ethereum/pow" 29 "gopkg.in/fatih/set.v0" 30 ) 31 32 var ( 33 DurationLimit = big.NewInt(13) // The decision boundary on the blocktime duration used to determine whether difficulty should go up or not. 34 ExpDiffPeriod = big.NewInt(100000) 35 MinimumDifficulty = big.NewInt(131072) 36 MinGasLimit = big.NewInt(5000) // Minimum the gas limit may ever be. 37 TargetGasLimit = big.NewInt(4712388) // The artificial target 38 DifficultyBoundDivisor = big.NewInt(2048) // The bound divisor of the difficulty, used in the update calculations. 39 GasLimitBoundDivisor = big.NewInt(1024) // The bound divisor of the gas limit, used in update calculations. 40 ) 41 42 var ( 43 big10 = big.NewInt(10) 44 bigMinus99 = big.NewInt(-99) 45 ) 46 47 // Difficulty allows passing configurable options to a given difficulty algorithm. 48 type DifficultyConfig struct { 49 Name string `json:"name"` 50 Options map[string]interface{} `json:"options"` 51 } 52 53 // BlockValidator is responsible for validating block headers, uncles and 54 // processed state. 55 // 56 // BlockValidator implements Validator. 57 type BlockValidator struct { 58 config *ChainConfig // Chain configuration options 59 bc *BlockChain // Canonical block chain 60 Pow pow.PoW // Proof of work used for validating 61 } 62 63 // NewBlockValidator returns a new block validator which is safe for re-use 64 func NewBlockValidator(config *ChainConfig, blockchain *BlockChain, pow pow.PoW) *BlockValidator { 65 validator := &BlockValidator{ 66 config: config, 67 Pow: pow, 68 bc: blockchain, 69 } 70 return validator 71 } 72 73 // ValidateBlock validates the given block's header and uncles and verifies the 74 // the block header's transaction and uncle roots. 75 // 76 // ValidateBlock does not validate the header's pow. The pow work validated 77 // separately so we can process them in parallel. 78 // 79 // ValidateBlock also validates and makes sure that any previous state (or present) 80 // state that might or might not be present is checked to make sure that fast 81 // sync has done it's job proper. This prevents the block validator form accepting 82 // false positives where a header is present but the state is not. 83 func (v *BlockValidator) ValidateBlock(block *types.Block) error { 84 if v.bc.HasBlock(block.Hash()) { 85 if _, err := state.New(block.Root(), state.NewDatabase(v.bc.chainDb)); err == nil { 86 return &KnownBlockError{block.Number(), block.Hash()} 87 } 88 } 89 parent := v.bc.GetBlock(block.ParentHash()) 90 if parent == nil { 91 return ParentError(block.ParentHash()) 92 } 93 if _, err := state.New(parent.Root(), state.NewDatabase(v.bc.chainDb)); err != nil { 94 return ParentError(block.ParentHash()) 95 } 96 97 header := block.Header() 98 // validate the block header 99 if err := ValidateHeader(v.config, v.Pow, header, parent.Header(), false, false); err != nil { 100 return err 101 } 102 // verify the uncles are correctly rewarded 103 if err := v.VerifyUncles(block, parent); err != nil { 104 return err 105 } 106 107 // Verify UncleHash before running other uncle validations 108 unclesSha := types.CalcUncleHash(block.Uncles()) 109 if unclesSha != header.UncleHash { 110 return fmt.Errorf("invalid uncles root hash. received=%x calculated=%x", header.UncleHash, unclesSha) 111 } 112 113 // The transactions Trie's root (R = (Tr [[i, RLP(T1)], [i, RLP(T2)], ... [n, RLP(Tn)]])) 114 // can be used by light clients to make sure they've received the correct Txs 115 txSha := types.DeriveSha(block.Transactions()) 116 if txSha != header.TxHash { 117 return fmt.Errorf("invalid transaction root hash. received=%x calculated=%x", header.TxHash, txSha) 118 } 119 120 return nil 121 } 122 123 // ValidateState validates the various changes that happen after a state 124 // transition, such as amount of used gas, the receipt roots and the state root 125 // itself. ValidateState returns a database batch if the validation was a success 126 // otherwise nil and an error is returned. 127 func (v *BlockValidator) ValidateState(block, parent *types.Block, statedb *state.StateDB, receipts types.Receipts, usedGas *big.Int) (err error) { 128 header := block.Header() 129 if block.GasUsed().Cmp(usedGas) != 0 { 130 return validateError(fmt.Sprintf("gas used error (%v / %v)", block.GasUsed(), usedGas)) 131 } 132 // Validate the received block's bloom with the one derived from the generated receipts. 133 // For valid blocks this should always validate to true. 134 rbloom := types.CreateBloom(receipts) 135 if rbloom != header.Bloom { 136 return fmt.Errorf("unable to replicate block's bloom=%x vs calculated bloom=%x", header.Bloom, rbloom) 137 } 138 // Tre receipt Trie's root (R = (Tr [[H1, R1], ... [Hn, R1]])) 139 receiptSha := types.DeriveSha(receipts) 140 if receiptSha != header.ReceiptHash { 141 return fmt.Errorf("invalid receipt root hash. received=%x calculated=%x", header.ReceiptHash, receiptSha) 142 } 143 // Validate the state root against the received state root and throw 144 // an error if they don't match. 145 if root := statedb.IntermediateRoot(false); header.Root != root { 146 return fmt.Errorf("invalid merkle root: header=%x computed=%x", header.Root, root) 147 } 148 return nil 149 } 150 151 // VerifyUncles verifies the given block's uncles and applies the Ethereum 152 // consensus rules to the various block headers included; it will return an 153 // error if any of the included uncle headers were invalid. It returns an error 154 // if the validation failed. 155 func (v *BlockValidator) VerifyUncles(block, parent *types.Block) error { 156 // validate that there at most 2 uncles included in this block 157 if len(block.Uncles()) > 2 { 158 return validateError(fmt.Sprintf("Block can only contain maximum 2 uncles (contained %d)", len(block.Uncles()))) 159 } 160 161 uncles := set.New() 162 ancestors := make(map[common.Hash]*types.Block) 163 for _, ancestor := range v.bc.GetBlocksFromHash(block.ParentHash(), 7) { 164 ancestors[ancestor.Hash()] = ancestor 165 // Include ancestors uncles in the uncle set. Uncles must be unique. 166 for _, uncle := range ancestor.Uncles() { 167 uncles.Add(uncle.Hash()) 168 } 169 } 170 ancestors[block.Hash()] = block 171 uncles.Add(block.Hash()) 172 173 for i, uncle := range block.Uncles() { 174 hash := uncle.Hash() 175 if uncles.Has(hash) { 176 // Error not unique 177 return UncleError("uncle[%d](%x) not unique", i, hash[:4]) 178 } 179 uncles.Add(hash) 180 181 if ancestors[hash] != nil { 182 branch := fmt.Sprintf(" O - %x\n |\n", block.Hash()) 183 for h := range ancestors { 184 branch += fmt.Sprintf(" O - %x\n |\n", h) 185 } 186 glog.Infoln(branch) 187 return UncleError("uncle[%d](%x) is ancestor", i, hash[:4]) 188 } 189 190 if ancestors[uncle.ParentHash] == nil || uncle.ParentHash == parent.Hash() { 191 return UncleError("uncle[%d](%x)'s parent is not ancestor (%x)", i, hash[:4], uncle.ParentHash[0:4]) 192 } 193 194 if err := ValidateHeader(v.config, v.Pow, uncle, ancestors[uncle.ParentHash].Header(), true, true); err != nil { 195 return validateError(fmt.Sprintf("uncle[%d](%x) header invalid: %v", i, hash[:4], err)) 196 } 197 } 198 199 return nil 200 } 201 202 // ValidateHeader validates the given header and, depending on the pow arg, 203 // checks the proof of work of the given header. Returns an error if the 204 // validation failed. 205 func (v *BlockValidator) ValidateHeader(header, parent *types.Header, checkPow bool) error { 206 // Short circuit if the parent is missing. 207 if parent == nil { 208 return ParentError(header.ParentHash) 209 } 210 // Short circuit if the header's already known or its parent missing 211 if v.bc.HasHeader(header.Hash()) { 212 return nil 213 } 214 return ValidateHeader(v.config, v.Pow, header, parent, checkPow, false) 215 } 216 217 // Validates a header. Returns an error if the header is invalid. 218 // 219 // See YP section 4.3.4. "Block Header Validity" 220 func ValidateHeader(config *ChainConfig, pow pow.PoW, header *types.Header, parent *types.Header, checkPow, uncle bool) error { 221 if len(header.Extra) > types.HeaderExtraMax { 222 return fmt.Errorf("extra data size %d exceeds limit of %d", len(header.Extra), types.HeaderExtraMax) 223 } 224 225 if uncle { 226 if header.Time.Cmp(common.MaxBig) == 1 { 227 return BlockTSTooBigErr 228 } 229 } else { 230 if header.Time.Cmp(big.NewInt(time.Now().Unix())) == 1 { 231 return BlockFutureErr 232 } 233 } 234 if header.Time.Cmp(parent.Time) != 1 { 235 return BlockEqualTSErr 236 } 237 238 expd := CalcDifficulty(config, header.Time.Uint64(), parent.Time.Uint64(), parent.Number, parent.Difficulty) 239 if expd.Cmp(header.Difficulty) != 0 { 240 return fmt.Errorf("Difficulty check failed for header %v != %v at %v", header.Difficulty, expd, header.Number) 241 } 242 243 a := new(big.Int).Set(parent.GasLimit) 244 a = a.Sub(a, header.GasLimit) 245 a.Abs(a) 246 b := new(big.Int).Set(parent.GasLimit) 247 b = b.Div(b, GasLimitBoundDivisor) 248 if !(a.Cmp(b) < 0) || (header.GasLimit.Cmp(MinGasLimit) == -1) { 249 return fmt.Errorf("GasLimit check failed for header %v (%v > %v)", header.GasLimit, a, b) 250 } 251 252 num := new(big.Int).Set(parent.Number) 253 num.Sub(header.Number, num) 254 if num.Cmp(big.NewInt(1)) != 0 { 255 return BlockNumberErr 256 } 257 258 if checkPow { 259 // Verify the nonce of the header. Return an error if it's not valid 260 if !pow.Verify(types.NewBlockWithHeader(header)) { 261 return &BlockNonceErr{header.Number, header.Hash(), header.Nonce.Uint64()} 262 } 263 } 264 // If all checks passed, validate the extra-data field for hard forks 265 return nil 266 } 267 268 // CalcDifficulty is the difficulty adjustment algorithm. It returns 269 // the difficulty that a new block should have when created at time 270 // given the parent block's time and difficulty. 271 func CalcDifficulty(config *ChainConfig, time, parentTime uint64, parentNumber, parentDiff *big.Int) *big.Int { 272 if config == nil { 273 glog.Fatalln("missing chain configuration, cannot calculate difficulty") 274 } 275 if parentDiff == nil { 276 parentDiff = big.NewInt(0) 277 } 278 num := new(big.Int).Add(parentNumber, common.Big1) // increment block number to current 279 280 f, fork, configured := config.GetFeature(num, "difficulty") 281 if !configured { 282 return calcDifficultyFrontier(time, parentTime, parentNumber, parentDiff) 283 } 284 name, ok := f.GetString("type") 285 if !ok { 286 name = "" 287 } // will fall to default panic 288 switch name { 289 case "defused": 290 return calcDifficultyDefused(time, parentTime, parentNumber, parentDiff) 291 case "ecip1010": 292 if length, ok := f.GetBigInt("length"); ok { 293 explosionBlock := big.NewInt(0).Add(fork.Block, length) 294 if num.Cmp(explosionBlock) < 0 { 295 return calcDifficultyDiehard(time, parentTime, parentDiff, 296 fork.Block) 297 } else { 298 return calcDifficultyExplosion(time, parentTime, parentNumber, parentDiff, 299 fork.Block, explosionBlock) 300 } 301 } else { 302 panic(fmt.Sprintf("Length is not set for diehard difficulty at %v", num)) 303 } 304 case "homestead": 305 return calcDifficultyHomestead(time, parentTime, parentNumber, parentDiff) 306 case "frontier": 307 return calcDifficultyFrontier(time, parentTime, parentNumber, parentDiff) 308 default: 309 panic(fmt.Sprintf("Unsupported difficulty '%v' for block: %v", name, num)) 310 } 311 } 312 313 func calcDifficultyDiehard(time, parentTime uint64, parentDiff *big.Int, diehardBlock *big.Int) *big.Int { 314 // https://github.com/ethereumproject/ECIPs/blob/master/ECIPS/ECIP-1010.md 315 // algorithm: 316 // diff = (parent_diff + 317 // (parent_diff / 2048 * max(1 - (block_timestamp - parent_timestamp) // 10, -99)) 318 // ) + 2^(fixed_diff) 319 320 bigTime := new(big.Int).SetUint64(time) 321 bigParentTime := new(big.Int).SetUint64(parentTime) 322 323 // holds intermediate values to make the algo easier to read & audit 324 x := new(big.Int) 325 y := new(big.Int) 326 327 // 1 - (block_timestamp -parent_timestamp) // 10 328 x.Sub(bigTime, bigParentTime) 329 x.Div(x, big10) 330 x.Sub(common.Big1, x) 331 332 // max(1 - (block_timestamp - parent_timestamp) // 10, -99))) 333 if x.Cmp(bigMinus99) < 0 { 334 x.Set(bigMinus99) 335 } 336 337 // (parent_diff + parent_diff // 2048 * max(1 - (block_timestamp - parent_timestamp) // 10, -99)) 338 y.Div(parentDiff, DifficultyBoundDivisor) 339 x.Mul(y, x) 340 x.Add(parentDiff, x) 341 342 // minimum difficulty can ever be (before exponential factor) 343 if x.Cmp(MinimumDifficulty) < 0 { 344 x.Set(MinimumDifficulty) 345 } 346 347 // for the exponential factor 348 fixedCount := new(big.Int).Div(diehardBlock, ExpDiffPeriod) 349 350 // the exponential factor, commonly referred to as "the bomb" 351 // diff = diff + 2^(periodCount - 2) 352 if fixedCount.Cmp(common.Big1) > 0 { 353 y.Sub(fixedCount, common.Big2) 354 y.Exp(common.Big2, y, nil) 355 x.Add(x, y) 356 } 357 358 return x 359 } 360 361 func calcDifficultyExplosion(time, parentTime uint64, parentNumber, parentDiff *big.Int, delayBlock *big.Int, continueBlock *big.Int) *big.Int { 362 // https://github.com/ethereumproject/ECIPs/blob/master/ECIPs/ECIP-1010.md 363 // algorithm: 364 // diff = (parent_diff + 365 // (parent_diff / 2048 * max(1 - (block_timestamp - parent_timestamp) // 10, -99)) 366 // ) + 2^(delayedCount - 2) 367 368 bigTime := new(big.Int).SetUint64(time) 369 bigParentTime := new(big.Int).SetUint64(parentTime) 370 371 // holds intermediate values to make the algo easier to read & audit 372 x := new(big.Int) 373 y := new(big.Int) 374 375 // 1 - (block_timestamp -parent_timestamp) // 10 376 x.Sub(bigTime, bigParentTime) 377 x.Div(x, big10) 378 x.Sub(common.Big1, x) 379 380 // max(1 - (block_timestamp - parent_timestamp) // 10, -99))) 381 if x.Cmp(bigMinus99) < 0 { 382 x.Set(bigMinus99) 383 } 384 385 // (parent_diff + parent_diff // 2048 * max(1 - (block_timestamp - parent_timestamp) // 10, -99)) 386 y.Div(parentDiff, DifficultyBoundDivisor) 387 x.Mul(y, x) 388 x.Add(parentDiff, x) 389 390 // minimum difficulty can ever be (before exponential factor) 391 if x.Cmp(MinimumDifficulty) < 0 { 392 x.Set(MinimumDifficulty) 393 } 394 395 // for the exponential factor... 396 397 delayedCount := new(big.Int).Add(parentNumber, common.Big1) 398 delayedCount.Sub(delayedCount, continueBlock) 399 delayedCount.Add(delayedCount, delayBlock) 400 delayedCount.Div(delayedCount, ExpDiffPeriod) 401 402 // the exponential factor, commonly referred to as "the bomb" 403 // diff = diff + 2^(periodCount - 2) 404 if delayedCount.Cmp(common.Big1) > 0 { 405 y.Sub(delayedCount, common.Big2) 406 y.Exp(common.Big2, y, nil) 407 x.Add(x, y) 408 } 409 410 return x 411 } 412 413 func calcDifficultyDefused(time, parentTime uint64, parentNumber, parentDiff *big.Int) *big.Int { 414 // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-2.mediawiki 415 // algorithm: 416 // diff = (parent_diff + 417 // (parent_diff / 2048 * max(1 - (block_timestamp - parent_timestamp) // 10, -99)) 418 // ) 419 420 bigTime := new(big.Int).SetUint64(time) 421 bigParentTime := new(big.Int).SetUint64(parentTime) 422 423 // holds intermediate values to make the algo easier to read & audit 424 x := new(big.Int) 425 y := new(big.Int) 426 427 // 1 - (block_timestamp -parent_timestamp) // 10 428 x.Sub(bigTime, bigParentTime) 429 x.Div(x, big10) 430 x.Sub(common.Big1, x) 431 432 // max(1 - (block_timestamp - parent_timestamp) // 10, -99))) 433 if x.Cmp(bigMinus99) < 0 { 434 x.Set(bigMinus99) 435 } 436 437 // (parent_diff + parent_diff // 2048 * max(1 - (block_timestamp - parent_timestamp) // 10, -99)) 438 y.Div(parentDiff, DifficultyBoundDivisor) 439 x.Mul(y, x) 440 x.Add(parentDiff, x) 441 442 // minimum difficulty can ever be (before exponential factor) 443 if x.Cmp(MinimumDifficulty) < 0 { 444 x.Set(MinimumDifficulty) 445 } 446 447 return x 448 } 449 450 func calcDifficultyHomestead(time, parentTime uint64, parentNumber, parentDiff *big.Int) *big.Int { 451 // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-2.mediawiki 452 // algorithm: 453 // diff = (parent_diff + 454 // (parent_diff / 2048 * max(1 - (block_timestamp - parent_timestamp) // 10, -99)) 455 // ) + 2^(periodCount - 2) 456 457 bigTime := new(big.Int).SetUint64(time) 458 bigParentTime := new(big.Int).SetUint64(parentTime) 459 460 // holds intermediate values to make the algo easier to read & audit 461 x := new(big.Int) 462 y := new(big.Int) 463 464 // 1 - (block_timestamp -parent_timestamp) // 10 465 x.Sub(bigTime, bigParentTime) 466 x.Div(x, big10) 467 x.Sub(common.Big1, x) 468 469 // max(1 - (block_timestamp - parent_timestamp) // 10, -99))) 470 if x.Cmp(bigMinus99) < 0 { 471 x.Set(bigMinus99) 472 } 473 474 // (parent_diff + parent_diff // 2048 * max(1 - (block_timestamp - parent_timestamp) // 10, -99)) 475 y.Div(parentDiff, DifficultyBoundDivisor) 476 x.Mul(y, x) 477 x.Add(parentDiff, x) 478 479 // minimum difficulty can ever be (before exponential factor) 480 if x.Cmp(MinimumDifficulty) < 0 { 481 x.Set(MinimumDifficulty) 482 } 483 484 // for the exponential factor 485 periodCount := new(big.Int).Add(parentNumber, common.Big1) 486 periodCount.Div(periodCount, ExpDiffPeriod) 487 488 // the exponential factor, commonly referred to as "the bomb" 489 // diff = diff + 2^(periodCount - 2) 490 if periodCount.Cmp(common.Big1) > 0 { 491 y.Sub(periodCount, common.Big2) 492 y.Exp(common.Big2, y, nil) 493 x.Add(x, y) 494 } 495 496 return x 497 } 498 499 func calcDifficultyFrontier(time, parentTime uint64, parentNumber, parentDiff *big.Int) *big.Int { 500 diff := new(big.Int) 501 adjust := new(big.Int).Div(parentDiff, DifficultyBoundDivisor) 502 bigTime := new(big.Int) 503 bigParentTime := new(big.Int) 504 505 bigTime.SetUint64(time) 506 bigParentTime.SetUint64(parentTime) 507 508 if bigTime.Sub(bigTime, bigParentTime).Cmp(DurationLimit) < 0 { 509 diff.Add(parentDiff, adjust) 510 } else { 511 diff.Sub(parentDiff, adjust) 512 } 513 if diff.Cmp(MinimumDifficulty) < 0 { 514 diff.Set(MinimumDifficulty) 515 } 516 517 periodCount := new(big.Int).Add(parentNumber, common.Big1) 518 periodCount.Div(periodCount, ExpDiffPeriod) 519 if periodCount.Cmp(common.Big1) > 0 { 520 // diff = diff + 2^(periodCount - 2) 521 expDiff := periodCount.Sub(periodCount, common.Big2) 522 expDiff.Exp(common.Big2, expDiff, nil) 523 diff.Add(diff, expDiff) 524 diff = common.BigMax(diff, MinimumDifficulty) 525 } 526 527 return diff 528 } 529 530 // CalcGasLimit computes the gas limit of the next block after parent. 531 // The result may be modified by the caller. 532 // This is miner strategy, not consensus protocol. 533 func CalcGasLimit(parent *types.Block) *big.Int { 534 // contrib = (parentGasUsed * 3 / 2) / 1024 535 contrib := new(big.Int).Mul(parent.GasUsed(), big.NewInt(3)) 536 contrib = contrib.Div(contrib, big.NewInt(2)) 537 contrib = contrib.Div(contrib, GasLimitBoundDivisor) 538 539 // decay = parentGasLimit / 1024 -1 540 decay := new(big.Int).Div(parent.GasLimit(), GasLimitBoundDivisor) 541 decay.Sub(decay, big.NewInt(1)) 542 543 /* 544 strategy: gasLimit of block-to-mine is set based on parent's 545 gasUsed value. if parentGasUsed > parentGasLimit * (2/3) then we 546 increase it, otherwise lower it (or leave it unchanged if it's right 547 at that usage) the amount increased/decreased depends on how far away 548 from parentGasLimit * (2/3) parentGasUsed is. 549 */ 550 gl := new(big.Int).Sub(parent.GasLimit(), decay) 551 gl = gl.Add(gl, contrib) 552 gl.Set(common.BigMax(gl, MinGasLimit)) 553 554 // however, if we're now below the target (TargetGasLimit) we increase the 555 // limit as much as we can (parentGasLimit / 1024 -1) 556 if gl.Cmp(TargetGasLimit) < 0 { 557 gl.Add(parent.GasLimit(), decay) 558 gl.Set(common.BigMin(gl, TargetGasLimit)) 559 } 560 return gl 561 }