github.com/amazechain/amc@v0.1.3/internal/consensus/apos/snapshot.go (about) 1 // Copyright 2022 The AmazeChain Authors 2 // This file is part of the AmazeChain library. 3 // 4 // The AmazeChain 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 AmazeChain 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 AmazeChain library. If not, see <http://www.gnu.org/licenses/>. 16 17 package apos 18 19 import ( 20 "bytes" 21 "encoding/json" 22 "github.com/amazechain/amc/params" 23 "sort" 24 "time" 25 26 "github.com/amazechain/amc/common/block" 27 "github.com/amazechain/amc/common/types" 28 "github.com/amazechain/amc/internal/avm/common" 29 "github.com/amazechain/amc/log" 30 "github.com/amazechain/amc/modules/rawdb" 31 "github.com/ledgerwatch/erigon-lib/kv" 32 33 lru "github.com/hashicorp/golang-lru" 34 ) 35 36 // Vote represents a single vote that an authorized signer made to modify the 37 // list of authorizations. 38 type Vote struct { 39 Signer types.Address `json:"signer"` // Authorized signer that cast this vote 40 Block uint64 `json:"block"` // Block number the vote was cast in (expire old votes) 41 Address types.Address `json:"address"` // Account being voted on to change its authorization 42 Authorize bool `json:"authorize"` // Whether to authorize or deauthorize the voted account 43 } 44 45 // Tally is a simple vote tally to keep the current score of votes. Votes that 46 // go against the proposal aren't counted since it's equivalent to not voting. 47 type Tally struct { 48 Authorize bool `json:"authorize"` // Whether the vote is about authorizing or kicking someone 49 Votes int `json:"votes"` // Number of votes until now wanting to pass the proposal 50 } 51 52 // Snapshot is the state of the authorization voting at a given point in time. 53 type Snapshot struct { 54 config *params.APosConfig // Consensus engine parameters to fine tune behavior 55 sigcache *lru.ARCCache // Cache of recent block signatures to speed up ecrecover 56 57 Number uint64 `json:"number"` // Block number where the snapshot was created 58 Hash types.Hash `json:"hash"` // Block hash where the snapshot was created 59 Signers map[types.Address]struct{} `json:"signers"` // Set of authorized signers at this moment 60 Recents map[uint64]types.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[types.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 []types.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.APosConfig, sigcache *lru.ARCCache, number uint64, hash types.Hash, signers []types.Address) *Snapshot { 76 snap := &Snapshot{ 77 config: config, 78 sigcache: sigcache, 79 Number: number, 80 Hash: hash, 81 Signers: make(map[types.Address]struct{}), 82 Recents: make(map[uint64]types.Address), 83 Tally: make(map[types.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.APosConfig, sigcache *lru.ARCCache, tx kv.Getter, hash types.Hash) (*Snapshot, error) { 93 blob, err := rawdb.GetPoaSnapshot(tx, 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(tx kv.Putter) error { 109 blob, err := json.Marshal(s) 110 if err != nil { 111 return err 112 } 113 return rawdb.StorePoaSnapshot(tx, 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[types.Address]struct{}), 124 Recents: make(map[uint64]types.Address), 125 Votes: make([]*Vote, len(s.Votes)), 126 Tally: make(map[types.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 types.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 types.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 types.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 []block.IHeader) (*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].(*block.Header).Number.Uint64() != headers[i].(*block.Header).Number.Uint64()+1 { 196 return nil, errInvalidVotingChain 197 } 198 } 199 if headers[0].(*block.Header).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, iHeader := range headers { 210 header := iHeader.(*block.Header) 211 // Remove any votes on checkpoint blocks 212 number := header.Number.Uint64() 213 if number%s.config.Epoch == 0 { 214 snap.Votes = nil 215 snap.Tally = make(map[types.Address]Tally) 216 } 217 // Delete the oldest signer from the recent list to allow it signing again 218 if limit := uint64(len(snap.Signers)/2 + 1); number >= limit { 219 delete(snap.Recents, number-limit) 220 } 221 // Resolve the authorization key and check against signers 222 signer, err := ecrecover(header, s.sigcache) 223 if err != nil { 224 return nil, err 225 } 226 if _, ok := snap.Signers[signer]; !ok { 227 return nil, errUnauthorizedSigner 228 } 229 for _, recent := range snap.Recents { 230 if recent == signer { 231 return nil, errRecentlySigned 232 } 233 } 234 snap.Recents[number] = signer 235 236 // Header authorized, discard any previous votes from the signer 237 for i, vote := range snap.Votes { 238 if vote.Signer == signer && vote.Address == header.Coinbase { 239 // Uncast the vote from the cached tally 240 snap.uncast(vote.Address, vote.Authorize) 241 242 // Uncast the vote from the chronological list 243 snap.Votes = append(snap.Votes[:i], snap.Votes[i+1:]...) 244 break // only one vote allowed 245 } 246 } 247 // Tally up the new vote from the signer 248 var authorize bool 249 switch { 250 case bytes.Equal(header.Nonce[:], nonceAuthVote): 251 authorize = true 252 case bytes.Equal(header.Nonce[:], nonceDropVote): 253 authorize = false 254 default: 255 return nil, errInvalidVote 256 } 257 if snap.cast(header.Coinbase, authorize) { 258 snap.Votes = append(snap.Votes, &Vote{ 259 Signer: signer, 260 Block: number, 261 Address: header.Coinbase, 262 Authorize: authorize, 263 }) 264 } 265 // If the vote passed, update the list of signers 266 if tally := snap.Tally[header.Coinbase]; tally.Votes > len(snap.Signers)/2 { 267 if tally.Authorize { 268 snap.Signers[header.Coinbase] = struct{}{} 269 } else { 270 delete(snap.Signers, header.Coinbase) 271 272 // Signer list shrunk, delete any leftover recent caches 273 if limit := uint64(len(snap.Signers)/2 + 1); number >= limit { 274 delete(snap.Recents, number-limit) 275 } 276 // Discard any previous votes the deauthorized signer cast 277 for i := 0; i < len(snap.Votes); i++ { 278 if snap.Votes[i].Signer == header.Coinbase { 279 // Uncast the vote from the cached tally 280 snap.uncast(snap.Votes[i].Address, snap.Votes[i].Authorize) 281 282 // Uncast the vote from the chronological list 283 snap.Votes = append(snap.Votes[:i], snap.Votes[i+1:]...) 284 285 i-- 286 } 287 } 288 } 289 // Discard any previous votes around the just changed account 290 for i := 0; i < len(snap.Votes); i++ { 291 if snap.Votes[i].Address == header.Coinbase { 292 snap.Votes = append(snap.Votes[:i], snap.Votes[i+1:]...) 293 i-- 294 } 295 } 296 delete(snap.Tally, header.Coinbase) 297 } 298 // If we're taking too much time (ecrecover), notify the user once a while 299 if time.Since(logged) > 8*time.Second { 300 log.Info("Reconstructing voting history", "processed", i, "total", len(headers), "elapsed", common.PrettyDuration(time.Since(start))) 301 logged = time.Now() 302 } 303 } 304 if time.Since(start) > 8*time.Second { 305 //log.Info("Reconstructed voting history", "processed", len(headers), "elapsed", common.PrettyDuration(time.Since(start))) 306 } 307 snap.Number += uint64(len(headers)) 308 snap.Hash = headers[len(headers)-1].Hash() 309 310 return snap, nil 311 } 312 313 // signers retrieves the list of authorized signers in ascending order. 314 func (s *Snapshot) signers() []types.Address { 315 sigs := make([]types.Address, 0, len(s.Signers)) 316 for sig := range s.Signers { 317 sigs = append(sigs, sig) 318 } 319 sort.Sort(signersAscending(sigs)) 320 return sigs 321 } 322 323 // inturn returns if a signer at a given block height is in-turn or not. 324 func (s *Snapshot) inturn(number uint64, signer types.Address) bool { 325 signers, offset := s.signers(), 0 326 for offset < len(signers) && signers[offset] != signer { 327 offset++ 328 } 329 return (number % uint64(len(signers))) == uint64(offset) 330 }