github.com/ethereum/go-ethereum@v1.16.1/consensus/clique/clique.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 clique implements the proof-of-authority consensus engine. 18 package clique 19 20 import ( 21 "bytes" 22 "errors" 23 "fmt" 24 "io" 25 "math/big" 26 "math/rand" 27 "sync" 28 "time" 29 30 "github.com/ethereum/go-ethereum/common" 31 "github.com/ethereum/go-ethereum/common/hexutil" 32 "github.com/ethereum/go-ethereum/common/lru" 33 "github.com/ethereum/go-ethereum/consensus" 34 "github.com/ethereum/go-ethereum/consensus/misc" 35 "github.com/ethereum/go-ethereum/consensus/misc/eip1559" 36 "github.com/ethereum/go-ethereum/core/state" 37 "github.com/ethereum/go-ethereum/core/types" 38 "github.com/ethereum/go-ethereum/core/vm" 39 "github.com/ethereum/go-ethereum/crypto" 40 "github.com/ethereum/go-ethereum/ethdb" 41 "github.com/ethereum/go-ethereum/log" 42 "github.com/ethereum/go-ethereum/params" 43 "github.com/ethereum/go-ethereum/rlp" 44 "github.com/ethereum/go-ethereum/trie" 45 "golang.org/x/crypto/sha3" 46 ) 47 48 const ( 49 checkpointInterval = 1024 // Number of blocks after which to save the vote snapshot to the database 50 inmemorySnapshots = 128 // Number of recent vote snapshots to keep in memory 51 inmemorySignatures = 4096 // Number of recent block signatures to keep in memory 52 ) 53 54 // Clique proof-of-authority protocol constants. 55 var ( 56 epochLength = uint64(30000) // Default number of blocks after which to checkpoint and reset the pending votes 57 58 extraVanity = 32 // Fixed number of extra-data prefix bytes reserved for signer vanity 59 extraSeal = crypto.SignatureLength // Fixed number of extra-data suffix bytes reserved for signer seal 60 61 nonceAuthVote = hexutil.MustDecode("0xffffffffffffffff") // Magic nonce number to vote on adding a new signer 62 nonceDropVote = hexutil.MustDecode("0x0000000000000000") // Magic nonce number to vote on removing a signer. 63 64 uncleHash = types.CalcUncleHash(nil) // Always Keccak256(RLP([])) as uncles are meaningless outside of PoW. 65 66 diffInTurn = big.NewInt(2) // Block difficulty for in-turn signatures 67 diffNoTurn = big.NewInt(1) // Block difficulty for out-of-turn signatures 68 ) 69 70 // Various error messages to mark blocks invalid. These should be private to 71 // prevent engine specific errors from being referenced in the remainder of the 72 // codebase, inherently breaking if the engine is swapped out. Please put common 73 // error types into the consensus package. 74 var ( 75 // errUnknownBlock is returned when the list of signers is requested for a block 76 // that is not part of the local blockchain. 77 errUnknownBlock = errors.New("unknown block") 78 79 // errInvalidCheckpointBeneficiary is returned if a checkpoint/epoch transition 80 // block has a beneficiary set to non-zeroes. 81 errInvalidCheckpointBeneficiary = errors.New("beneficiary in checkpoint block non-zero") 82 83 // errInvalidVote is returned if a nonce value is something else that the two 84 // allowed constants of 0x00..0 or 0xff..f. 85 errInvalidVote = errors.New("vote nonce not 0x00..0 or 0xff..f") 86 87 // errInvalidCheckpointVote is returned if a checkpoint/epoch transition block 88 // has a vote nonce set to non-zeroes. 89 errInvalidCheckpointVote = errors.New("vote nonce in checkpoint block non-zero") 90 91 // errMissingVanity is returned if a block's extra-data section is shorter than 92 // 32 bytes, which is required to store the signer vanity. 93 errMissingVanity = errors.New("extra-data 32 byte vanity prefix missing") 94 95 // errMissingSignature is returned if a block's extra-data section doesn't seem 96 // to contain a 65 byte secp256k1 signature. 97 errMissingSignature = errors.New("extra-data 65 byte signature suffix missing") 98 99 // errExtraSigners is returned if non-checkpoint block contain signer data in 100 // their extra-data fields. 101 errExtraSigners = errors.New("non-checkpoint block contains extra signer list") 102 103 // errInvalidCheckpointSigners is returned if a checkpoint block contains an 104 // invalid list of signers (i.e. non divisible by 20 bytes). 105 errInvalidCheckpointSigners = errors.New("invalid signer list on checkpoint block") 106 107 // errMismatchingCheckpointSigners is returned if a checkpoint block contains a 108 // list of signers different than the one the local node calculated. 109 errMismatchingCheckpointSigners = errors.New("mismatching signer list on checkpoint block") 110 111 // errInvalidMixDigest is returned if a block's mix digest is non-zero. 112 errInvalidMixDigest = errors.New("non-zero mix digest") 113 114 // errInvalidUncleHash is returned if a block contains an non-empty uncle list. 115 errInvalidUncleHash = errors.New("non empty uncle hash") 116 117 // errInvalidDifficulty is returned if the difficulty of a block neither 1 or 2. 118 errInvalidDifficulty = errors.New("invalid difficulty") 119 120 // errWrongDifficulty is returned if the difficulty of a block doesn't match the 121 // turn of the signer. 122 errWrongDifficulty = errors.New("wrong difficulty") 123 124 // errInvalidTimestamp is returned if the timestamp of a block is lower than 125 // the previous block's timestamp + the minimum block period. 126 errInvalidTimestamp = errors.New("invalid timestamp") 127 128 // errInvalidVotingChain is returned if an authorization list is attempted to 129 // be modified via out-of-range or non-contiguous headers. 130 errInvalidVotingChain = errors.New("invalid voting chain") 131 132 // errUnauthorizedSigner is returned if a header is signed by a non-authorized entity. 133 errUnauthorizedSigner = errors.New("unauthorized signer") 134 135 // errRecentlySigned is returned if a header is signed by an authorized entity 136 // that already signed a header recently, thus is temporarily not allowed to. 137 errRecentlySigned = errors.New("recently signed") 138 ) 139 140 // ecrecover extracts the Ethereum account address from a signed header. 141 func ecrecover(header *types.Header, sigcache *sigLRU) (common.Address, error) { 142 // If the signature's already cached, return that 143 hash := header.Hash() 144 if address, known := sigcache.Get(hash); known { 145 return address, nil 146 } 147 // Retrieve the signature from the header extra-data 148 if len(header.Extra) < extraSeal { 149 return common.Address{}, errMissingSignature 150 } 151 signature := header.Extra[len(header.Extra)-extraSeal:] 152 153 // Recover the public key and the Ethereum address 154 pubkey, err := crypto.Ecrecover(SealHash(header).Bytes(), signature) 155 if err != nil { 156 return common.Address{}, err 157 } 158 var signer common.Address 159 copy(signer[:], crypto.Keccak256(pubkey[1:])[12:]) 160 161 sigcache.Add(hash, signer) 162 return signer, nil 163 } 164 165 // Clique is the proof-of-authority consensus engine proposed to support the 166 // Ethereum testnet following the Ropsten attacks. 167 type Clique struct { 168 config *params.CliqueConfig // Consensus engine configuration parameters 169 db ethdb.Database // Database to store and retrieve snapshot checkpoints 170 171 recents *lru.Cache[common.Hash, *Snapshot] // Snapshots for recent block to speed up reorgs 172 signatures *sigLRU // Signatures of recent blocks to speed up mining 173 174 proposals map[common.Address]bool // Current list of proposals we are pushing 175 176 signer common.Address // Ethereum address of the signing key 177 lock sync.RWMutex // Protects the signer and proposals fields 178 179 // The fields below are for testing only 180 fakeDiff bool // Skip difficulty verifications 181 } 182 183 // New creates a Clique proof-of-authority consensus engine with the initial 184 // signers set to the ones provided by the user. 185 func New(config *params.CliqueConfig, db ethdb.Database) *Clique { 186 // Set any missing consensus parameters to their defaults 187 conf := *config 188 if conf.Epoch == 0 { 189 conf.Epoch = epochLength 190 } 191 // Allocate the snapshot caches and create the engine 192 recents := lru.NewCache[common.Hash, *Snapshot](inmemorySnapshots) 193 signatures := lru.NewCache[common.Hash, common.Address](inmemorySignatures) 194 195 return &Clique{ 196 config: &conf, 197 db: db, 198 recents: recents, 199 signatures: signatures, 200 proposals: make(map[common.Address]bool), 201 } 202 } 203 204 // Author implements consensus.Engine, returning the Ethereum address recovered 205 // from the signature in the header's extra-data section. 206 func (c *Clique) Author(header *types.Header) (common.Address, error) { 207 return ecrecover(header, c.signatures) 208 } 209 210 // VerifyHeader checks whether a header conforms to the consensus rules. 211 func (c *Clique) VerifyHeader(chain consensus.ChainHeaderReader, header *types.Header) error { 212 return c.verifyHeader(chain, header, nil) 213 } 214 215 // VerifyHeaders is similar to VerifyHeader, but verifies a batch of headers. The 216 // method returns a quit channel to abort the operations and a results channel to 217 // retrieve the async verifications (the order is that of the input slice). 218 func (c *Clique) VerifyHeaders(chain consensus.ChainHeaderReader, headers []*types.Header) (chan<- struct{}, <-chan error) { 219 abort := make(chan struct{}) 220 results := make(chan error, len(headers)) 221 222 go func() { 223 for i, header := range headers { 224 err := c.verifyHeader(chain, header, headers[:i]) 225 226 select { 227 case <-abort: 228 return 229 case results <- err: 230 } 231 } 232 }() 233 return abort, results 234 } 235 236 // verifyHeader checks whether a header conforms to the consensus rules.The 237 // caller may optionally pass in a batch of parents (ascending order) to avoid 238 // looking those up from the database. This is useful for concurrently verifying 239 // a batch of new headers. 240 func (c *Clique) verifyHeader(chain consensus.ChainHeaderReader, header *types.Header, parents []*types.Header) error { 241 if header.Number == nil { 242 return errUnknownBlock 243 } 244 number := header.Number.Uint64() 245 246 // Don't waste time checking blocks from the future 247 if header.Time > uint64(time.Now().Unix()) { 248 return consensus.ErrFutureBlock 249 } 250 // Checkpoint blocks need to enforce zero beneficiary 251 checkpoint := (number % c.config.Epoch) == 0 252 if checkpoint && header.Coinbase != (common.Address{}) { 253 return errInvalidCheckpointBeneficiary 254 } 255 // Nonces must be 0x00..0 or 0xff..f, zeroes enforced on checkpoints 256 if !bytes.Equal(header.Nonce[:], nonceAuthVote) && !bytes.Equal(header.Nonce[:], nonceDropVote) { 257 return errInvalidVote 258 } 259 if checkpoint && !bytes.Equal(header.Nonce[:], nonceDropVote) { 260 return errInvalidCheckpointVote 261 } 262 // Check that the extra-data contains both the vanity and signature 263 if len(header.Extra) < extraVanity { 264 return errMissingVanity 265 } 266 if len(header.Extra) < extraVanity+extraSeal { 267 return errMissingSignature 268 } 269 // Ensure that the extra-data contains a signer list on checkpoint, but none otherwise 270 signersBytes := len(header.Extra) - extraVanity - extraSeal 271 if !checkpoint && signersBytes != 0 { 272 return errExtraSigners 273 } 274 if checkpoint && signersBytes%common.AddressLength != 0 { 275 return errInvalidCheckpointSigners 276 } 277 // Ensure that the mix digest is zero as we don't have fork protection currently 278 if header.MixDigest != (common.Hash{}) { 279 return errInvalidMixDigest 280 } 281 // Ensure that the block doesn't contain any uncles which are meaningless in PoA 282 if header.UncleHash != uncleHash { 283 return errInvalidUncleHash 284 } 285 // Ensure that the block's difficulty is meaningful (may not be correct at this point) 286 if number > 0 { 287 if header.Difficulty == nil || (header.Difficulty.Cmp(diffInTurn) != 0 && header.Difficulty.Cmp(diffNoTurn) != 0) { 288 return errInvalidDifficulty 289 } 290 } 291 // Verify that the gas limit is <= 2^63-1 292 if header.GasLimit > params.MaxGasLimit { 293 return fmt.Errorf("invalid gasLimit: have %v, max %v", header.GasLimit, params.MaxGasLimit) 294 } 295 if chain.Config().IsShanghai(header.Number, header.Time) { 296 return errors.New("clique does not support shanghai fork") 297 } 298 // Verify the non-existence of withdrawalsHash. 299 if header.WithdrawalsHash != nil { 300 return fmt.Errorf("invalid withdrawalsHash: have %x, expected nil", header.WithdrawalsHash) 301 } 302 if chain.Config().IsCancun(header.Number, header.Time) { 303 return errors.New("clique does not support cancun fork") 304 } 305 // Verify the non-existence of cancun-specific header fields 306 switch { 307 case header.ExcessBlobGas != nil: 308 return fmt.Errorf("invalid excessBlobGas: have %d, expected nil", header.ExcessBlobGas) 309 case header.BlobGasUsed != nil: 310 return fmt.Errorf("invalid blobGasUsed: have %d, expected nil", header.BlobGasUsed) 311 case header.ParentBeaconRoot != nil: 312 return fmt.Errorf("invalid parentBeaconRoot, have %#x, expected nil", header.ParentBeaconRoot) 313 } 314 // All basic checks passed, verify cascading fields 315 return c.verifyCascadingFields(chain, header, parents) 316 } 317 318 // verifyCascadingFields verifies all the header fields that are not standalone, 319 // rather depend on a batch of previous headers. The caller may optionally pass 320 // in a batch of parents (ascending order) to avoid looking those up from the 321 // database. This is useful for concurrently verifying a batch of new headers. 322 func (c *Clique) verifyCascadingFields(chain consensus.ChainHeaderReader, header *types.Header, parents []*types.Header) error { 323 // The genesis block is the always valid dead-end 324 number := header.Number.Uint64() 325 if number == 0 { 326 return nil 327 } 328 // Ensure that the block's timestamp isn't too close to its parent 329 var parent *types.Header 330 if len(parents) > 0 { 331 parent = parents[len(parents)-1] 332 } else { 333 parent = chain.GetHeader(header.ParentHash, number-1) 334 } 335 if parent == nil || parent.Number.Uint64() != number-1 || parent.Hash() != header.ParentHash { 336 return consensus.ErrUnknownAncestor 337 } 338 if parent.Time+c.config.Period > header.Time { 339 return errInvalidTimestamp 340 } 341 // Verify that the gasUsed is <= gasLimit 342 if header.GasUsed > header.GasLimit { 343 return fmt.Errorf("invalid gasUsed: have %d, gasLimit %d", header.GasUsed, header.GasLimit) 344 } 345 if !chain.Config().IsLondon(header.Number) { 346 // Verify BaseFee not present before EIP-1559 fork. 347 if header.BaseFee != nil { 348 return fmt.Errorf("invalid baseFee before fork: have %d, want <nil>", header.BaseFee) 349 } 350 if err := misc.VerifyGaslimit(parent.GasLimit, header.GasLimit); err != nil { 351 return err 352 } 353 } else if err := eip1559.VerifyEIP1559Header(chain.Config(), parent, header); err != nil { 354 // Verify the header's EIP-1559 attributes. 355 return err 356 } 357 // Retrieve the snapshot needed to verify this header and cache it 358 snap, err := c.snapshot(chain, number-1, header.ParentHash, parents) 359 if err != nil { 360 return err 361 } 362 // If the block is a checkpoint block, verify the signer list 363 if number%c.config.Epoch == 0 { 364 signers := make([]byte, len(snap.Signers)*common.AddressLength) 365 for i, signer := range snap.signers() { 366 copy(signers[i*common.AddressLength:], signer[:]) 367 } 368 extraSuffix := len(header.Extra) - extraSeal 369 if !bytes.Equal(header.Extra[extraVanity:extraSuffix], signers) { 370 return errMismatchingCheckpointSigners 371 } 372 } 373 // All basic checks passed, verify the seal and return 374 return c.verifySeal(snap, header, parents) 375 } 376 377 // snapshot retrieves the authorization snapshot at a given point in time. 378 func (c *Clique) snapshot(chain consensus.ChainHeaderReader, number uint64, hash common.Hash, parents []*types.Header) (*Snapshot, error) { 379 // Search for a snapshot in memory or on disk for checkpoints 380 var ( 381 headers []*types.Header 382 snap *Snapshot 383 ) 384 for snap == nil { 385 // If an in-memory snapshot was found, use that 386 if s, ok := c.recents.Get(hash); ok { 387 snap = s 388 break 389 } 390 // If an on-disk checkpoint snapshot can be found, use that 391 if number%checkpointInterval == 0 { 392 if s, err := loadSnapshot(c.config, c.signatures, c.db, hash); err == nil { 393 log.Trace("Loaded voting snapshot from disk", "number", number, "hash", hash) 394 snap = s 395 break 396 } 397 } 398 // If we're at the genesis, snapshot the initial state. Alternatively if we're 399 // at a checkpoint block without a parent (light client CHT), or we have piled 400 // up more headers than allowed to be reorged (chain reinit from a freezer), 401 // consider the checkpoint trusted and snapshot it. 402 if number == 0 || (number%c.config.Epoch == 0 && (len(headers) > params.FullImmutabilityThreshold || chain.GetHeaderByNumber(number-1) == nil)) { 403 checkpoint := chain.GetHeaderByNumber(number) 404 if checkpoint != nil { 405 hash := checkpoint.Hash() 406 407 signers := make([]common.Address, (len(checkpoint.Extra)-extraVanity-extraSeal)/common.AddressLength) 408 for i := 0; i < len(signers); i++ { 409 copy(signers[i][:], checkpoint.Extra[extraVanity+i*common.AddressLength:]) 410 } 411 snap = newSnapshot(c.config, c.signatures, number, hash, signers) 412 if err := snap.store(c.db); err != nil { 413 return nil, err 414 } 415 log.Info("Stored checkpoint snapshot to disk", "number", number, "hash", hash) 416 break 417 } 418 } 419 // No snapshot for this header, gather the header and move backward 420 var header *types.Header 421 if len(parents) > 0 { 422 // If we have explicit parents, pick from there (enforced) 423 header = parents[len(parents)-1] 424 if header.Hash() != hash || header.Number.Uint64() != number { 425 return nil, consensus.ErrUnknownAncestor 426 } 427 parents = parents[:len(parents)-1] 428 } else { 429 // No explicit parents (or no more left), reach out to the database 430 header = chain.GetHeader(hash, number) 431 if header == nil { 432 return nil, consensus.ErrUnknownAncestor 433 } 434 } 435 headers = append(headers, header) 436 number, hash = number-1, header.ParentHash 437 } 438 // Previous snapshot found, apply any pending headers on top of it 439 for i := 0; i < len(headers)/2; i++ { 440 headers[i], headers[len(headers)-1-i] = headers[len(headers)-1-i], headers[i] 441 } 442 snap, err := snap.apply(headers) 443 if err != nil { 444 return nil, err 445 } 446 c.recents.Add(snap.Hash, snap) 447 448 // If we've generated a new checkpoint snapshot, save to disk 449 if snap.Number%checkpointInterval == 0 && len(headers) > 0 { 450 if err = snap.store(c.db); err != nil { 451 return nil, err 452 } 453 log.Trace("Stored voting snapshot to disk", "number", snap.Number, "hash", snap.Hash) 454 } 455 return snap, err 456 } 457 458 // VerifyUncles implements consensus.Engine, always returning an error for any 459 // uncles as this consensus mechanism doesn't permit uncles. 460 func (c *Clique) VerifyUncles(chain consensus.ChainReader, block *types.Block) error { 461 if len(block.Uncles()) > 0 { 462 return errors.New("uncles not allowed") 463 } 464 return nil 465 } 466 467 // verifySeal checks whether the signature contained in the header satisfies the 468 // consensus protocol requirements. The method accepts an optional list of parent 469 // headers that aren't yet part of the local blockchain to generate the snapshots 470 // from. 471 func (c *Clique) verifySeal(snap *Snapshot, header *types.Header, parents []*types.Header) error { 472 // Verifying the genesis block is not supported 473 number := header.Number.Uint64() 474 if number == 0 { 475 return errUnknownBlock 476 } 477 // Resolve the authorization key and check against signers 478 signer, err := ecrecover(header, c.signatures) 479 if err != nil { 480 return err 481 } 482 if _, ok := snap.Signers[signer]; !ok { 483 return errUnauthorizedSigner 484 } 485 for seen, recent := range snap.Recents { 486 if recent == signer { 487 // Signer is among recents, only fail if the current block doesn't shift it out 488 if limit := uint64(len(snap.Signers)/2 + 1); seen > number-limit { 489 return errRecentlySigned 490 } 491 } 492 } 493 // Ensure that the difficulty corresponds to the turn-ness of the signer 494 if !c.fakeDiff { 495 inturn := snap.inturn(header.Number.Uint64(), signer) 496 if inturn && header.Difficulty.Cmp(diffInTurn) != 0 { 497 return errWrongDifficulty 498 } 499 if !inturn && header.Difficulty.Cmp(diffNoTurn) != 0 { 500 return errWrongDifficulty 501 } 502 } 503 return nil 504 } 505 506 // Prepare implements consensus.Engine, preparing all the consensus fields of the 507 // header for running the transactions on top. 508 func (c *Clique) Prepare(chain consensus.ChainHeaderReader, header *types.Header) error { 509 // If the block isn't a checkpoint, cast a random vote (good enough for now) 510 header.Coinbase = common.Address{} 511 header.Nonce = types.BlockNonce{} 512 513 number := header.Number.Uint64() 514 // Assemble the voting snapshot to check which votes make sense 515 snap, err := c.snapshot(chain, number-1, header.ParentHash, nil) 516 if err != nil { 517 return err 518 } 519 c.lock.RLock() 520 if number%c.config.Epoch != 0 { 521 // Gather all the proposals that make sense voting on 522 addresses := make([]common.Address, 0, len(c.proposals)) 523 for address, authorize := range c.proposals { 524 if snap.validVote(address, authorize) { 525 addresses = append(addresses, address) 526 } 527 } 528 // If there's pending proposals, cast a vote on them 529 if len(addresses) > 0 { 530 header.Coinbase = addresses[rand.Intn(len(addresses))] 531 if c.proposals[header.Coinbase] { 532 copy(header.Nonce[:], nonceAuthVote) 533 } else { 534 copy(header.Nonce[:], nonceDropVote) 535 } 536 } 537 } 538 539 // Copy signer protected by mutex to avoid race condition 540 signer := c.signer 541 c.lock.RUnlock() 542 543 // Set the correct difficulty 544 header.Difficulty = calcDifficulty(snap, signer) 545 546 // Ensure the extra data has all its components 547 if len(header.Extra) < extraVanity { 548 header.Extra = append(header.Extra, bytes.Repeat([]byte{0x00}, extraVanity-len(header.Extra))...) 549 } 550 header.Extra = header.Extra[:extraVanity] 551 552 if number%c.config.Epoch == 0 { 553 for _, signer := range snap.signers() { 554 header.Extra = append(header.Extra, signer[:]...) 555 } 556 } 557 header.Extra = append(header.Extra, make([]byte, extraSeal)...) 558 559 // Mix digest is reserved for now, set to empty 560 header.MixDigest = common.Hash{} 561 562 // Ensure the timestamp has the correct delay 563 parent := chain.GetHeader(header.ParentHash, number-1) 564 if parent == nil { 565 return consensus.ErrUnknownAncestor 566 } 567 header.Time = parent.Time + c.config.Period 568 if header.Time < uint64(time.Now().Unix()) { 569 header.Time = uint64(time.Now().Unix()) 570 } 571 return nil 572 } 573 574 // Finalize implements consensus.Engine. There is no post-transaction 575 // consensus rules in clique, do nothing here. 576 func (c *Clique) Finalize(chain consensus.ChainHeaderReader, header *types.Header, state vm.StateDB, body *types.Body) { 577 // No block rewards in PoA, so the state remains as is 578 } 579 580 // FinalizeAndAssemble implements consensus.Engine, ensuring no uncles are set, 581 // nor block rewards given, and returns the final block. 582 func (c *Clique) FinalizeAndAssemble(chain consensus.ChainHeaderReader, header *types.Header, state *state.StateDB, body *types.Body, receipts []*types.Receipt) (*types.Block, error) { 583 if len(body.Withdrawals) > 0 { 584 return nil, errors.New("clique does not support withdrawals") 585 } 586 // Finalize block 587 c.Finalize(chain, header, state, body) 588 589 // Assign the final state root to header. 590 header.Root = state.IntermediateRoot(chain.Config().IsEIP158(header.Number)) 591 592 // Assemble and return the final block for sealing. 593 return types.NewBlock(header, &types.Body{Transactions: body.Transactions}, receipts, trie.NewStackTrie(nil)), nil 594 } 595 596 // Authorize injects a private key into the consensus engine to mint new blocks 597 // with. 598 func (c *Clique) Authorize(signer common.Address) { 599 c.lock.Lock() 600 defer c.lock.Unlock() 601 602 c.signer = signer 603 } 604 605 // Seal implements consensus.Engine, attempting to create a sealed block using 606 // the local signing credentials. 607 func (c *Clique) Seal(chain consensus.ChainHeaderReader, block *types.Block, results chan<- *types.Block, stop <-chan struct{}) error { 608 panic("clique (poa) sealing not supported any more") 609 } 610 611 // CalcDifficulty is the difficulty adjustment algorithm. It returns the difficulty 612 // that a new block should have: 613 // * DIFF_NOTURN(2) if BLOCK_NUMBER % SIGNER_COUNT != SIGNER_INDEX 614 // * DIFF_INTURN(1) if BLOCK_NUMBER % SIGNER_COUNT == SIGNER_INDEX 615 func (c *Clique) CalcDifficulty(chain consensus.ChainHeaderReader, time uint64, parent *types.Header) *big.Int { 616 snap, err := c.snapshot(chain, parent.Number.Uint64(), parent.Hash(), nil) 617 if err != nil { 618 return nil 619 } 620 c.lock.RLock() 621 signer := c.signer 622 c.lock.RUnlock() 623 return calcDifficulty(snap, signer) 624 } 625 626 func calcDifficulty(snap *Snapshot, signer common.Address) *big.Int { 627 if snap.inturn(snap.Number+1, signer) { 628 return new(big.Int).Set(diffInTurn) 629 } 630 return new(big.Int).Set(diffNoTurn) 631 } 632 633 // SealHash returns the hash of a block prior to it being sealed. 634 func (c *Clique) SealHash(header *types.Header) common.Hash { 635 return SealHash(header) 636 } 637 638 // Close implements consensus.Engine. It's a noop for clique as there are no background threads. 639 func (c *Clique) Close() error { 640 return nil 641 } 642 643 // SealHash returns the hash of a block prior to it being sealed. 644 func SealHash(header *types.Header) (hash common.Hash) { 645 hasher := sha3.NewLegacyKeccak256() 646 encodeSigHeader(hasher, header) 647 hasher.(crypto.KeccakState).Read(hash[:]) 648 return hash 649 } 650 651 // CliqueRLP returns the rlp bytes which needs to be signed for the proof-of-authority 652 // sealing. The RLP to sign consists of the entire header apart from the 65 byte signature 653 // contained at the end of the extra data. 654 // 655 // Note, the method requires the extra data to be at least 65 bytes, otherwise it 656 // panics. This is done to avoid accidentally using both forms (signature present 657 // or not), which could be abused to produce different hashes for the same header. 658 func CliqueRLP(header *types.Header) []byte { 659 b := new(bytes.Buffer) 660 encodeSigHeader(b, header) 661 return b.Bytes() 662 } 663 664 func encodeSigHeader(w io.Writer, header *types.Header) { 665 enc := []interface{}{ 666 header.ParentHash, 667 header.UncleHash, 668 header.Coinbase, 669 header.Root, 670 header.TxHash, 671 header.ReceiptHash, 672 header.Bloom, 673 header.Difficulty, 674 header.Number, 675 header.GasLimit, 676 header.GasUsed, 677 header.Time, 678 header.Extra[:len(header.Extra)-crypto.SignatureLength], // Yes, this will panic if extra is too short 679 header.MixDigest, 680 header.Nonce, 681 } 682 if header.BaseFee != nil { 683 enc = append(enc, header.BaseFee) 684 } 685 if header.WithdrawalsHash != nil { 686 panic("unexpected withdrawal hash value in clique") 687 } 688 if header.ExcessBlobGas != nil { 689 panic("unexpected excess blob gas value in clique") 690 } 691 if header.BlobGasUsed != nil { 692 panic("unexpected blob gas used value in clique") 693 } 694 if header.ParentBeaconRoot != nil { 695 panic("unexpected parent beacon root value in clique") 696 } 697 if err := rlp.Encode(w, enc); err != nil { 698 panic("can't encode: " + err.Error()) 699 } 700 }