clique.go 27 KB

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