clique.go 24 KB

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