clique.go 26 KB

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