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