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