snapshot.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  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
  17. import (
  18. "bytes"
  19. "encoding/json"
  20. "sort"
  21. "time"
  22. "github.com/ethereum/go-ethereum/common"
  23. "github.com/ethereum/go-ethereum/core/types"
  24. "github.com/ethereum/go-ethereum/ethdb"
  25. "github.com/ethereum/go-ethereum/log"
  26. "github.com/ethereum/go-ethereum/params"
  27. lru "github.com/hashicorp/golang-lru"
  28. )
  29. // Vote represents a single vote that an authorized signer made to modify the
  30. // list of authorizations.
  31. type Vote struct {
  32. Signer common.Address `json:"signer"` // Authorized signer that cast this vote
  33. Block uint64 `json:"block"` // Block number the vote was cast in (expire old votes)
  34. Address common.Address `json:"address"` // Account being voted on to change its authorization
  35. Authorize bool `json:"authorize"` // Whether to authorize or deauthorize the voted account
  36. }
  37. // Tally is a simple vote tally to keep the current score of votes. Votes that
  38. // go against the proposal aren't counted since it's equivalent to not voting.
  39. type Tally struct {
  40. Authorize bool `json:"authorize"` // Whether the vote is about authorizing or kicking someone
  41. Votes int `json:"votes"` // Number of votes until now wanting to pass the proposal
  42. }
  43. // Snapshot is the state of the authorization voting at a given point in time.
  44. type Snapshot struct {
  45. config *params.CliqueConfig // Consensus engine parameters to fine tune behavior
  46. sigcache *lru.ARCCache // Cache of recent block signatures to speed up ecrecover
  47. Number uint64 `json:"number"` // Block number where the snapshot was created
  48. Hash common.Hash `json:"hash"` // Block hash where the snapshot was created
  49. Signers map[common.Address]struct{} `json:"signers"` // Set of authorized signers at this moment
  50. Recents map[uint64]common.Address `json:"recents"` // Set of recent signers for spam protections
  51. Votes []*Vote `json:"votes"` // List of votes cast in chronological order
  52. Tally map[common.Address]Tally `json:"tally"` // Current vote tally to avoid recalculating
  53. }
  54. // signersAscending implements the sort interface to allow sorting a list of addresses
  55. type signersAscending []common.Address
  56. func (s signersAscending) Len() int { return len(s) }
  57. func (s signersAscending) Less(i, j int) bool { return bytes.Compare(s[i][:], s[j][:]) < 0 }
  58. func (s signersAscending) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
  59. // newSnapshot creates a new snapshot with the specified startup parameters. This
  60. // method does not initialize the set of recent signers, so only ever use if for
  61. // the genesis block.
  62. func newSnapshot(config *params.CliqueConfig, sigcache *lru.ARCCache, number uint64, hash common.Hash, signers []common.Address) *Snapshot {
  63. snap := &Snapshot{
  64. config: config,
  65. sigcache: sigcache,
  66. Number: number,
  67. Hash: hash,
  68. Signers: make(map[common.Address]struct{}),
  69. Recents: make(map[uint64]common.Address),
  70. Tally: make(map[common.Address]Tally),
  71. }
  72. for _, signer := range signers {
  73. snap.Signers[signer] = struct{}{}
  74. }
  75. return snap
  76. }
  77. // loadSnapshot loads an existing snapshot from the database.
  78. func loadSnapshot(config *params.CliqueConfig, sigcache *lru.ARCCache, db ethdb.Database, hash common.Hash) (*Snapshot, error) {
  79. blob, err := db.Get(append([]byte("clique-"), hash[:]...))
  80. if err != nil {
  81. return nil, err
  82. }
  83. snap := new(Snapshot)
  84. if err := json.Unmarshal(blob, snap); err != nil {
  85. return nil, err
  86. }
  87. snap.config = config
  88. snap.sigcache = sigcache
  89. return snap, nil
  90. }
  91. // store inserts the snapshot into the database.
  92. func (s *Snapshot) store(db ethdb.Database) error {
  93. blob, err := json.Marshal(s)
  94. if err != nil {
  95. return err
  96. }
  97. return db.Put(append([]byte("clique-"), s.Hash[:]...), blob)
  98. }
  99. // copy creates a deep copy of the snapshot, though not the individual votes.
  100. func (s *Snapshot) copy() *Snapshot {
  101. cpy := &Snapshot{
  102. config: s.config,
  103. sigcache: s.sigcache,
  104. Number: s.Number,
  105. Hash: s.Hash,
  106. Signers: make(map[common.Address]struct{}),
  107. Recents: make(map[uint64]common.Address),
  108. Votes: make([]*Vote, len(s.Votes)),
  109. Tally: make(map[common.Address]Tally),
  110. }
  111. for signer := range s.Signers {
  112. cpy.Signers[signer] = struct{}{}
  113. }
  114. for block, signer := range s.Recents {
  115. cpy.Recents[block] = signer
  116. }
  117. for address, tally := range s.Tally {
  118. cpy.Tally[address] = tally
  119. }
  120. copy(cpy.Votes, s.Votes)
  121. return cpy
  122. }
  123. // validVote returns whether it makes sense to cast the specified vote in the
  124. // given snapshot context (e.g. don't try to add an already authorized signer).
  125. func (s *Snapshot) validVote(address common.Address, authorize bool) bool {
  126. _, signer := s.Signers[address]
  127. return (signer && !authorize) || (!signer && authorize)
  128. }
  129. // cast adds a new vote into the tally.
  130. func (s *Snapshot) cast(address common.Address, authorize bool) bool {
  131. // Ensure the vote is meaningful
  132. if !s.validVote(address, authorize) {
  133. return false
  134. }
  135. // Cast the vote into an existing or new tally
  136. if old, ok := s.Tally[address]; ok {
  137. old.Votes++
  138. s.Tally[address] = old
  139. } else {
  140. s.Tally[address] = Tally{Authorize: authorize, Votes: 1}
  141. }
  142. return true
  143. }
  144. // uncast removes a previously cast vote from the tally.
  145. func (s *Snapshot) uncast(address common.Address, authorize bool) bool {
  146. // If there's no tally, it's a dangling vote, just drop
  147. tally, ok := s.Tally[address]
  148. if !ok {
  149. return false
  150. }
  151. // Ensure we only revert counted votes
  152. if tally.Authorize != authorize {
  153. return false
  154. }
  155. // Otherwise revert the vote
  156. if tally.Votes > 1 {
  157. tally.Votes--
  158. s.Tally[address] = tally
  159. } else {
  160. delete(s.Tally, address)
  161. }
  162. return true
  163. }
  164. // apply creates a new authorization snapshot by applying the given headers to
  165. // the original one.
  166. func (s *Snapshot) apply(headers []*types.Header) (*Snapshot, error) {
  167. // Allow passing in no headers for cleaner code
  168. if len(headers) == 0 {
  169. return s, nil
  170. }
  171. // Sanity check that the headers can be applied
  172. for i := 0; i < len(headers)-1; i++ {
  173. if headers[i+1].Number.Uint64() != headers[i].Number.Uint64()+1 {
  174. return nil, errInvalidVotingChain
  175. }
  176. }
  177. if headers[0].Number.Uint64() != s.Number+1 {
  178. return nil, errInvalidVotingChain
  179. }
  180. // Iterate through the headers and create a new snapshot
  181. snap := s.copy()
  182. var (
  183. start = time.Now()
  184. logged = time.Now()
  185. )
  186. for i, header := range headers {
  187. // Remove any votes on checkpoint blocks
  188. number := header.Number.Uint64()
  189. if number%s.config.Epoch == 0 {
  190. snap.Votes = nil
  191. snap.Tally = make(map[common.Address]Tally)
  192. }
  193. // Delete the oldest signer from the recent list to allow it signing again
  194. if limit := uint64(len(snap.Signers)/2 + 1); number >= limit {
  195. delete(snap.Recents, number-limit)
  196. }
  197. // Resolve the authorization key and check against signers
  198. signer, err := ecrecover(header, s.sigcache)
  199. if err != nil {
  200. return nil, err
  201. }
  202. if _, ok := snap.Signers[signer]; !ok {
  203. return nil, errUnauthorizedSigner
  204. }
  205. for _, recent := range snap.Recents {
  206. if recent == signer {
  207. return nil, errRecentlySigned
  208. }
  209. }
  210. snap.Recents[number] = signer
  211. // Header authorized, discard any previous votes from the signer
  212. for i, vote := range snap.Votes {
  213. if vote.Signer == signer && vote.Address == header.Coinbase {
  214. // Uncast the vote from the cached tally
  215. snap.uncast(vote.Address, vote.Authorize)
  216. // Uncast the vote from the chronological list
  217. snap.Votes = append(snap.Votes[:i], snap.Votes[i+1:]...)
  218. break // only one vote allowed
  219. }
  220. }
  221. // Tally up the new vote from the signer
  222. var authorize bool
  223. switch {
  224. case bytes.Equal(header.Nonce[:], nonceAuthVote):
  225. authorize = true
  226. case bytes.Equal(header.Nonce[:], nonceDropVote):
  227. authorize = false
  228. default:
  229. return nil, errInvalidVote
  230. }
  231. if snap.cast(header.Coinbase, authorize) {
  232. snap.Votes = append(snap.Votes, &Vote{
  233. Signer: signer,
  234. Block: number,
  235. Address: header.Coinbase,
  236. Authorize: authorize,
  237. })
  238. }
  239. // If the vote passed, update the list of signers
  240. if tally := snap.Tally[header.Coinbase]; tally.Votes > len(snap.Signers)/2 {
  241. if tally.Authorize {
  242. snap.Signers[header.Coinbase] = struct{}{}
  243. } else {
  244. delete(snap.Signers, header.Coinbase)
  245. // Signer list shrunk, delete any leftover recent caches
  246. if limit := uint64(len(snap.Signers)/2 + 1); number >= limit {
  247. delete(snap.Recents, number-limit)
  248. }
  249. // Discard any previous votes the deauthorized signer cast
  250. for i := 0; i < len(snap.Votes); i++ {
  251. if snap.Votes[i].Signer == header.Coinbase {
  252. // Uncast the vote from the cached tally
  253. snap.uncast(snap.Votes[i].Address, snap.Votes[i].Authorize)
  254. // Uncast the vote from the chronological list
  255. snap.Votes = append(snap.Votes[:i], snap.Votes[i+1:]...)
  256. i--
  257. }
  258. }
  259. }
  260. // Discard any previous votes around the just changed account
  261. for i := 0; i < len(snap.Votes); i++ {
  262. if snap.Votes[i].Address == header.Coinbase {
  263. snap.Votes = append(snap.Votes[:i], snap.Votes[i+1:]...)
  264. i--
  265. }
  266. }
  267. delete(snap.Tally, header.Coinbase)
  268. }
  269. // If we're taking too much time (ecrecover), notify the user once a while
  270. if time.Since(logged) > 8*time.Second {
  271. log.Info("Reconstructing voting history", "processed", i, "total", len(headers), "elapsed", common.PrettyDuration(time.Since(start)))
  272. logged = time.Now()
  273. }
  274. }
  275. if time.Since(start) > 8*time.Second {
  276. log.Info("Reconstructed voting history", "processed", len(headers), "elapsed", common.PrettyDuration(time.Since(start)))
  277. }
  278. snap.Number += uint64(len(headers))
  279. snap.Hash = headers[len(headers)-1].Hash()
  280. return snap, nil
  281. }
  282. // signers retrieves the list of authorized signers in ascending order.
  283. func (s *Snapshot) signers() []common.Address {
  284. sigs := make([]common.Address, 0, len(s.Signers))
  285. for sig := range s.Signers {
  286. sigs = append(sigs, sig)
  287. }
  288. sort.Sort(signersAscending(sigs))
  289. return sigs
  290. }
  291. // inturn returns if a signer at a given block height is in-turn or not.
  292. func (s *Snapshot) inturn(number uint64, signer common.Address) bool {
  293. signers, offset := s.signers(), 0
  294. for offset < len(signers) && signers[offset] != signer {
  295. offset++
  296. }
  297. return (number % uint64(len(signers))) == uint64(offset)
  298. }