github.com/onflow/flow-go@v0.33.17/consensus/hotstuff/signature/weighted_signature_aggregator.go (about) 1 package signature 2 3 import ( 4 "errors" 5 "fmt" 6 "sync" 7 8 "github.com/onflow/flow-go/consensus/hotstuff" 9 "github.com/onflow/flow-go/consensus/hotstuff/model" 10 "github.com/onflow/flow-go/crypto" 11 "github.com/onflow/flow-go/model/flow" 12 "github.com/onflow/flow-go/module/signature" 13 ) 14 15 // signerInfo holds information about a signer, its weight and index 16 type signerInfo struct { 17 weight uint64 18 index int 19 } 20 21 // WeightedSignatureAggregator implements consensus/hotstuff.WeightedSignatureAggregator. 22 // It is a wrapper around module/signature.SignatureAggregatorSameMessage, which implements a 23 // mapping from node IDs (as used by HotStuff) to index-based addressing of authorized 24 // signers (as used by SignatureAggregatorSameMessage). 25 // 26 // Similarly to module/signature.SignatureAggregatorSameMessage, this module assumes proofs of possession (PoP) 27 // of all identity public keys are valid. 28 type WeightedSignatureAggregator struct { 29 aggregator *signature.SignatureAggregatorSameMessage // low level crypto BLS aggregator, agnostic of weights and flow IDs 30 ids flow.IdentityList // all possible ids (only gets updated by constructor) 31 idToInfo map[flow.Identifier]signerInfo // auxiliary map to lookup signer weight and index by ID (only gets updated by constructor) 32 totalWeight uint64 // weight collected (gets updated) 33 lock sync.RWMutex // lock for atomic updates to totalWeight and collectedIDs 34 35 // collectedIDs tracks the Identities of all nodes whose signatures have been collected so far. 36 // The reason for tracking the duplicate signers at this module level is that having no duplicates 37 // is a Hotstuff constraint, rather than a cryptographic aggregation constraint. We are planning to 38 // extend the cryptographic primitives to support multiplicity higher than 1 in the future. 39 // Therefore, we already add the logic for identifying duplicates here. 40 collectedIDs map[flow.Identifier]struct{} // map of collected IDs (gets updated) 41 } 42 43 var _ hotstuff.WeightedSignatureAggregator = (*WeightedSignatureAggregator)(nil) 44 45 // NewWeightedSignatureAggregator returns a weighted aggregator initialized with a list of flow 46 // identities, their respective public keys, a message and a domain separation tag. The identities 47 // represent the list of all possible signers. 48 // This aggregator is only safe if PoPs of all identity keys are valid. This constructor does not 49 // verify the PoPs but assumes they have been validated outside this module. 50 // The constructor errors if: 51 // - the list of identities is empty 52 // - if the length of keys does not match the length of identities 53 // - if one of the keys is not a valid public key. 54 // 55 // A weighted aggregator is used for one aggregation only. A new instance should be used for each 56 // signature aggregation task in the protocol. 57 func NewWeightedSignatureAggregator( 58 ids flow.IdentityList, // list of all authorized signers 59 pks []crypto.PublicKey, // list of corresponding public keys used for signature verifications 60 message []byte, // message to get an aggregated signature for 61 dsTag string, // domain separation tag used by the signature 62 ) (*WeightedSignatureAggregator, error) { 63 if len(ids) != len(pks) { 64 return nil, fmt.Errorf("keys length %d and identities length %d do not match", len(pks), len(ids)) 65 } 66 67 // build the internal map for a faster look-up 68 idToInfo := make(map[flow.Identifier]signerInfo) 69 for i, id := range ids { 70 idToInfo[id.NodeID] = signerInfo{ 71 weight: id.Weight, 72 index: i, 73 } 74 } 75 76 // instantiate low-level crypto aggregator, which works based on signer indices instead of nodeIDs 77 agg, err := signature.NewSignatureAggregatorSameMessage(message, dsTag, pks) 78 if err != nil { 79 return nil, fmt.Errorf("instantiating index-based signature aggregator failed: %w", err) 80 } 81 82 return &WeightedSignatureAggregator{ 83 aggregator: agg, 84 ids: ids, 85 idToInfo: idToInfo, 86 collectedIDs: make(map[flow.Identifier]struct{}), 87 }, nil 88 } 89 90 // Verify verifies the signature under the stored public keys and message. 91 // Expected errors during normal operations: 92 // - model.InvalidSignerError if signerID is invalid (not a consensus participant) 93 // - model.ErrInvalidSignature if signerID is valid but signature is cryptographically invalid 94 // 95 // The function is thread-safe. 96 func (w *WeightedSignatureAggregator) Verify(signerID flow.Identifier, sig crypto.Signature) error { 97 info, ok := w.idToInfo[signerID] 98 if !ok { 99 return model.NewInvalidSignerErrorf("%v is not an authorized signer", signerID) 100 } 101 102 ok, err := w.aggregator.Verify(info.index, sig) // no error expected during normal operation 103 if err != nil { 104 return fmt.Errorf("couldn't verify signature from %s: %w", signerID, err) 105 } 106 if !ok { 107 return fmt.Errorf("invalid signature from %s: %w", signerID, model.ErrInvalidSignature) 108 } 109 return nil 110 } 111 112 // TrustedAdd adds a signature to the internal set of signatures and adds the signer's 113 // weight to the total collected weight, iff the signature is _not_ a duplicate. 114 // 115 // The total weight of all collected signatures (excluding duplicates) is returned regardless 116 // of any returned error. 117 // The function errors with: 118 // - model.InvalidSignerError if signerID is invalid (not a consensus participant) 119 // - model.DuplicatedSignerError if the signer has been already added 120 // 121 // The function is thread-safe. 122 func (w *WeightedSignatureAggregator) TrustedAdd(signerID flow.Identifier, sig crypto.Signature) (uint64, error) { 123 info, found := w.idToInfo[signerID] 124 if !found { 125 return w.TotalWeight(), model.NewInvalidSignerErrorf("%v is not an authorized signer", signerID) 126 } 127 128 // atomically update the signatures pool and the total weight 129 w.lock.Lock() 130 defer w.lock.Unlock() 131 132 // check for repeated occurrence of signerID (in anticipation of aggregator supporting multiplicities larger than 1 in the future) 133 if _, duplicate := w.collectedIDs[signerID]; duplicate { 134 return w.totalWeight, model.NewDuplicatedSignerErrorf("signature from %v was already added", signerID) 135 } 136 137 err := w.aggregator.TrustedAdd(info.index, sig) 138 if err != nil { 139 // During normal operations, signature.InvalidSignerIdxError or signature.DuplicatedSignerIdxError should never occur. 140 return w.totalWeight, fmt.Errorf("unexpected exception while trusted add of signature from %v: %w", signerID, err) 141 } 142 w.totalWeight += info.weight 143 w.collectedIDs[signerID] = struct{}{} 144 145 return w.totalWeight, nil 146 } 147 148 // TotalWeight returns the total weight presented by the collected signatures. 149 // The function is thread-safe 150 func (w *WeightedSignatureAggregator) TotalWeight() uint64 { 151 w.lock.RLock() 152 defer w.lock.RUnlock() 153 return w.totalWeight 154 } 155 156 // Aggregate aggregates the signatures and returns the aggregated signature. 157 // The function performs a final verification and errors if the aggregated signature is invalid. This is 158 // required for the function safety since `TrustedAdd` allows adding invalid signatures. 159 // The function errors with: 160 // - model.InsufficientSignaturesError if no signatures have been added yet 161 // - model.InvalidSignatureIncludedError if: 162 // - some signature(s), included via TrustedAdd, fail to deserialize (regardless of the aggregated public key) 163 // -- or all signatures deserialize correctly but some signature(s), included via TrustedAdd, are 164 // invalid (while aggregated public key is valid) 165 // -- model.InvalidAggregatedKeyError if all signatures deserialize correctly but the signer's 166 // staking public keys sum up to an invalid key (BLS identity public key). 167 // Any aggregated signature would fail the cryptographic verification under the identity public 168 // key and therefore such signature is considered invalid. Such scenario can only happen if 169 // staking public keys of signers were forged to add up to the identity public key. 170 // Under the assumption that all staking key PoPs are valid, this error case can only 171 // happen if all signers are malicious and colluding. If there is at least one honest signer, 172 // there is a negligible probability that the aggregated key is identity. 173 // 174 // The function is thread-safe. 175 func (w *WeightedSignatureAggregator) Aggregate() (flow.IdentifierList, []byte, error) { 176 w.lock.Lock() 177 defer w.lock.Unlock() 178 179 // Aggregate includes the safety check of the aggregated signature 180 indices, aggSignature, err := w.aggregator.Aggregate() 181 if err != nil { 182 if signature.IsInsufficientSignaturesError(err) { 183 return nil, nil, model.NewInsufficientSignaturesError(err) 184 } 185 if errors.Is(err, signature.ErrIdentityPublicKey) { 186 return nil, nil, model.NewInvalidAggregatedKeyError(err) 187 } 188 if signature.IsInvalidSignatureIncludedError(err) { 189 return nil, nil, model.NewInvalidSignatureIncludedError(err) 190 } 191 return nil, nil, fmt.Errorf("unexpected error during signature aggregation: %w", err) 192 } 193 signerIDs := make([]flow.Identifier, 0, len(indices)) 194 for _, index := range indices { 195 signerIDs = append(signerIDs, w.ids[index].NodeID) 196 } 197 198 return signerIDs, aggSignature, nil 199 }