clique.go 25 KB

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