clique.go 26 KB

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