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