-
Notifications
You must be signed in to change notification settings - Fork 2
/
mask.go
326 lines (294 loc) · 8.96 KB
/
mask.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
package bls
import (
"github.com/PositionExchange/bls/ffi/go/bls"
lru "github.com/hashicorp/golang-lru"
"github.com/pkg/errors"
)
const (
blsPubKeyCacheSize = 1024
)
var (
// BLSPubKeyCache is the Cache of the Deserialized BLS PubKey
BLSPubKeyCache, _ = lru.New(blsPubKeyCacheSize)
)
func init() {
bls.Init(bls.BLS12_381)
}
// RandPrivateKey returns a random private key.
func RandPrivateKey() *bls.SecretKey {
sec := bls.SecretKey{}
sec.SetByCSPRNG()
return &sec
}
var (
errEmptyInput = errors.New("BytesToBLSPublicKey: empty input")
errPubKeyCast = errors.New("BytesToBLSPublicKey: cast error")
)
// BytesToBLSPublicKey converts bytes into bls.PublicKey pointer.
func BytesToBLSPublicKey(bytes []byte) (*bls.PublicKey, error) {
if len(bytes) == 0 {
return nil, errEmptyInput
}
kkey := string(bytes)
if k, ok := BLSPubKeyCache.Get(kkey); ok {
if pk, ok := k.(bls.PublicKey); ok {
return &pk, nil
}
return nil, errPubKeyCast
}
pubKey := &bls.PublicKey{}
err := pubKey.Deserialize(bytes)
if err == nil {
BLSPubKeyCache.Add(kkey, *pubKey)
return pubKey, nil
}
return nil, err
}
// AggregateSig aggregates all the BLS signature into a single multi-signature.
func AggregateSig(sigs []*bls.Sign) *bls.Sign {
var aggregatedSig bls.Sign
for _, sig := range sigs {
aggregatedSig.Add(sig)
}
return &aggregatedSig
}
// Mask represents a cosigning participation bitmask.
type Mask struct {
Bitmap []byte
Publics []*PublicKeyWrapper
PublicsIndex map[SerializedPublicKey]int
AggregatePublic *bls.PublicKey
}
// NewMask returns a new participation bitmask for cosigning where all
// cosigners are disabled by default. If a public key is given it verifies that
// it is present in the list of keys and sets the corresponding index in the
// bitmask to 1 (enabled).
func NewMask(publics []PublicKeyWrapper, myKey *PublicKeyWrapper) (*Mask, error) {
index := map[SerializedPublicKey]int{}
publicKeys := make([]*PublicKeyWrapper, len(publics))
for i, key := range publics {
publicKeys[i] = &publics[i]
index[key.Bytes] = i
}
m := &Mask{
Publics: publicKeys,
PublicsIndex: index,
}
m.Bitmap = make([]byte, m.Len())
m.AggregatePublic = &bls.PublicKey{}
if myKey != nil {
i, found := m.PublicsIndex[myKey.Bytes]
if found {
m.SetBit(i, true)
found = true
}
if !found {
return nil, errors.New("key not found")
}
}
return m, nil
}
// Clear clears the existing bits and aggregate public keys.
func (m *Mask) Clear() {
m.Bitmap = make([]byte, m.Len())
m.AggregatePublic = &bls.PublicKey{}
}
// Mask returns a copy of the participation bitmask.
func (m *Mask) Mask() []byte {
clone := make([]byte, len(m.Bitmap))
copy(clone[:], m.Bitmap)
return clone
}
// Len returns the Bitmap length in bytes.
func (m *Mask) Len() int {
return (len(m.Publics) + 7) >> 3
}
// SetMask sets the participation bitmask according to the given byte slice
// interpreted in little-endian order, i.e., bits 0-7 of byte 0 correspond to
// cosigners 0-7, bits 0-7 of byte 1 correspond to cosigners 8-15, etc.
func (m *Mask) SetMask(mask []byte) error {
if m.Len() != len(mask) {
return errors.Errorf(
"mismatching bitmap lengths expectedBitmapLength %d providedBitmapLength %d",
m.Len(),
len(mask),
)
}
for i := range m.Publics {
byt := i >> 3
msk := byte(1) << uint(i&7)
if ((m.Bitmap[byt] & msk) == 0) && ((mask[byt] & msk) != 0) {
m.Bitmap[byt] ^= msk // flip bit in Bitmap from 0 to 1
m.AggregatePublic.Add(m.Publics[i].Object)
}
if ((m.Bitmap[byt] & msk) != 0) && ((mask[byt] & msk) == 0) {
m.Bitmap[byt] ^= msk // flip bit in Bitmap from 1 to 0
m.AggregatePublic.Sub(m.Publics[i].Object)
}
}
return nil
}
// SetBit enables (enable: true) or disables (enable: false) the bit
// in the participation Bitmap of the given cosigner.
func (m *Mask) SetBit(i int, enable bool) error {
if i >= len(m.Publics) {
return errors.New("index out of range")
}
byt := i >> 3
msk := byte(1) << uint(i&7)
if ((m.Bitmap[byt] & msk) == 0) && enable {
m.Bitmap[byt] ^= msk // flip bit in Bitmap from 0 to 1
m.AggregatePublic.Add(m.Publics[i].Object)
}
if ((m.Bitmap[byt] & msk) != 0) && !enable {
m.Bitmap[byt] ^= msk // flip bit in Bitmap from 1 to 0
m.AggregatePublic.Sub(m.Publics[i].Object)
}
return nil
}
// GetPubKeyFromMask will return pubkeys which masked either zero or one depending on the flag
// it is used to show which signers are signed or not in the cosign message
func (m *Mask) GetPubKeyFromMask(flag bool) []*bls.PublicKey {
pubKeys := []*bls.PublicKey{}
for i := range m.Publics {
byt := i >> 3
msk := byte(1) << uint(i&7)
if flag {
if (m.Bitmap[byt] & msk) != 0 {
pubKeys = append(pubKeys, m.Publics[i].Object)
}
} else {
if (m.Bitmap[byt] & msk) == 0 {
pubKeys = append(pubKeys, m.Publics[i].Object)
}
}
}
return pubKeys
}
// GetSignedPubKeysFromBitmap will return pubkeys that are signed based on the specified bitmap.
func (m *Mask) GetSignedPubKeysFromBitmap(bitmap []byte) ([]*PublicKeyWrapper, error) {
if m.Len() != len(bitmap) {
return nil, errors.Errorf(
"mismatching bitmap lengths expectedBitmapLength %d providedBitmapLength %d",
m.Len(),
len(bitmap),
)
}
pubKeys := []*PublicKeyWrapper{}
// For details about who bitmap is structured, refer to func SetMask
for i := range m.Publics {
byt := i >> 3
msk := byte(1) << uint(i&7)
if (bitmap[byt] & msk) != 0 {
pubKeys = append(pubKeys, m.Publics[i])
}
}
return pubKeys, nil
}
// IndexEnabled checks whether the given index is enabled in the Bitmap or not.
func (m *Mask) IndexEnabled(i int) (bool, error) {
if i >= len(m.Publics) {
return false, errors.New("index out of range")
}
byt := i >> 3
msk := byte(1) << uint(i&7)
return ((m.Bitmap[byt] & msk) != 0), nil
}
// KeyEnabled checks whether the index, corresponding to the given key, is
// enabled in the Bitmap or not.
func (m *Mask) KeyEnabled(public SerializedPublicKey) (bool, error) {
i, found := m.PublicsIndex[public]
if found {
return m.IndexEnabled(i)
}
return false, errors.New("key not found")
}
// SetKey set the bit in the Bitmap for the given cosigner
func (m *Mask) SetKey(public SerializedPublicKey, enable bool) error {
i, found := m.PublicsIndex[public]
if found {
return m.SetBit(i, enable)
}
return errors.New("key not found")
}
// SetKeysAtomic set the bit in the Bitmap for the given cosigners only when all the cosigners are present in the map.
func (m *Mask) SetKeysAtomic(publics []*PublicKeyWrapper, enable bool) error {
indexes := make([]int, len(publics))
for i, key := range publics {
index, found := m.PublicsIndex[key.Bytes]
if !found {
return errors.New("key not found")
}
indexes[i] = index
}
for _, index := range indexes {
err := m.SetBit(index, enable)
if err != nil {
return err
}
}
return nil
}
// CountEnabled returns the number of enabled nodes in the CoSi participation
// Bitmap.
func (m *Mask) CountEnabled() int {
// hw is hamming weight
hw := 0
for i := range m.Publics {
byt := i >> 3
msk := byte(1) << uint(i&7)
if (m.Bitmap[byt] & msk) != 0 {
hw++
}
}
return hw
}
// CountTotal returns the total number of nodes this CoSi instance knows.
func (m *Mask) CountTotal() int {
return len(m.Publics)
}
// AggregateMasks computes the bitwise OR of the two given participation masks.
func AggregateMasks(a, b []byte) ([]byte, error) {
if len(a) != len(b) {
return nil, errors.New("mismatching Bitmap lengths")
}
m := make([]byte, len(a))
for i := range m {
m[i] = a[i] | b[i]
}
return m, nil
}
// Policy represents a fully customizable cosigning policy deciding what
// cosigner sets are and aren't sufficient for a collective signature to be
// considered acceptable to a verifier. The Check method may inspect the set of
// participants that cosigned by invoking cosi.Mask and/or cosi.MaskBit, and may
// use any other relevant contextual information (e.g., how security-critical
// the operation relying on the collective signature is) in determining whether
// the collective signature was produced by an acceptable set of cosigners.
type Policy interface {
Check(m *Mask) bool
}
// CompletePolicy is the default policy requiring that all participants have
// cosigned to make a collective signature valid.
type CompletePolicy struct {
}
// Check verifies that all participants have contributed to a collective
// signature.
func (p CompletePolicy) Check(m *Mask) bool {
return m.CountEnabled() == m.CountTotal()
}
// ThresholdPolicy allows to specify a simple t-of-n policy requring that at
// least the given threshold number of participants t have cosigned to make a
// collective signature valid.
type ThresholdPolicy struct {
thold int
}
// NewThresholdPolicy returns a new ThresholdPolicy with the given threshold.
func NewThresholdPolicy(thold int) *ThresholdPolicy {
return &ThresholdPolicy{thold: thold}
}
// Check verifies that at least a threshold number of participants have
// contributed to a collective signature.
func (p ThresholdPolicy) Check(m *Mask) bool {
return m.CountEnabled() >= p.thold
}