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