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