clique.go 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735
  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/hexutil"
  29. "github.com/ethereum/go-ethereum/consensus"
  30. "github.com/ethereum/go-ethereum/consensus/misc"
  31. "github.com/ethereum/go-ethereum/core/state"
  32. "github.com/ethereum/go-ethereum/core/types"
  33. "github.com/ethereum/go-ethereum/crypto"
  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. "github.com/ethereum/go-ethereum/trie"
  40. lru "github.com/hashicorp/golang-lru"
  41. "golang.org/x/crypto/sha3"
  42. )
  43. const (
  44. checkpointInterval = 1024 // Number of blocks after which to save the vote snapshot to the database
  45. inmemorySnapshots = 128 // Number of recent vote snapshots to keep in memory
  46. inmemorySignatures = 4096 // Number of recent block signatures to keep in memory
  47. wiggleTime = 500 * time.Millisecond // Random delay (per signer) to allow concurrent signers
  48. )
  49. // Clique proof-of-authority protocol constants.
  50. var (
  51. epochLength = uint64(30000) // Default number of blocks after which to checkpoint and reset the pending votes
  52. extraVanity = 32 // Fixed number of extra-data prefix bytes reserved for signer vanity
  53. extraSeal = crypto.SignatureLength // Fixed number of extra-data suffix bytes reserved for signer seal
  54. nonceAuthVote = hexutil.MustDecode("0xffffffffffffffff") // Magic nonce number to vote on adding a new signer
  55. nonceDropVote = hexutil.MustDecode("0x0000000000000000") // Magic nonce number to vote on removing a signer.
  56. uncleHash = types.CalcUncleHash(nil) // Always Keccak256(RLP([])) as uncles are meaningless outside of PoW.
  57. diffInTurn = big.NewInt(2) // Block difficulty for in-turn signatures
  58. diffNoTurn = big.NewInt(1) // Block difficulty for out-of-turn signatures
  59. )
  60. // Various error messages to mark blocks invalid. These should be private to
  61. // prevent engine specific errors from being referenced in the remainder of the
  62. // codebase, inherently breaking if the engine is swapped out. Please put common
  63. // error types into the consensus package.
  64. var (
  65. // errUnknownBlock is returned when the list of signers is requested for a block
  66. // that is not part of the local blockchain.
  67. errUnknownBlock = errors.New("unknown block")
  68. // errInvalidCheckpointBeneficiary is returned if a checkpoint/epoch transition
  69. // block has a beneficiary set to non-zeroes.
  70. errInvalidCheckpointBeneficiary = errors.New("beneficiary in checkpoint block non-zero")
  71. // errInvalidVote is returned if a nonce value is something else that the two
  72. // allowed constants of 0x00..0 or 0xff..f.
  73. errInvalidVote = errors.New("vote nonce not 0x00..0 or 0xff..f")
  74. // errInvalidCheckpointVote is returned if a checkpoint/epoch transition block
  75. // has a vote nonce set to non-zeroes.
  76. errInvalidCheckpointVote = errors.New("vote nonce in checkpoint block non-zero")
  77. // errMissingVanity is returned if a block's extra-data section is shorter than
  78. // 32 bytes, which is required to store the signer vanity.
  79. errMissingVanity = errors.New("extra-data 32 byte vanity prefix missing")
  80. // errMissingSignature is returned if a block's extra-data section doesn't seem
  81. // to contain a 65 byte secp256k1 signature.
  82. errMissingSignature = errors.New("extra-data 65 byte signature suffix missing")
  83. // errExtraSigners is returned if non-checkpoint block contain signer data in
  84. // their extra-data fields.
  85. errExtraSigners = errors.New("non-checkpoint block contains extra signer list")
  86. // errInvalidCheckpointSigners is returned if a checkpoint block contains an
  87. // invalid list of signers (i.e. non divisible by 20 bytes).
  88. errInvalidCheckpointSigners = errors.New("invalid signer list on checkpoint block")
  89. // errMismatchingCheckpointSigners is returned if a checkpoint block contains a
  90. // list of signers different than the one the local node calculated.
  91. errMismatchingCheckpointSigners = errors.New("mismatching signer list on checkpoint block")
  92. // errInvalidMixDigest is returned if a block's mix digest is non-zero.
  93. errInvalidMixDigest = errors.New("non-zero mix digest")
  94. // errInvalidUncleHash is returned if a block contains an non-empty uncle list.
  95. errInvalidUncleHash = errors.New("non empty uncle hash")
  96. // errInvalidDifficulty is returned if the difficulty of a block neither 1 or 2.
  97. errInvalidDifficulty = errors.New("invalid difficulty")
  98. // errWrongDifficulty is returned if the difficulty of a block doesn't match the
  99. // turn of the signer.
  100. errWrongDifficulty = errors.New("wrong difficulty")
  101. // errInvalidTimestamp is returned if the timestamp of a block is lower than
  102. // the previous block's timestamp + the minimum block period.
  103. errInvalidTimestamp = errors.New("invalid timestamp")
  104. // errInvalidVotingChain is returned if an authorization list is attempted to
  105. // be modified via out-of-range or non-contiguous headers.
  106. errInvalidVotingChain = errors.New("invalid voting chain")
  107. // errUnauthorizedSigner is returned if a header is signed by a non-authorized entity.
  108. errUnauthorizedSigner = errors.New("unauthorized signer")
  109. // errRecentlySigned is returned if a header is signed by an authorized entity
  110. // that already signed a header recently, thus is temporarily not allowed to.
  111. errRecentlySigned = errors.New("recently signed")
  112. )
  113. // SignerFn hashes and signs the data to be signed by a backing account.
  114. type SignerFn func(signer accounts.Account, mimeType string, message []byte) ([]byte, error)
  115. // ecrecover extracts the Ethereum account address from a signed header.
  116. func ecrecover(header *types.Header, sigcache *lru.ARCCache) (common.Address, error) {
  117. // If the signature's already cached, return that
  118. hash := header.Hash()
  119. if address, known := sigcache.Get(hash); known {
  120. return address.(common.Address), nil
  121. }
  122. // Retrieve the signature from the header extra-data
  123. if len(header.Extra) < extraSeal {
  124. return common.Address{}, errMissingSignature
  125. }
  126. signature := header.Extra[len(header.Extra)-extraSeal:]
  127. // Recover the public key and the Ethereum address
  128. pubkey, err := crypto.Ecrecover(SealHash(header).Bytes(), signature)
  129. if err != nil {
  130. return common.Address{}, err
  131. }
  132. var signer common.Address
  133. copy(signer[:], crypto.Keccak256(pubkey[1:])[12:])
  134. sigcache.Add(hash, signer)
  135. return signer, nil
  136. }
  137. // Clique is the proof-of-authority consensus engine proposed to support the
  138. // Ethereum testnet following the Ropsten attacks.
  139. type Clique struct {
  140. config *params.CliqueConfig // Consensus engine configuration parameters
  141. db ethdb.Database // Database to store and retrieve snapshot checkpoints
  142. recents *lru.ARCCache // Snapshots for recent block to speed up reorgs
  143. signatures *lru.ARCCache // Signatures of recent blocks to speed up mining
  144. proposals map[common.Address]bool // Current list of proposals we are pushing
  145. signer common.Address // Ethereum address of the signing key
  146. signFn SignerFn // Signer function to authorize hashes with
  147. lock sync.RWMutex // Protects the signer fields
  148. // The fields below are for testing only
  149. fakeDiff bool // Skip difficulty verifications
  150. }
  151. // New creates a Clique proof-of-authority consensus engine with the initial
  152. // signers set to the ones provided by the user.
  153. func New(config *params.CliqueConfig, db ethdb.Database) *Clique {
  154. // Set any missing consensus parameters to their defaults
  155. conf := *config
  156. if conf.Epoch == 0 {
  157. conf.Epoch = epochLength
  158. }
  159. // Allocate the snapshot caches and create the engine
  160. recents, _ := lru.NewARC(inmemorySnapshots)
  161. signatures, _ := lru.NewARC(inmemorySignatures)
  162. return &Clique{
  163. config: &conf,
  164. db: db,
  165. recents: recents,
  166. signatures: signatures,
  167. proposals: make(map[common.Address]bool),
  168. }
  169. }
  170. // Author implements consensus.Engine, returning the Ethereum address recovered
  171. // from the signature in the header's extra-data section.
  172. func (c *Clique) Author(header *types.Header) (common.Address, error) {
  173. return ecrecover(header, c.signatures)
  174. }
  175. // VerifyHeader checks whether a header conforms to the consensus rules.
  176. func (c *Clique) VerifyHeader(chain consensus.ChainHeaderReader, header *types.Header, seal bool) error {
  177. return c.verifyHeader(chain, header, nil)
  178. }
  179. // VerifyHeaders is similar to VerifyHeader, but verifies a batch of headers. The
  180. // method returns a quit channel to abort the operations and a results channel to
  181. // retrieve the async verifications (the order is that of the input slice).
  182. func (c *Clique) VerifyHeaders(chain consensus.ChainHeaderReader, headers []*types.Header, seals []bool) (chan<- struct{}, <-chan error) {
  183. abort := make(chan struct{})
  184. results := make(chan error, len(headers))
  185. go func() {
  186. for i, header := range headers {
  187. err := c.verifyHeader(chain, header, headers[:i])
  188. select {
  189. case <-abort:
  190. return
  191. case results <- err:
  192. }
  193. }
  194. }()
  195. return abort, results
  196. }
  197. // verifyHeader checks whether a header conforms to the consensus rules.The
  198. // caller may optionally pass in a batch of parents (ascending order) to avoid
  199. // looking those up from the database. This is useful for concurrently verifying
  200. // a batch of new headers.
  201. func (c *Clique) verifyHeader(chain consensus.ChainHeaderReader, header *types.Header, parents []*types.Header) error {
  202. if header.Number == nil {
  203. return errUnknownBlock
  204. }
  205. number := header.Number.Uint64()
  206. // Don't waste time checking blocks from the future (adjusting for allowed threshold)
  207. adjustedTimeNow := time.Now().Add(time.Duration(c.config.AllowedFutureBlockTime) * time.Second).Unix()
  208. if header.Time > uint64(adjustedTimeNow) {
  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.GetImmutabilityThreshold() || 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. // No block rewards in PoA, so the state remains as is and uncles are dropped
  492. header.Root = state.IntermediateRoot(chain.Config().IsEIP158(header.Number))
  493. header.UncleHash = types.CalcUncleHash(nil)
  494. }
  495. // FinalizeAndAssemble implements consensus.Engine, ensuring no uncles are set,
  496. // nor block rewards given, and returns the final block.
  497. func (c *Clique) FinalizeAndAssemble(chain consensus.ChainHeaderReader, header *types.Header, state *state.StateDB, txs []*types.Transaction, uncles []*types.Header, receipts []*types.Receipt) (*types.Block, error) {
  498. // Finalize block
  499. c.Finalize(chain, header, state, txs, uncles)
  500. // Assemble and return the final block for sealing
  501. return types.NewBlock(header, txs, nil, receipts, trie.NewStackTrie(nil)), nil
  502. }
  503. // Authorize injects a private key into the consensus engine to mint new blocks
  504. // with.
  505. func (c *Clique) Authorize(signer common.Address, signFn SignerFn) {
  506. c.lock.Lock()
  507. defer c.lock.Unlock()
  508. c.signer = signer
  509. c.signFn = signFn
  510. }
  511. // Seal implements consensus.Engine, attempting to create a sealed block using
  512. // the local signing credentials.
  513. func (c *Clique) Seal(chain consensus.ChainHeaderReader, block *types.Block, results chan<- *types.Block, stop <-chan struct{}) error {
  514. header := block.Header()
  515. // Sealing the genesis block is not supported
  516. number := header.Number.Uint64()
  517. if number == 0 {
  518. return errUnknownBlock
  519. }
  520. // For 0-period chains, refuse to seal empty blocks (no reward but would spin sealing)
  521. if c.config.Period == 0 && len(block.Transactions()) == 0 {
  522. log.Info("Sealing paused, waiting for transactions")
  523. return nil
  524. }
  525. // Don't hold the signer fields for the entire sealing procedure
  526. c.lock.RLock()
  527. signer, signFn := c.signer, c.signFn
  528. c.lock.RUnlock()
  529. // Bail out if we're unauthorized to sign a block
  530. snap, err := c.snapshot(chain, number-1, header.ParentHash, nil)
  531. if err != nil {
  532. return err
  533. }
  534. if _, authorized := snap.Signers[signer]; !authorized {
  535. return errUnauthorizedSigner
  536. }
  537. // If we're amongst the recent signers, wait for the next block
  538. for seen, recent := range snap.Recents {
  539. if recent == signer {
  540. // Signer is among recents, only wait if the current block doesn't shift it out
  541. if limit := uint64(len(snap.Signers)/2 + 1); number < limit || seen > number-limit {
  542. log.Info("Signed recently, must wait for others")
  543. return nil
  544. }
  545. }
  546. }
  547. // Sweet, the protocol permits us to sign the block, wait for our time
  548. delay := time.Unix(int64(header.Time), 0).Sub(time.Now()) // nolint: gosimple
  549. if header.Difficulty.Cmp(diffNoTurn) == 0 {
  550. // It's not our turn explicitly to sign, delay it a bit
  551. wiggle := time.Duration(len(snap.Signers)/2+1) * wiggleTime
  552. delay += time.Duration(rand.Int63n(int64(wiggle)))
  553. log.Trace("Out-of-turn signing requested", "wiggle", common.PrettyDuration(wiggle))
  554. }
  555. // Sign all the things!
  556. sighash, err := signFn(accounts.Account{Address: signer}, accounts.MimetypeClique, CliqueRLP(header))
  557. if err != nil {
  558. return err
  559. }
  560. copy(header.Extra[len(header.Extra)-extraSeal:], sighash)
  561. // Wait until sealing is terminated or delay timeout.
  562. log.Trace("Waiting for slot to sign and propagate", "delay", common.PrettyDuration(delay))
  563. go func() {
  564. select {
  565. case <-stop:
  566. return
  567. case <-time.After(delay):
  568. }
  569. select {
  570. case results <- block.WithSeal(header):
  571. default:
  572. log.Warn("Sealing result is not read by miner", "sealhash", SealHash(header))
  573. }
  574. }()
  575. return nil
  576. }
  577. // CalcDifficulty is the difficulty adjustment algorithm. It returns the difficulty
  578. // that a new block should have:
  579. // * DIFF_NOTURN(2) if BLOCK_NUMBER % SIGNER_COUNT != SIGNER_INDEX
  580. // * DIFF_INTURN(1) if BLOCK_NUMBER % SIGNER_COUNT == SIGNER_INDEX
  581. func (c *Clique) CalcDifficulty(chain consensus.ChainHeaderReader, time uint64, parent *types.Header) *big.Int {
  582. snap, err := c.snapshot(chain, parent.Number.Uint64(), parent.Hash(), nil)
  583. if err != nil {
  584. return nil
  585. }
  586. return calcDifficulty(snap, c.signer)
  587. }
  588. func calcDifficulty(snap *Snapshot, signer common.Address) *big.Int {
  589. if snap.inturn(snap.Number+1, signer) {
  590. return new(big.Int).Set(diffInTurn)
  591. }
  592. return new(big.Int).Set(diffNoTurn)
  593. }
  594. // SealHash returns the hash of a block prior to it being sealed.
  595. func (c *Clique) SealHash(header *types.Header) common.Hash {
  596. return SealHash(header)
  597. }
  598. // Close implements consensus.Engine. It's a noop for clique as there are no background threads.
  599. func (c *Clique) Close() error {
  600. return nil
  601. }
  602. // APIs implements consensus.Engine, returning the user facing RPC API to allow
  603. // controlling the signer voting.
  604. func (c *Clique) APIs(chain consensus.ChainHeaderReader) []rpc.API {
  605. return []rpc.API{{
  606. Namespace: "clique",
  607. Version: "1.0",
  608. Service: &API{chain: chain, clique: c},
  609. Public: false,
  610. }}
  611. }
  612. // SealHash returns the hash of a block prior to it being sealed.
  613. func SealHash(header *types.Header) (hash common.Hash) {
  614. hasher := sha3.NewLegacyKeccak256()
  615. encodeSigHeader(hasher, header)
  616. hasher.Sum(hash[:0])
  617. return hash
  618. }
  619. // CliqueRLP returns the rlp bytes which needs to be signed for the proof-of-authority
  620. // sealing. The RLP to sign consists of the entire header apart from the 65 byte signature
  621. // contained at the end of the extra data.
  622. //
  623. // Note, the method requires the extra data to be at least 65 bytes, otherwise it
  624. // panics. This is done to avoid accidentally using both forms (signature present
  625. // or not), which could be abused to produce different hashes for the same header.
  626. func CliqueRLP(header *types.Header) []byte {
  627. b := new(bytes.Buffer)
  628. encodeSigHeader(b, header)
  629. return b.Bytes()
  630. }
  631. func encodeSigHeader(w io.Writer, header *types.Header) {
  632. err := rlp.Encode(w, []interface{}{
  633. header.ParentHash,
  634. header.UncleHash,
  635. header.Coinbase,
  636. header.Root,
  637. header.TxHash,
  638. header.ReceiptHash,
  639. header.Bloom,
  640. header.Difficulty,
  641. header.Number,
  642. header.GasLimit,
  643. header.GasUsed,
  644. header.Time,
  645. header.Extra[:len(header.Extra)-crypto.SignatureLength], // Yes, this will panic if extra is too short
  646. header.MixDigest,
  647. header.Nonce,
  648. })
  649. if err != nil {
  650. panic("can't encode: " + err.Error())
  651. }
  652. }
  653. // Protocol implements consensus.Engine.Protocol
  654. func (c *Clique) Protocol() consensus.Protocol {
  655. return consensus.CliqueProtocol
  656. }