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