gitee.com/liu-zhao234568/cntest@v1.0.0/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 "gitee.com/liu-zhao234568/cntest/accounts" 31 "gitee.com/liu-zhao234568/cntest/common" 32 "gitee.com/liu-zhao234568/cntest/common/hexutil" 33 "gitee.com/liu-zhao234568/cntest/consensus" 34 "gitee.com/liu-zhao234568/cntest/consensus/misc" 35 "gitee.com/liu-zhao234568/cntest/core/state" 36 "gitee.com/liu-zhao234568/cntest/core/types" 37 "gitee.com/liu-zhao234568/cntest/crypto" 38 "gitee.com/liu-zhao234568/cntest/ethdb" 39 "gitee.com/liu-zhao234568/cntest/log" 40 "gitee.com/liu-zhao234568/cntest/params" 41 "gitee.com/liu-zhao234568/cntest/rlp" 42 "gitee.com/liu-zhao234568/cntest/rpc" 43 "gitee.com/liu-zhao234568/cntest/trie" 44 lru "github.com/hashicorp/golang-lru" 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 wiggleTime = 500 * time.Millisecond // Random delay (per signer) to allow concurrent signers 54 ) 55 56 // Clique proof-of-authority protocol constants. 57 var ( 58 epochLength = uint64(30000) // Default number of blocks after which to checkpoint and reset the pending votes 59 60 extraVanity = 32 // Fixed number of extra-data prefix bytes reserved for signer vanity 61 extraSeal = crypto.SignatureLength // Fixed number of extra-data suffix bytes reserved for signer seal 62 63 nonceAuthVote = hexutil.MustDecode("0xffffffffffffffff") // Magic nonce number to vote on adding a new signer 64 nonceDropVote = hexutil.MustDecode("0x0000000000000000") // Magic nonce number to vote on removing a signer. 65 66 uncleHash = types.CalcUncleHash(nil) // Always Keccak256(RLP([])) as uncles are meaningless outside of PoW. 67 68 diffInTurn = big.NewInt(2) // Block difficulty for in-turn signatures 69 diffNoTurn = big.NewInt(1) // Block difficulty for out-of-turn signatures 70 ) 71 72 // Various error messages to mark blocks invalid. These should be private to 73 // prevent engine specific errors from being referenced in the remainder of the 74 // codebase, inherently breaking if the engine is swapped out. Please put common 75 // error types into the consensus package. 76 var ( 77 // errUnknownBlock is returned when the list of signers is requested for a block 78 // that is not part of the local blockchain. 79 errUnknownBlock = errors.New("unknown block") 80 81 // errInvalidCheckpointBeneficiary is returned if a checkpoint/epoch transition 82 // block has a beneficiary set to non-zeroes. 83 errInvalidCheckpointBeneficiary = errors.New("beneficiary in checkpoint block non-zero") 84 85 // errInvalidVote is returned if a nonce value is something else that the two 86 // allowed constants of 0x00..0 or 0xff..f. 87 errInvalidVote = errors.New("vote nonce not 0x00..0 or 0xff..f") 88 89 // errInvalidCheckpointVote is returned if a checkpoint/epoch transition block 90 // has a vote nonce set to non-zeroes. 91 errInvalidCheckpointVote = errors.New("vote nonce in checkpoint block non-zero") 92 93 // errMissingVanity is returned if a block's extra-data section is shorter than 94 // 32 bytes, which is required to store the signer vanity. 95 errMissingVanity = errors.New("extra-data 32 byte vanity prefix missing") 96 97 // errMissingSignature is returned if a block's extra-data section doesn't seem 98 // to contain a 65 byte secp256k1 signature. 99 errMissingSignature = errors.New("extra-data 65 byte signature suffix missing") 100 101 // errExtraSigners is returned if non-checkpoint block contain signer data in 102 // their extra-data fields. 103 errExtraSigners = errors.New("non-checkpoint block contains extra signer list") 104 105 // errInvalidCheckpointSigners is returned if a checkpoint block contains an 106 // invalid list of signers (i.e. non divisible by 20 bytes). 107 errInvalidCheckpointSigners = errors.New("invalid signer list on checkpoint block") 108 109 // errMismatchingCheckpointSigners is returned if a checkpoint block contains a 110 // list of signers different than the one the local node calculated. 111 errMismatchingCheckpointSigners = errors.New("mismatching signer list on checkpoint block") 112 113 // errInvalidMixDigest is returned if a block's mix digest is non-zero. 114 errInvalidMixDigest = errors.New("non-zero mix digest") 115 116 // errInvalidUncleHash is returned if a block contains an non-empty uncle list. 117 errInvalidUncleHash = errors.New("non empty uncle hash") 118 119 // errInvalidDifficulty is returned if the difficulty of a block neither 1 or 2. 120 errInvalidDifficulty = errors.New("invalid difficulty") 121 122 // errWrongDifficulty is returned if the difficulty of a block doesn't match the 123 // turn of the signer. 124 errWrongDifficulty = errors.New("wrong difficulty") 125 126 // errInvalidTimestamp is returned if the timestamp of a block is lower than 127 // the previous block's timestamp + the minimum block period. 128 errInvalidTimestamp = errors.New("invalid timestamp") 129 130 // errInvalidVotingChain is returned if an authorization list is attempted to 131 // be modified via out-of-range or non-contiguous headers. 132 errInvalidVotingChain = errors.New("invalid voting chain") 133 134 // errUnauthorizedSigner is returned if a header is signed by a non-authorized entity. 135 errUnauthorizedSigner = errors.New("unauthorized signer") 136 137 // errRecentlySigned is returned if a header is signed by an authorized entity 138 // that already signed a header recently, thus is temporarily not allowed to. 139 errRecentlySigned = errors.New("recently signed") 140 ) 141 142 // SignerFn hashes and signs the data to be signed by a backing account. 143 type SignerFn func(signer accounts.Account, mimeType string, message []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.ChainHeaderReader, 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.ChainHeaderReader, 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.ChainHeaderReader, header *types.Header, parents []*types.Header) error { 247 if header.Number == nil { 248 return errUnknownBlock 249 } 250 number := header.Number.Uint64() 251 252 // Don't waste time checking blocks from the future 253 if header.Time > uint64(time.Now().Unix()) { 254 return consensus.ErrFutureBlock 255 } 256 // Checkpoint blocks need to enforce zero beneficiary 257 checkpoint := (number % c.config.Epoch) == 0 258 if checkpoint && header.Coinbase != (common.Address{}) { 259 return errInvalidCheckpointBeneficiary 260 } 261 // Nonces must be 0x00..0 or 0xff..f, zeroes enforced on checkpoints 262 if !bytes.Equal(header.Nonce[:], nonceAuthVote) && !bytes.Equal(header.Nonce[:], nonceDropVote) { 263 return errInvalidVote 264 } 265 if checkpoint && !bytes.Equal(header.Nonce[:], nonceDropVote) { 266 return errInvalidCheckpointVote 267 } 268 // Check that the extra-data contains both the vanity and signature 269 if len(header.Extra) < extraVanity { 270 return errMissingVanity 271 } 272 if len(header.Extra) < extraVanity+extraSeal { 273 return errMissingSignature 274 } 275 // Ensure that the extra-data contains a signer list on checkpoint, but none otherwise 276 signersBytes := len(header.Extra) - extraVanity - extraSeal 277 if !checkpoint && signersBytes != 0 { 278 return errExtraSigners 279 } 280 if checkpoint && signersBytes%common.AddressLength != 0 { 281 return errInvalidCheckpointSigners 282 } 283 // Ensure that the mix digest is zero as we don't have fork protection currently 284 if header.MixDigest != (common.Hash{}) { 285 return errInvalidMixDigest 286 } 287 // Ensure that the block doesn't contain any uncles which are meaningless in PoA 288 if header.UncleHash != uncleHash { 289 return errInvalidUncleHash 290 } 291 // Ensure that the block's difficulty is meaningful (may not be correct at this point) 292 if number > 0 { 293 if header.Difficulty == nil || (header.Difficulty.Cmp(diffInTurn) != 0 && header.Difficulty.Cmp(diffNoTurn) != 0) { 294 return errInvalidDifficulty 295 } 296 } 297 // Verify that the gas limit is <= 2^63-1 298 cap := uint64(0x7fffffffffffffff) 299 if header.GasLimit > cap { 300 return fmt.Errorf("invalid gasLimit: have %v, max %v", header.GasLimit, cap) 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(chain, 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(chain consensus.ChainHeaderReader, 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 // Retrieve the snapshot needed to verify this header and cache it 470 snap, err := c.snapshot(chain, number-1, header.ParentHash, parents) 471 if err != nil { 472 return err 473 } 474 475 // Resolve the authorization key and check against signers 476 signer, err := ecrecover(header, c.signatures) 477 if err != nil { 478 return err 479 } 480 if _, ok := snap.Signers[signer]; !ok { 481 return errUnauthorizedSigner 482 } 483 for seen, recent := range snap.Recents { 484 if recent == signer { 485 // Signer is among recents, only fail if the current block doesn't shift it out 486 if limit := uint64(len(snap.Signers)/2 + 1); seen > number-limit { 487 return errRecentlySigned 488 } 489 } 490 } 491 // Ensure that the difficulty corresponds to the turn-ness of the signer 492 if !c.fakeDiff { 493 inturn := snap.inturn(header.Number.Uint64(), signer) 494 if inturn && header.Difficulty.Cmp(diffInTurn) != 0 { 495 return errWrongDifficulty 496 } 497 if !inturn && header.Difficulty.Cmp(diffNoTurn) != 0 { 498 return errWrongDifficulty 499 } 500 } 501 return nil 502 } 503 504 // Prepare implements consensus.Engine, preparing all the consensus fields of the 505 // header for running the transactions on top. 506 func (c *Clique) Prepare(chain consensus.ChainHeaderReader, header *types.Header) error { 507 // If the block isn't a checkpoint, cast a random vote (good enough for now) 508 header.Coinbase = common.Address{} 509 header.Nonce = types.BlockNonce{} 510 511 number := header.Number.Uint64() 512 // Assemble the voting snapshot to check which votes make sense 513 snap, err := c.snapshot(chain, number-1, header.ParentHash, nil) 514 if err != nil { 515 return err 516 } 517 if number%c.config.Epoch != 0 { 518 c.lock.RLock() 519 520 // Gather all the proposals that make sense voting on 521 addresses := make([]common.Address, 0, len(c.proposals)) 522 for address, authorize := range c.proposals { 523 if snap.validVote(address, authorize) { 524 addresses = append(addresses, address) 525 } 526 } 527 // If there's pending proposals, cast a vote on them 528 if len(addresses) > 0 { 529 header.Coinbase = addresses[rand.Intn(len(addresses))] 530 if c.proposals[header.Coinbase] { 531 copy(header.Nonce[:], nonceAuthVote) 532 } else { 533 copy(header.Nonce[:], nonceDropVote) 534 } 535 } 536 c.lock.RUnlock() 537 } 538 // Set the correct difficulty 539 header.Difficulty = calcDifficulty(snap, c.signer) 540 541 // Ensure the extra data has all its components 542 if len(header.Extra) < extraVanity { 543 header.Extra = append(header.Extra, bytes.Repeat([]byte{0x00}, extraVanity-len(header.Extra))...) 544 } 545 header.Extra = header.Extra[:extraVanity] 546 547 if number%c.config.Epoch == 0 { 548 for _, signer := range snap.signers() { 549 header.Extra = append(header.Extra, signer[:]...) 550 } 551 } 552 header.Extra = append(header.Extra, make([]byte, extraSeal)...) 553 554 // Mix digest is reserved for now, set to empty 555 header.MixDigest = common.Hash{} 556 557 // Ensure the timestamp has the correct delay 558 parent := chain.GetHeader(header.ParentHash, number-1) 559 if parent == nil { 560 return consensus.ErrUnknownAncestor 561 } 562 header.Time = parent.Time + c.config.Period 563 if header.Time < uint64(time.Now().Unix()) { 564 header.Time = uint64(time.Now().Unix()) 565 } 566 return nil 567 } 568 569 // Finalize implements consensus.Engine, ensuring no uncles are set, nor block 570 // rewards given. 571 func (c *Clique) Finalize(chain consensus.ChainHeaderReader, header *types.Header, state *state.StateDB, txs []*types.Transaction, uncles []*types.Header) { 572 // No block rewards in PoA, so the state remains as is and uncles are dropped 573 header.Root = state.IntermediateRoot(chain.Config().IsEIP158(header.Number)) 574 header.UncleHash = types.CalcUncleHash(nil) 575 } 576 577 // FinalizeAndAssemble implements consensus.Engine, ensuring no uncles are set, 578 // nor block rewards given, and returns the final block. 579 func (c *Clique) FinalizeAndAssemble(chain consensus.ChainHeaderReader, header *types.Header, state *state.StateDB, txs []*types.Transaction, uncles []*types.Header, receipts []*types.Receipt) (*types.Block, error) { 580 // Finalize block 581 c.Finalize(chain, header, state, txs, uncles) 582 583 // Assemble and return the final block for sealing 584 return types.NewBlock(header, txs, nil, receipts, trie.NewStackTrie(nil)), nil 585 } 586 587 // Authorize injects a private key into the consensus engine to mint new blocks 588 // with. 589 func (c *Clique) Authorize(signer common.Address, signFn SignerFn) { 590 c.lock.Lock() 591 defer c.lock.Unlock() 592 593 c.signer = signer 594 c.signFn = signFn 595 } 596 597 // Seal implements consensus.Engine, attempting to create a sealed block using 598 // the local signing credentials. 599 func (c *Clique) Seal(chain consensus.ChainHeaderReader, block *types.Block, results chan<- *types.Block, stop <-chan struct{}) error { 600 header := block.Header() 601 602 // Sealing the genesis block is not supported 603 number := header.Number.Uint64() 604 if number == 0 { 605 return errUnknownBlock 606 } 607 // For 0-period chains, refuse to seal empty blocks (no reward but would spin sealing) 608 if c.config.Period == 0 && len(block.Transactions()) == 0 { 609 log.Info("Sealing paused, waiting for transactions") 610 return nil 611 } 612 // Don't hold the signer fields for the entire sealing procedure 613 c.lock.RLock() 614 signer, signFn := c.signer, c.signFn 615 c.lock.RUnlock() 616 617 // Bail out if we're unauthorized to sign a block 618 snap, err := c.snapshot(chain, number-1, header.ParentHash, nil) 619 if err != nil { 620 return err 621 } 622 if _, authorized := snap.Signers[signer]; !authorized { 623 return errUnauthorizedSigner 624 } 625 // If we're amongst the recent signers, wait for the next block 626 for seen, recent := range snap.Recents { 627 if recent == signer { 628 // Signer is among recents, only wait if the current block doesn't shift it out 629 if limit := uint64(len(snap.Signers)/2 + 1); number < limit || seen > number-limit { 630 log.Info("Signed recently, must wait for others") 631 return nil 632 } 633 } 634 } 635 // Sweet, the protocol permits us to sign the block, wait for our time 636 delay := time.Unix(int64(header.Time), 0).Sub(time.Now()) // nolint: gosimple 637 if header.Difficulty.Cmp(diffNoTurn) == 0 { 638 // It's not our turn explicitly to sign, delay it a bit 639 wiggle := time.Duration(len(snap.Signers)/2+1) * wiggleTime 640 delay += time.Duration(rand.Int63n(int64(wiggle))) 641 642 log.Trace("Out-of-turn signing requested", "wiggle", common.PrettyDuration(wiggle)) 643 } 644 // Sign all the things! 645 sighash, err := signFn(accounts.Account{Address: signer}, accounts.MimetypeClique, CliqueRLP(header)) 646 if err != nil { 647 return err 648 } 649 copy(header.Extra[len(header.Extra)-extraSeal:], sighash) 650 // Wait until sealing is terminated or delay timeout. 651 log.Trace("Waiting for slot to sign and propagate", "delay", common.PrettyDuration(delay)) 652 go func() { 653 select { 654 case <-stop: 655 return 656 case <-time.After(delay): 657 } 658 659 select { 660 case results <- block.WithSeal(header): 661 default: 662 log.Warn("Sealing result is not read by miner", "sealhash", SealHash(header)) 663 } 664 }() 665 666 return nil 667 } 668 669 // CalcDifficulty is the difficulty adjustment algorithm. It returns the difficulty 670 // that a new block should have: 671 // * DIFF_NOTURN(2) if BLOCK_NUMBER % SIGNER_COUNT != SIGNER_INDEX 672 // * DIFF_INTURN(1) if BLOCK_NUMBER % SIGNER_COUNT == SIGNER_INDEX 673 func (c *Clique) CalcDifficulty(chain consensus.ChainHeaderReader, time uint64, parent *types.Header) *big.Int { 674 snap, err := c.snapshot(chain, parent.Number.Uint64(), parent.Hash(), nil) 675 if err != nil { 676 return nil 677 } 678 return calcDifficulty(snap, c.signer) 679 } 680 681 func calcDifficulty(snap *Snapshot, signer common.Address) *big.Int { 682 if snap.inturn(snap.Number+1, signer) { 683 return new(big.Int).Set(diffInTurn) 684 } 685 return new(big.Int).Set(diffNoTurn) 686 } 687 688 // SealHash returns the hash of a block prior to it being sealed. 689 func (c *Clique) SealHash(header *types.Header) common.Hash { 690 return SealHash(header) 691 } 692 693 // Close implements consensus.Engine. It's a noop for clique as there are no background threads. 694 func (c *Clique) Close() error { 695 return nil 696 } 697 698 // APIs implements consensus.Engine, returning the user facing RPC API to allow 699 // controlling the signer voting. 700 func (c *Clique) APIs(chain consensus.ChainHeaderReader) []rpc.API { 701 return []rpc.API{{ 702 Namespace: "clique", 703 Version: "1.0", 704 Service: &API{chain: chain, clique: c}, 705 Public: false, 706 }} 707 } 708 709 // SealHash returns the hash of a block prior to it being sealed. 710 func SealHash(header *types.Header) (hash common.Hash) { 711 hasher := sha3.NewLegacyKeccak256() 712 encodeSigHeader(hasher, header) 713 hasher.(crypto.KeccakState).Read(hash[:]) 714 return hash 715 } 716 717 // CliqueRLP returns the rlp bytes which needs to be signed for the proof-of-authority 718 // sealing. The RLP to sign consists of the entire header apart from the 65 byte signature 719 // contained at the end of the extra data. 720 // 721 // Note, the method requires the extra data to be at least 65 bytes, otherwise it 722 // panics. This is done to avoid accidentally using both forms (signature present 723 // or not), which could be abused to produce different hashes for the same header. 724 func CliqueRLP(header *types.Header) []byte { 725 b := new(bytes.Buffer) 726 encodeSigHeader(b, header) 727 return b.Bytes() 728 } 729 730 func encodeSigHeader(w io.Writer, header *types.Header) { 731 enc := []interface{}{ 732 header.ParentHash, 733 header.UncleHash, 734 header.Coinbase, 735 header.Root, 736 header.TxHash, 737 header.ReceiptHash, 738 header.Bloom, 739 header.Difficulty, 740 header.Number, 741 header.GasLimit, 742 header.GasUsed, 743 header.Time, 744 header.Extra[:len(header.Extra)-crypto.SignatureLength], // Yes, this will panic if extra is too short 745 header.MixDigest, 746 header.Nonce, 747 } 748 if header.BaseFee != nil { 749 enc = append(enc, header.BaseFee) 750 } 751 if err := rlp.Encode(w, enc); err != nil { 752 panic("can't encode: " + err.Error()) 753 } 754 }