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