clique.go 23 KB

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