github.com/theQRL/go-zond@v0.1.1/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 "time" 23 24 "github.com/theQRL/go-zond/common" 25 "github.com/theQRL/go-zond/common/lru" 26 "github.com/theQRL/go-zond/core/rawdb" 27 "github.com/theQRL/go-zond/core/types" 28 "github.com/theQRL/go-zond/log" 29 "github.com/theQRL/go-zond/params" 30 "github.com/theQRL/go-zond/zonddb" 31 "golang.org/x/exp/slices" 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 // newSnapshot creates a new snapshot with the specified startup parameters. This 66 // method does not initialize the set of recent signers, so only ever use if for 67 // the genesis block. 68 func newSnapshot(config *params.CliqueConfig, sigcache *sigLRU, number uint64, hash common.Hash, signers []common.Address) *Snapshot { 69 snap := &Snapshot{ 70 config: config, 71 sigcache: sigcache, 72 Number: number, 73 Hash: hash, 74 Signers: make(map[common.Address]struct{}), 75 Recents: make(map[uint64]common.Address), 76 Tally: make(map[common.Address]Tally), 77 } 78 for _, signer := range signers { 79 snap.Signers[signer] = struct{}{} 80 } 81 return snap 82 } 83 84 // loadSnapshot loads an existing snapshot from the database. 85 func loadSnapshot(config *params.CliqueConfig, sigcache *sigLRU, db zonddb.Database, hash common.Hash) (*Snapshot, error) { 86 blob, err := db.Get(append(rawdb.CliqueSnapshotPrefix, hash[:]...)) 87 if err != nil { 88 return nil, err 89 } 90 snap := new(Snapshot) 91 if err := json.Unmarshal(blob, snap); err != nil { 92 return nil, err 93 } 94 snap.config = config 95 snap.sigcache = sigcache 96 97 return snap, nil 98 } 99 100 // store inserts the snapshot into the database. 101 func (s *Snapshot) store(db zonddb.Database) error { 102 blob, err := json.Marshal(s) 103 if err != nil { 104 return err 105 } 106 return db.Put(append(rawdb.CliqueSnapshotPrefix, s.Hash[:]...), blob) 107 } 108 109 // copy creates a deep copy of the snapshot, though not the individual votes. 110 func (s *Snapshot) copy() *Snapshot { 111 cpy := &Snapshot{ 112 config: s.config, 113 sigcache: s.sigcache, 114 Number: s.Number, 115 Hash: s.Hash, 116 Signers: make(map[common.Address]struct{}), 117 Recents: make(map[uint64]common.Address), 118 Votes: make([]*Vote, len(s.Votes)), 119 Tally: make(map[common.Address]Tally), 120 } 121 for signer := range s.Signers { 122 cpy.Signers[signer] = struct{}{} 123 } 124 for block, signer := range s.Recents { 125 cpy.Recents[block] = signer 126 } 127 for address, tally := range s.Tally { 128 cpy.Tally[address] = tally 129 } 130 copy(cpy.Votes, s.Votes) 131 132 return cpy 133 } 134 135 // validVote returns whether it makes sense to cast the specified vote in the 136 // given snapshot context (e.g. don't try to add an already authorized signer). 137 func (s *Snapshot) validVote(address common.Address, authorize bool) bool { 138 _, signer := s.Signers[address] 139 return (signer && !authorize) || (!signer && authorize) 140 } 141 142 // cast adds a new vote into the tally. 143 func (s *Snapshot) cast(address common.Address, authorize bool) bool { 144 // Ensure the vote is meaningful 145 if !s.validVote(address, authorize) { 146 return false 147 } 148 // Cast the vote into an existing or new tally 149 if old, ok := s.Tally[address]; ok { 150 old.Votes++ 151 s.Tally[address] = old 152 } else { 153 s.Tally[address] = Tally{Authorize: authorize, Votes: 1} 154 } 155 return true 156 } 157 158 // uncast removes a previously cast vote from the tally. 159 func (s *Snapshot) uncast(address common.Address, authorize bool) bool { 160 // If there's no tally, it's a dangling vote, just drop 161 tally, ok := s.Tally[address] 162 if !ok { 163 return false 164 } 165 // Ensure we only revert counted votes 166 if tally.Authorize != authorize { 167 return false 168 } 169 // Otherwise revert the vote 170 if tally.Votes > 1 { 171 tally.Votes-- 172 s.Tally[address] = tally 173 } else { 174 delete(s.Tally, address) 175 } 176 return true 177 } 178 179 // apply creates a new authorization snapshot by applying the given headers to 180 // the original one. 181 func (s *Snapshot) apply(headers []*types.Header) (*Snapshot, error) { 182 // Allow passing in no headers for cleaner code 183 if len(headers) == 0 { 184 return s, nil 185 } 186 // Sanity check that the headers can be applied 187 for i := 0; i < len(headers)-1; i++ { 188 if headers[i+1].Number.Uint64() != headers[i].Number.Uint64()+1 { 189 return nil, errInvalidVotingChain 190 } 191 } 192 if headers[0].Number.Uint64() != s.Number+1 { 193 return nil, errInvalidVotingChain 194 } 195 // Iterate through the headers and create a new snapshot 196 snap := s.copy() 197 198 var ( 199 start = time.Now() 200 logged = time.Now() 201 ) 202 for i, header := range headers { 203 // Remove any votes on checkpoint blocks 204 number := header.Number.Uint64() 205 if number%s.config.Epoch == 0 { 206 snap.Votes = nil 207 snap.Tally = make(map[common.Address]Tally) 208 } 209 // Delete the oldest signer from the recent list to allow it signing again 210 if limit := uint64(len(snap.Signers)/2 + 1); number >= limit { 211 delete(snap.Recents, number-limit) 212 } 213 // Resolve the authorization key and check against signers 214 signer, err := ecrecover(header, s.sigcache) 215 if err != nil { 216 return nil, err 217 } 218 if _, ok := snap.Signers[signer]; !ok { 219 return nil, errUnauthorizedSigner 220 } 221 for _, recent := range snap.Recents { 222 if recent == signer { 223 return nil, errRecentlySigned 224 } 225 } 226 snap.Recents[number] = signer 227 228 // Header authorized, discard any previous votes from the signer 229 for i, vote := range snap.Votes { 230 if vote.Signer == signer && vote.Address == header.Coinbase { 231 // Uncast the vote from the cached tally 232 snap.uncast(vote.Address, vote.Authorize) 233 234 // Uncast the vote from the chronological list 235 snap.Votes = append(snap.Votes[:i], snap.Votes[i+1:]...) 236 break // only one vote allowed 237 } 238 } 239 // Tally up the new vote from the signer 240 var authorize bool 241 switch { 242 case bytes.Equal(header.Nonce[:], nonceAuthVote): 243 authorize = true 244 case bytes.Equal(header.Nonce[:], nonceDropVote): 245 authorize = false 246 default: 247 return nil, errInvalidVote 248 } 249 if snap.cast(header.Coinbase, authorize) { 250 snap.Votes = append(snap.Votes, &Vote{ 251 Signer: signer, 252 Block: number, 253 Address: header.Coinbase, 254 Authorize: authorize, 255 }) 256 } 257 // If the vote passed, update the list of signers 258 if tally := snap.Tally[header.Coinbase]; tally.Votes > len(snap.Signers)/2 { 259 if tally.Authorize { 260 snap.Signers[header.Coinbase] = struct{}{} 261 } else { 262 delete(snap.Signers, header.Coinbase) 263 264 // Signer list shrunk, delete any leftover recent caches 265 if limit := uint64(len(snap.Signers)/2 + 1); number >= limit { 266 delete(snap.Recents, number-limit) 267 } 268 // Discard any previous votes the deauthorized signer cast 269 for i := 0; i < len(snap.Votes); i++ { 270 if snap.Votes[i].Signer == header.Coinbase { 271 // Uncast the vote from the cached tally 272 snap.uncast(snap.Votes[i].Address, snap.Votes[i].Authorize) 273 274 // Uncast the vote from the chronological list 275 snap.Votes = append(snap.Votes[:i], snap.Votes[i+1:]...) 276 277 i-- 278 } 279 } 280 } 281 // Discard any previous votes around the just changed account 282 for i := 0; i < len(snap.Votes); i++ { 283 if snap.Votes[i].Address == header.Coinbase { 284 snap.Votes = append(snap.Votes[:i], snap.Votes[i+1:]...) 285 i-- 286 } 287 } 288 delete(snap.Tally, header.Coinbase) 289 } 290 // If we're taking too much time (ecrecover), notify the user once a while 291 if time.Since(logged) > 8*time.Second { 292 log.Info("Reconstructing voting history", "processed", i, "total", len(headers), "elapsed", common.PrettyDuration(time.Since(start))) 293 logged = time.Now() 294 } 295 } 296 if time.Since(start) > 8*time.Second { 297 log.Info("Reconstructed voting history", "processed", len(headers), "elapsed", common.PrettyDuration(time.Since(start))) 298 } 299 snap.Number += uint64(len(headers)) 300 snap.Hash = headers[len(headers)-1].Hash() 301 302 return snap, nil 303 } 304 305 // signers retrieves the list of authorized signers in ascending order. 306 func (s *Snapshot) signers() []common.Address { 307 sigs := make([]common.Address, 0, len(s.Signers)) 308 for sig := range s.Signers { 309 sigs = append(sigs, sig) 310 } 311 slices.SortFunc(sigs, common.Address.Cmp) 312 return sigs 313 } 314 315 // inturn returns if a signer at a given block height is in-turn or not. 316 func (s *Snapshot) inturn(number uint64, signer common.Address) bool { 317 signers, offset := s.signers(), 0 318 for offset < len(signers) && signers[offset] != signer { 319 offset++ 320 } 321 return (number % uint64(len(signers))) == uint64(offset) 322 }