github.com/energicryptocurrency/go-energi@v1.1.7/consensus/clique/clique.go (about) 1 // Copyright 2018 The Energi Core Authors 2 // Copyright 2017 The go-ethereum Authors 3 // This file is part of the Energi Core library. 4 // 5 // The Energi Core library is free software: you can redistribute it and/or modify 6 // it under the terms of the GNU Lesser General Public License as published by 7 // the Free Software Foundation, either version 3 of the License, or 8 // (at your option) any later version. 9 // 10 // The Energi Core library is distributed in the hope that it will be useful, 11 // but WITHOUT ANY WARRANTY; without even the implied warranty of 12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 // GNU Lesser General Public License for more details. 14 // 15 // You should have received a copy of the GNU Lesser General Public License 16 // along with the Energi Core library. If not, see <http://www.gnu.org/licenses/>. 17 18 // Package clique implements the proof-of-authority consensus engine. 19 package clique 20 21 import ( 22 "bytes" 23 "errors" 24 "math/big" 25 "math/rand" 26 "sync" 27 "time" 28 29 "github.com/energicryptocurrency/go-energi/accounts" 30 "github.com/energicryptocurrency/go-energi/common" 31 "github.com/energicryptocurrency/go-energi/common/hexutil" 32 "github.com/energicryptocurrency/go-energi/consensus" 33 "github.com/energicryptocurrency/go-energi/consensus/misc" 34 "github.com/energicryptocurrency/go-energi/core/state" 35 "github.com/energicryptocurrency/go-energi/core/types" 36 "github.com/energicryptocurrency/go-energi/crypto" 37 "github.com/energicryptocurrency/go-energi/ethdb" 38 "github.com/energicryptocurrency/go-energi/log" 39 "github.com/energicryptocurrency/go-energi/params" 40 "github.com/energicryptocurrency/go-energi/rlp" 41 "github.com/energicryptocurrency/go-energi/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 = 65 // 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 hash to be signed by a 141 // backing account. 142 type SignerFn func(accounts.Account, []byte) ([]byte, error) 143 144 // sigHash returns the hash which is used as input for the proof-of-authority 145 // signing. It is the hash of the entire header apart from the 65 byte signature 146 // contained at the end of the extra data. 147 // 148 // Note, the method requires the extra data to be at least 65 bytes, otherwise it 149 // panics. This is done to avoid accidentally using both forms (signature present 150 // or not), which could be abused to produce different hashes for the same header. 151 func sigHash(header *types.Header) (hash common.Hash) { 152 hasher := sha3.NewLegacyKeccak256() 153 154 rlp.Encode(hasher, []interface{}{ 155 header.ParentHash, 156 header.UncleHash, 157 header.Coinbase, 158 header.Root, 159 header.TxHash, 160 header.ReceiptHash, 161 header.Bloom, 162 header.Difficulty, 163 header.Number, 164 header.GasLimit, 165 header.GasUsed, 166 header.Time, 167 header.Extra[:len(header.Extra)-65], // Yes, this will panic if extra is too short 168 header.MixDigest, 169 header.Nonce, 170 }) 171 hasher.Sum(hash[:0]) 172 return hash 173 } 174 175 // ecrecover extracts the Ethereum account address from a signed header. 176 func ecrecover(header *types.Header, sigcache *lru.ARCCache) (common.Address, error) { 177 // If the signature's already cached, return that 178 hash := header.Hash() 179 if address, known := sigcache.Get(hash); known { 180 return address.(common.Address), nil 181 } 182 // Retrieve the signature from the header extra-data 183 if len(header.Extra) < extraSeal { 184 return common.Address{}, errMissingSignature 185 } 186 signature := header.Extra[len(header.Extra)-extraSeal:] 187 188 // Recover the public key and the Ethereum address 189 pubkey, err := crypto.Ecrecover(sigHash(header).Bytes(), signature) 190 if err != nil { 191 return common.Address{}, err 192 } 193 var signer common.Address 194 copy(signer[:], crypto.Keccak256(pubkey[1:])[12:]) 195 196 sigcache.Add(hash, signer) 197 return signer, nil 198 } 199 200 // Clique is the proof-of-authority consensus engine proposed to support the 201 // Ethereum testnet following the Ropsten attacks. 202 type Clique struct { 203 config *params.CliqueConfig // Consensus engine configuration parameters 204 db ethdb.Database // Database to store and retrieve snapshot checkpoints 205 206 recents *lru.ARCCache // Snapshots for recent block to speed up reorgs 207 signatures *lru.ARCCache // Signatures of recent blocks to speed up mining 208 209 proposals map[common.Address]bool // Current list of proposals we are pushing 210 211 signer common.Address // Ethereum address of the signing key 212 signFn SignerFn // Signer function to authorize hashes with 213 lock sync.RWMutex // Protects the signer fields 214 215 // The fields below are for testing only 216 fakeDiff bool // Skip difficulty verifications 217 } 218 219 // New creates a Clique proof-of-authority consensus engine with the initial 220 // signers set to the ones provided by the user. 221 func New(config *params.CliqueConfig, db ethdb.Database) *Clique { 222 // Set any missing consensus parameters to their defaults 223 conf := *config 224 if conf.Epoch == 0 { 225 conf.Epoch = epochLength 226 } 227 // Allocate the snapshot caches and create the engine 228 recents, _ := lru.NewARC(inmemorySnapshots) 229 signatures, _ := lru.NewARC(inmemorySignatures) 230 231 return &Clique{ 232 config: &conf, 233 db: db, 234 recents: recents, 235 signatures: signatures, 236 proposals: make(map[common.Address]bool), 237 } 238 } 239 240 // Author implements consensus.Engine, returning the Ethereum address recovered 241 // from the signature in the header's extra-data section. 242 func (c *Clique) Author(header *types.Header) (common.Address, error) { 243 return ecrecover(header, c.signatures) 244 } 245 246 // VerifyHeader checks whether a header conforms to the consensus rules. 247 func (c *Clique) VerifyHeader(chain consensus.ChainReader, header *types.Header, seal bool) error { 248 return c.verifyHeader(chain, header, nil) 249 } 250 251 // VerifyHeaders is similar to VerifyHeader, but verifies a batch of headers. The 252 // method returns a quit channel to abort the operations and a results channel to 253 // retrieve the async verifications (the order is that of the input slice). 254 func (c *Clique) VerifyHeaders(chain consensus.ChainReader, headers []*types.Header, seals []bool) (chan<- struct{}, <-chan error, chan<- bool) { 255 abort := make(chan struct{}) 256 results := make(chan error, len(headers)) 257 258 go func() { 259 for i, header := range headers { 260 err := c.verifyHeader(chain, header, headers[:i]) 261 262 select { 263 case <-abort: 264 return 265 case results <- err: 266 } 267 } 268 }() 269 return abort, results, nil 270 } 271 272 // verifyHeader checks whether a header conforms to the consensus rules.The 273 // caller may optionally pass in a batch of parents (ascending order) to avoid 274 // looking those up from the database. This is useful for concurrently verifying 275 // a batch of new headers. 276 func (c *Clique) verifyHeader(chain consensus.ChainReader, header *types.Header, parents []*types.Header) error { 277 if header.Number == nil { 278 return errUnknownBlock 279 } 280 number := header.Number.Uint64() 281 282 // Don't waste time checking blocks from the future 283 if header.Time > uint64(time.Now().Unix()) { 284 return consensus.ErrFutureBlock 285 } 286 // Checkpoint blocks need to enforce zero beneficiary 287 checkpoint := (number % c.config.Epoch) == 0 288 if checkpoint && header.Coinbase != (common.Address{}) { 289 return errInvalidCheckpointBeneficiary 290 } 291 // Nonces must be 0x00..0 or 0xff..f, zeroes enforced on checkpoints 292 if !bytes.Equal(header.Nonce[:], nonceAuthVote) && !bytes.Equal(header.Nonce[:], nonceDropVote) { 293 return errInvalidVote 294 } 295 if checkpoint && !bytes.Equal(header.Nonce[:], nonceDropVote) { 296 return errInvalidCheckpointVote 297 } 298 // Check that the extra-data contains both the vanity and signature 299 if len(header.Extra) < extraVanity { 300 return errMissingVanity 301 } 302 if len(header.Extra) < extraVanity+extraSeal { 303 return errMissingSignature 304 } 305 // Ensure that the extra-data contains a signer list on checkpoint, but none otherwise 306 signersBytes := len(header.Extra) - extraVanity - extraSeal 307 if !checkpoint && signersBytes != 0 { 308 return errExtraSigners 309 } 310 if checkpoint && signersBytes%common.AddressLength != 0 { 311 return errInvalidCheckpointSigners 312 } 313 // Ensure that the mix digest is zero as we don't have fork protection currently 314 if header.MixDigest != (common.Hash{}) { 315 return errInvalidMixDigest 316 } 317 // Ensure that the block doesn't contain any uncles which are meaningless in PoA 318 if header.UncleHash != uncleHash { 319 return errInvalidUncleHash 320 } 321 // Ensure that the block's difficulty is meaningful (may not be correct at this point) 322 if number > 0 { 323 if header.Difficulty == nil || (header.Difficulty.Cmp(diffInTurn) != 0 && header.Difficulty.Cmp(diffNoTurn) != 0) { 324 return errInvalidDifficulty 325 } 326 } 327 // If all checks passed, validate any special fields for hard forks 328 if err := misc.VerifyForkHashes(chain.Config(), header, false); err != nil { 329 return err 330 } 331 // All basic checks passed, verify cascading fields 332 return c.verifyCascadingFields(chain, header, parents) 333 } 334 335 // verifyCascadingFields verifies all the header fields that are not standalone, 336 // rather depend on a batch of previous headers. The caller may optionally pass 337 // in a batch of parents (ascending order) to avoid looking those up from the 338 // database. This is useful for concurrently verifying a batch of new headers. 339 func (c *Clique) verifyCascadingFields(chain consensus.ChainReader, header *types.Header, parents []*types.Header) error { 340 // The genesis block is the always valid dead-end 341 number := header.Number.Uint64() 342 if number == 0 { 343 return nil 344 } 345 // Ensure that the block's timestamp isn't too close to it's parent 346 var parent *types.Header 347 if len(parents) > 0 { 348 parent = parents[len(parents)-1] 349 } else { 350 parent = chain.GetHeader(header.ParentHash, number-1) 351 } 352 if parent == nil || parent.Number.Uint64() != number-1 || parent.Hash() != header.ParentHash { 353 return consensus.ErrUnknownAncestor 354 } 355 if parent.Time+c.config.Period > header.Time { 356 return ErrInvalidTimestamp 357 } 358 // Retrieve the snapshot needed to verify this header and cache it 359 snap, err := c.snapshot(chain, number-1, header.ParentHash, parents) 360 if err != nil { 361 return err 362 } 363 // If the block is a checkpoint block, verify the signer list 364 if number%c.config.Epoch == 0 { 365 signers := make([]byte, len(snap.Signers)*common.AddressLength) 366 for i, signer := range snap.signers() { 367 copy(signers[i*common.AddressLength:], signer[:]) 368 } 369 extraSuffix := len(header.Extra) - extraSeal 370 if !bytes.Equal(header.Extra[extraVanity:extraSuffix], signers) { 371 return errMismatchingCheckpointSigners 372 } 373 } 374 // All basic checks passed, verify the seal and return 375 return c.verifySeal(chain, header, parents) 376 } 377 378 // snapshot retrieves the authorization snapshot at a given point in time. 379 func (c *Clique) snapshot(chain consensus.ChainReader, number uint64, hash common.Hash, parents []*types.Header) (*Snapshot, error) { 380 // Search for a snapshot in memory or on disk for checkpoints 381 var ( 382 headers []*types.Header 383 snap *Snapshot 384 ) 385 for snap == nil { 386 // If an in-memory snapshot was found, use that 387 if s, ok := c.recents.Get(hash); ok { 388 snap = s.(*Snapshot) 389 break 390 } 391 // If an on-disk checkpoint snapshot can be found, use that 392 if number%checkpointInterval == 0 { 393 if s, err := loadSnapshot(c.config, c.signatures, c.db, hash); err == nil { 394 log.Trace("Loaded voting snapshot from disk", "number", number, "hash", hash) 395 snap = s 396 break 397 } 398 } 399 // If we're at an checkpoint block, make a snapshot if it's known 400 if number == 0 || (number%c.config.Epoch == 0 && chain.GetHeaderByNumber(number-1) == nil) { 401 checkpoint := chain.GetHeaderByNumber(number) 402 if checkpoint != nil { 403 hash := checkpoint.Hash() 404 405 signers := make([]common.Address, (len(checkpoint.Extra)-extraVanity-extraSeal)/common.AddressLength) 406 for i := 0; i < len(signers); i++ { 407 copy(signers[i][:], checkpoint.Extra[extraVanity+i*common.AddressLength:]) 408 } 409 snap = newSnapshot(c.config, c.signatures, number, hash, signers) 410 if err := snap.store(c.db); err != nil { 411 return nil, err 412 } 413 log.Info("Stored checkpoint snapshot to disk", "number", number, "hash", hash) 414 break 415 } 416 } 417 // No snapshot for this header, gather the header and move backward 418 var header *types.Header 419 if len(parents) > 0 { 420 // If we have explicit parents, pick from there (enforced) 421 header = parents[len(parents)-1] 422 if header.Hash() != hash || header.Number.Uint64() != number { 423 return nil, consensus.ErrUnknownAncestor 424 } 425 parents = parents[:len(parents)-1] 426 } else { 427 // No explicit parents (or no more left), reach out to the database 428 header = chain.GetHeader(hash, number) 429 if header == nil { 430 return nil, consensus.ErrUnknownAncestor 431 } 432 } 433 headers = append(headers, header) 434 number, hash = number-1, header.ParentHash 435 } 436 // Previous snapshot found, apply any pending headers on top of it 437 for i := 0; i < len(headers)/2; i++ { 438 headers[i], headers[len(headers)-1-i] = headers[len(headers)-1-i], headers[i] 439 } 440 snap, err := snap.apply(headers) 441 if err != nil { 442 return nil, err 443 } 444 c.recents.Add(snap.Hash, snap) 445 446 // If we've generated a new checkpoint snapshot, save to disk 447 if snap.Number%checkpointInterval == 0 && len(headers) > 0 { 448 if err = snap.store(c.db); err != nil { 449 return nil, err 450 } 451 log.Trace("Stored voting snapshot to disk", "number", snap.Number, "hash", snap.Hash) 452 } 453 return snap, err 454 } 455 456 // VerifyUncles implements consensus.Engine, always returning an error for any 457 // uncles as this consensus mechanism doesn't permit uncles. 458 func (c *Clique) VerifyUncles(chain consensus.ChainReader, block *types.Block) error { 459 if len(block.Uncles()) > 0 { 460 return errors.New("uncles not allowed") 461 } 462 return nil 463 } 464 465 // VerifySeal implements consensus.Engine, checking whether the signature contained 466 // in the header satisfies the consensus protocol requirements. 467 func (c *Clique) VerifySeal(chain consensus.ChainReader, header *types.Header) error { 468 return c.verifySeal(chain, header, nil) 469 } 470 471 // verifySeal checks whether the signature contained in the header satisfies the 472 // consensus protocol requirements. The method accepts an optional list of parent 473 // headers that aren't yet part of the local blockchain to generate the snapshots 474 // from. 475 func (c *Clique) verifySeal(chain consensus.ChainReader, header *types.Header, parents []*types.Header) error { 476 // Verifying the genesis block is not supported 477 number := header.Number.Uint64() 478 if number == 0 { 479 return errUnknownBlock 480 } 481 // Retrieve the snapshot needed to verify this header and cache it 482 snap, err := c.snapshot(chain, number-1, header.ParentHash, parents) 483 if err != nil { 484 return err 485 } 486 487 // Resolve the authorization key and check against signers 488 signer, err := ecrecover(header, c.signatures) 489 if err != nil { 490 return err 491 } 492 if _, ok := snap.Signers[signer]; !ok { 493 return errUnauthorizedSigner 494 } 495 for seen, recent := range snap.Recents { 496 if recent == signer { 497 // Signer is among recents, only fail if the current block doesn't shift it out 498 if limit := uint64(len(snap.Signers)/2 + 1); seen > number-limit { 499 return errRecentlySigned 500 } 501 } 502 } 503 // Ensure that the difficulty corresponds to the turn-ness of the signer 504 if !c.fakeDiff { 505 inturn := snap.inturn(header.Number.Uint64(), signer) 506 if inturn && header.Difficulty.Cmp(diffInTurn) != 0 { 507 return errWrongDifficulty 508 } 509 if !inturn && header.Difficulty.Cmp(diffNoTurn) != 0 { 510 return errWrongDifficulty 511 } 512 } 513 return nil 514 } 515 516 // Prepare implements consensus.Engine, preparing all the consensus fields of the 517 // header for running the transactions on top. 518 func (c *Clique) Prepare(chain consensus.ChainReader, header *types.Header) error { 519 // If the block isn't a checkpoint, cast a random vote (good enough for now) 520 header.Coinbase = common.Address{} 521 header.Nonce = types.BlockNonce{} 522 523 number := header.Number.Uint64() 524 // Assemble the voting snapshot to check which votes make sense 525 snap, err := c.snapshot(chain, number-1, header.ParentHash, nil) 526 if err != nil { 527 return err 528 } 529 if number%c.config.Epoch != 0 { 530 c.lock.RLock() 531 532 // Gather all the proposals that make sense voting on 533 addresses := make([]common.Address, 0, len(c.proposals)) 534 for address, authorize := range c.proposals { 535 if snap.validVote(address, authorize) { 536 addresses = append(addresses, address) 537 } 538 } 539 // If there's pending proposals, cast a vote on them 540 if len(addresses) > 0 { 541 header.Coinbase = addresses[rand.Intn(len(addresses))] 542 if c.proposals[header.Coinbase] { 543 copy(header.Nonce[:], nonceAuthVote) 544 } else { 545 copy(header.Nonce[:], nonceDropVote) 546 } 547 } 548 c.lock.RUnlock() 549 } 550 // Set the correct difficulty 551 header.Difficulty = CalcDifficulty(snap, c.signer) 552 553 // Ensure the extra data has all it's components 554 if len(header.Extra) < extraVanity { 555 header.Extra = append(header.Extra, bytes.Repeat([]byte{0x00}, extraVanity-len(header.Extra))...) 556 } 557 header.Extra = header.Extra[:extraVanity] 558 559 if number%c.config.Epoch == 0 { 560 for _, signer := range snap.signers() { 561 header.Extra = append(header.Extra, signer[:]...) 562 } 563 } 564 header.Extra = append(header.Extra, make([]byte, extraSeal)...) 565 566 // Mix digest is reserved for now, set to empty 567 header.MixDigest = common.Hash{} 568 569 // Ensure the timestamp has the correct delay 570 parent := chain.GetHeader(header.ParentHash, number-1) 571 if parent == nil { 572 return consensus.ErrUnknownAncestor 573 } 574 header.Time = parent.Time + c.config.Period 575 if header.Time < uint64(time.Now().Unix()) { 576 header.Time = uint64(time.Now().Unix()) 577 } 578 return nil 579 } 580 581 // Finalize implements consensus.Engine, ensuring no uncles are set, nor block 582 // rewards given, and returns the final block. 583 func (c *Clique) Finalize(chain consensus.ChainReader, header *types.Header, state *state.StateDB, txs []*types.Transaction, uncles []*types.Header, receipts []*types.Receipt) (*types.Block, []*types.Receipt, error) { 584 // No block rewards in PoA, so the state remains as is and uncles are dropped 585 header.Root = state.IntermediateRoot(chain.Config().IsEIP158(header.Number)) 586 header.UncleHash = types.CalcUncleHash(nil) 587 588 // Assemble and return the final block for sealing 589 return types.NewBlock(header, txs, nil, receipts), receipts, nil 590 } 591 592 // Authorize injects a private key into the consensus engine to mint new blocks 593 // with. 594 func (c *Clique) Authorize(signer common.Address, signFn SignerFn) { 595 c.lock.Lock() 596 defer c.lock.Unlock() 597 598 c.signer = signer 599 c.signFn = signFn 600 } 601 602 // Seal implements consensus.Engine, attempting to create a sealed block using 603 // the local signing credentials. 604 func (c *Clique) Seal(chain consensus.ChainReader, block *types.Block, results chan<- *consensus.SealResult, stop <-chan struct{}) error { 605 header := block.Header() 606 607 // Sealing the genesis block is not supported 608 number := header.Number.Uint64() 609 if number == 0 { 610 return errUnknownBlock 611 } 612 // For 0-period chains, refuse to seal empty blocks (no reward but would spin sealing) 613 if c.config.Period == 0 && len(block.Transactions()) == 0 { 614 log.Info("Sealing paused, waiting for transactions") 615 return nil 616 } 617 // Don't hold the signer fields for the entire sealing procedure 618 c.lock.RLock() 619 signer, signFn := c.signer, c.signFn 620 c.lock.RUnlock() 621 622 // Bail out if we're unauthorized to sign a block 623 snap, err := c.snapshot(chain, number-1, header.ParentHash, nil) 624 if err != nil { 625 return err 626 } 627 if _, authorized := snap.Signers[signer]; !authorized { 628 return errUnauthorizedSigner 629 } 630 // If we're amongst the recent signers, wait for the next block 631 for seen, recent := range snap.Recents { 632 if recent == signer { 633 // Signer is among recents, only wait if the current block doesn't shift it out 634 if limit := uint64(len(snap.Signers)/2 + 1); number < limit || seen > number-limit { 635 log.Info("Signed recently, must wait for others") 636 return nil 637 } 638 } 639 } 640 // Sweet, the protocol permits us to sign the block, wait for our time 641 delay := time.Unix(int64(header.Time), 0).Sub(time.Now()) // nolint: gosimple 642 if header.Difficulty.Cmp(diffNoTurn) == 0 { 643 // It's not our turn explicitly to sign, delay it a bit 644 wiggle := time.Duration(len(snap.Signers)/2+1) * wiggleTime 645 delay += time.Duration(rand.Int63n(int64(wiggle))) 646 647 log.Trace("Out-of-turn signing requested", "wiggle", common.PrettyDuration(wiggle)) 648 } 649 // Sign all the things! 650 sighash, err := signFn(accounts.Account{Address: signer}, sigHash(header).Bytes()) 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 <- consensus.NewSealResult(block.WithSeal(header), nil, nil): 666 default: 667 log.Warn("Sealing result is not read by miner", "sealhash", c.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 sigHash(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 }