aboutsummaryrefslogtreecommitdiffstats
path: root/vendor/github.com/tangerine-network/tangerine-consensus/core/types/dkg/dkg.go
blob: bc1b19e94a880fd966b3f742e92f6f6b297a1361 (plain) (blame)
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
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
// Copyright 2018 The dexon-consensus Authors
// This file is part of the dexon-consensus library.
//
// The dexon-consensus library is free software: you can redistribute it
// and/or modify it under the terms of the GNU Lesser General Public License as
// published by the Free Software Foundation, either version 3 of the License,
// or (at your option) any later version.
//
// The dexon-consensus library is distributed in the hope that it will be
// useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser
// General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with the dexon-consensus library. If not, see
// <http://www.gnu.org/licenses/>.

package dkg

import (
    "bytes"
    "encoding/json"
    "fmt"
    "io"

    "github.com/tangerine-network/go-tangerine/rlp"

    "github.com/tangerine-network/tangerine-consensus/common"
    "github.com/tangerine-network/tangerine-consensus/core/crypto"
    cryptoDKG "github.com/tangerine-network/tangerine-consensus/core/crypto/dkg"
    "github.com/tangerine-network/tangerine-consensus/core/types"
)

// Errors for typesDKG package.
var (
    ErrNotReachThreshold = fmt.Errorf("threshold not reach")
    ErrInvalidThreshold  = fmt.Errorf("invalid threshold")
)

// NewID creates a DKGID from NodeID.
func NewID(ID types.NodeID) cryptoDKG.ID {
    return cryptoDKG.NewID(ID.Hash[:])
}

// PrivateShare describe a secret share in DKG protocol.
type PrivateShare struct {
    ProposerID   types.NodeID         `json:"proposer_id"`
    ReceiverID   types.NodeID         `json:"receiver_id"`
    Round        uint64               `json:"round"`
    Reset        uint64               `json:"reset"`
    PrivateShare cryptoDKG.PrivateKey `json:"private_share"`
    Signature    crypto.Signature     `json:"signature"`
}

// Equal checks equality between two PrivateShare instances.
func (p *PrivateShare) Equal(other *PrivateShare) bool {
    return p.ProposerID.Equal(other.ProposerID) &&
        p.ReceiverID.Equal(other.ReceiverID) &&
        p.Round == other.Round &&
        p.Reset == other.Reset &&
        p.Signature.Type == other.Signature.Type &&
        bytes.Compare(p.Signature.Signature, other.Signature.Signature) == 0 &&
        bytes.Compare(
            p.PrivateShare.Bytes(), other.PrivateShare.Bytes()) == 0
}

// MasterPublicKey decrtibe a master public key in DKG protocol.
type MasterPublicKey struct {
    ProposerID      types.NodeID              `json:"proposer_id"`
    Round           uint64                    `json:"round"`
    Reset           uint64                    `json:"reset"`
    DKGID           cryptoDKG.ID              `json:"dkg_id"`
    PublicKeyShares cryptoDKG.PublicKeyShares `json:"public_key_shares"`
    Signature       crypto.Signature          `json:"signature"`
}

func (d *MasterPublicKey) String() string {
    return fmt.Sprintf("MasterPublicKey{KP:%s Round:%d Reset:%d}",
        d.ProposerID.String()[:6],
        d.Round,
        d.Reset)
}

// Equal check equality of two DKG master public keys.
func (d *MasterPublicKey) Equal(other *MasterPublicKey) bool {
    return d.ProposerID.Equal(other.ProposerID) &&
        d.Round == other.Round &&
        d.Reset == other.Reset &&
        d.DKGID.GetHexString() == other.DKGID.GetHexString() &&
        d.PublicKeyShares.Equal(&other.PublicKeyShares) &&
        d.Signature.Type == other.Signature.Type &&
        bytes.Compare(d.Signature.Signature, other.Signature.Signature) == 0
}

type rlpMasterPublicKey struct {
    ProposerID      types.NodeID
    Round           uint64
    Reset           uint64
    DKGID           []byte
    PublicKeyShares *cryptoDKG.PublicKeyShares
    Signature       crypto.Signature
}

// EncodeRLP implements rlp.Encoder
func (d *MasterPublicKey) EncodeRLP(w io.Writer) error {
    return rlp.Encode(w, rlpMasterPublicKey{
        ProposerID:      d.ProposerID,
        Round:           d.Round,
        Reset:           d.Reset,
        DKGID:           d.DKGID.GetLittleEndian(),
        PublicKeyShares: &d.PublicKeyShares,
        Signature:       d.Signature,
    })
}

// DecodeRLP implements rlp.Decoder
func (d *MasterPublicKey) DecodeRLP(s *rlp.Stream) error {
    var dec rlpMasterPublicKey
    if err := s.Decode(&dec); err != nil {
        return err
    }

    id, err := cryptoDKG.BytesID(dec.DKGID)
    if err != nil {
        return err
    }

    *d = MasterPublicKey{
        ProposerID:      dec.ProposerID,
        Round:           dec.Round,
        Reset:           dec.Reset,
        DKGID:           id,
        PublicKeyShares: *dec.PublicKeyShares.Move(),
        Signature:       dec.Signature,
    }
    return err
}

// NewMasterPublicKey returns a new MasterPublicKey instance.
func NewMasterPublicKey() *MasterPublicKey {
    return &MasterPublicKey{
        PublicKeyShares: *cryptoDKG.NewEmptyPublicKeyShares(),
    }
}

// UnmarshalJSON implements json.Unmarshaller.
func (d *MasterPublicKey) UnmarshalJSON(data []byte) error {
    type innertMasterPublicKey MasterPublicKey
    d.PublicKeyShares = *cryptoDKG.NewEmptyPublicKeyShares()
    return json.Unmarshal(data, (*innertMasterPublicKey)(d))
}

// Complaint describe a complaint in DKG protocol.
type Complaint struct {
    ProposerID   types.NodeID     `json:"proposer_id"`
    Round        uint64           `json:"round"`
    Reset        uint64           `json:"reset"`
    PrivateShare PrivateShare     `json:"private_share"`
    Signature    crypto.Signature `json:"signature"`
}

func (c *Complaint) String() string {
    if c.IsNack() {
        return fmt.Sprintf("DKGNackComplaint{CP:%s Round:%d Reset %d PSP:%s}",
            c.ProposerID.String()[:6], c.Round, c.Reset,
            c.PrivateShare.ProposerID.String()[:6])
    }
    return fmt.Sprintf("DKGComplaint{CP:%s Round:%d Reset %d PrivateShare:%v}",
        c.ProposerID.String()[:6], c.Round, c.Reset, c.PrivateShare)
}

// Equal checks equality between two Complaint instances.
func (c *Complaint) Equal(other *Complaint) bool {
    return c.ProposerID.Equal(other.ProposerID) &&
        c.Round == other.Round &&
        c.Reset == other.Reset &&
        c.PrivateShare.Equal(&other.PrivateShare) &&
        c.Signature.Type == other.Signature.Type &&
        bytes.Compare(c.Signature.Signature, other.Signature.Signature) == 0
}

type rlpComplaint struct {
    ProposerID   types.NodeID
    Round        uint64
    Reset        uint64
    IsNack       bool
    PrivateShare []byte
    Signature    crypto.Signature
}

// EncodeRLP implements rlp.Encoder
func (c *Complaint) EncodeRLP(w io.Writer) error {
    if c.IsNack() {
        return rlp.Encode(w, rlpComplaint{
            ProposerID:   c.ProposerID,
            Round:        c.Round,
            Reset:        c.Reset,
            IsNack:       true,
            PrivateShare: c.PrivateShare.ProposerID.Hash[:],
            Signature:    c.Signature,
        })
    }
    prvShare, err := rlp.EncodeToBytes(&c.PrivateShare)
    if err != nil {
        return err
    }
    return rlp.Encode(w, rlpComplaint{
        ProposerID:   c.ProposerID,
        Round:        c.Round,
        Reset:        c.Reset,
        IsNack:       false,
        PrivateShare: prvShare,
        Signature:    c.Signature,
    })
}

// DecodeRLP implements rlp.Decoder
func (c *Complaint) DecodeRLP(s *rlp.Stream) error {
    var dec rlpComplaint
    if err := s.Decode(&dec); err != nil {
        return err
    }

    var prvShare PrivateShare
    if dec.IsNack {
        copy(prvShare.ProposerID.Hash[:], dec.PrivateShare)
        prvShare.Round = dec.Round
        prvShare.Reset = dec.Reset
    } else {
        if err := rlp.DecodeBytes(dec.PrivateShare, &prvShare); err != nil {
            return err
        }
    }

    *c = Complaint{
        ProposerID:   dec.ProposerID,
        Round:        dec.Round,
        Reset:        dec.Reset,
        PrivateShare: prvShare,
        Signature:    dec.Signature,
    }
    return nil
}

// IsNack returns true if it's a nack complaint in DKG protocol.
func (c *Complaint) IsNack() bool {
    return len(c.PrivateShare.Signature.Signature) == 0
}

// PartialSignature describe a partial signature in DKG protocol.
type PartialSignature struct {
    ProposerID       types.NodeID               `json:"proposer_id"`
    Round            uint64                     `json:"round"`
    Hash             common.Hash                `json:"hash"`
    PartialSignature cryptoDKG.PartialSignature `json:"partial_signature"`
    Signature        crypto.Signature           `json:"signature"`
}

// MPKReady describe a dkg ready message in DKG protocol.
type MPKReady struct {
    ProposerID types.NodeID     `json:"proposer_id"`
    Round      uint64           `json:"round"`
    Reset      uint64           `json:"reset"`
    Signature  crypto.Signature `json:"signature"`
}

func (ready *MPKReady) String() string {
    return fmt.Sprintf("DKGMPKReady{RP:%s Round:%d Reset:%d}",
        ready.ProposerID.String()[:6],
        ready.Round,
        ready.Reset)
}

// Equal check equality of two MPKReady instances.
func (ready *MPKReady) Equal(other *MPKReady) bool {
    return ready.ProposerID.Equal(other.ProposerID) &&
        ready.Round == other.Round &&
        ready.Reset == other.Reset &&
        ready.Signature.Type == other.Signature.Type &&
        bytes.Compare(ready.Signature.Signature, other.Signature.Signature) == 0
}

// Finalize describe a dkg finalize message in DKG protocol.
type Finalize struct {
    ProposerID types.NodeID     `json:"proposer_id"`
    Round      uint64           `json:"round"`
    Reset      uint64           `json:"reset"`
    Signature  crypto.Signature `json:"signature"`
}

func (final *Finalize) String() string {
    return fmt.Sprintf("DKGFinal{FP:%s Round:%d Reset:%d}",
        final.ProposerID.String()[:6],
        final.Round,
        final.Reset)
}

// Equal check equality of two Finalize instances.
func (final *Finalize) Equal(other *Finalize) bool {
    return final.ProposerID.Equal(other.ProposerID) &&
        final.Round == other.Round &&
        final.Reset == other.Reset &&
        final.Signature.Type == other.Signature.Type &&
        bytes.Compare(final.Signature.Signature, other.Signature.Signature) == 0
}

// Success describe a dkg success message in DKG protocol.
type Success struct {
    ProposerID types.NodeID     `json:"proposer_id"`
    Round      uint64           `json:"round"`
    Reset      uint64           `json:"reset"`
    Signature  crypto.Signature `json:"signature"`
}

func (s *Success) String() string {
    return fmt.Sprintf("DKGSuccess{SP:%s Round:%d Reset:%d}",
        s.ProposerID.String()[:6],
        s.Round,
        s.Reset)
}

// Equal check equality of two Success instances.
func (s *Success) Equal(other *Success) bool {
    return s.ProposerID.Equal(other.ProposerID) &&
        s.Round == other.Round &&
        s.Reset == other.Reset &&
        s.Signature.Type == other.Signature.Type &&
        bytes.Compare(s.Signature.Signature, other.Signature.Signature) == 0
}

// GroupPublicKey is the result of DKG protocol.
type GroupPublicKey struct {
    Round          uint64
    QualifyIDs     cryptoDKG.IDs
    QualifyNodeIDs map[types.NodeID]struct{}
    IDMap          map[types.NodeID]cryptoDKG.ID
    GroupPublicKey *cryptoDKG.PublicKey
    Threshold      int
}

// VerifySignature verifies if the signature is correct.
func (gpk *GroupPublicKey) VerifySignature(
    hash common.Hash, sig crypto.Signature) bool {
    return gpk.GroupPublicKey.VerifySignature(hash, sig)
}

// CalcQualifyNodes returns the qualified nodes.
func CalcQualifyNodes(
    mpks []*MasterPublicKey, complaints []*Complaint, threshold int) (
    qualifyIDs cryptoDKG.IDs, qualifyNodeIDs map[types.NodeID]struct{}, err error) {
    if len(mpks) < threshold {
        err = ErrInvalidThreshold
        return
    }

    // Calculate qualify members.
    disqualifyIDs := map[types.NodeID]struct{}{}
    complaintsByID := map[types.NodeID]map[types.NodeID]struct{}{}
    for _, complaint := range complaints {
        if complaint.IsNack() {
            if _, exist := complaintsByID[complaint.PrivateShare.ProposerID]; !exist {
                complaintsByID[complaint.PrivateShare.ProposerID] =
                    make(map[types.NodeID]struct{})
            }
            complaintsByID[complaint.PrivateShare.ProposerID][complaint.ProposerID] =
                struct{}{}
        } else {
            disqualifyIDs[complaint.PrivateShare.ProposerID] = struct{}{}
        }
    }
    for nID, complaints := range complaintsByID {
        if len(complaints) >= threshold {
            disqualifyIDs[nID] = struct{}{}
        }
    }
    qualifyIDs = make(cryptoDKG.IDs, 0, len(mpks)-len(disqualifyIDs))
    if cap(qualifyIDs) < threshold {
        err = ErrNotReachThreshold
        return
    }
    qualifyNodeIDs = make(map[types.NodeID]struct{})
    for _, mpk := range mpks {
        if _, exist := disqualifyIDs[mpk.ProposerID]; exist {
            continue
        }
        qualifyIDs = append(qualifyIDs, mpk.DKGID)
        qualifyNodeIDs[mpk.ProposerID] = struct{}{}
    }
    return
}

// NewGroupPublicKey creats a GroupPublicKey instance.
func NewGroupPublicKey(
    round uint64,
    mpks []*MasterPublicKey, complaints []*Complaint,
    threshold int) (
    *GroupPublicKey, error) {
    qualifyIDs, qualifyNodeIDs, err :=
        CalcQualifyNodes(mpks, complaints, threshold)
    if err != nil {
        return nil, err
    }
    mpkMap := make(map[cryptoDKG.ID]*MasterPublicKey, cap(qualifyIDs))
    idMap := make(map[types.NodeID]cryptoDKG.ID)
    for _, mpk := range mpks {
        if _, exist := qualifyNodeIDs[mpk.ProposerID]; !exist {
            continue
        }
        mpkMap[mpk.DKGID] = mpk
        idMap[mpk.ProposerID] = mpk.DKGID
    }
    // Recover Group Public Key.
    pubShares := make([]*cryptoDKG.PublicKeyShares, 0, len(qualifyIDs))
    for _, id := range qualifyIDs {
        pubShares = append(pubShares, &mpkMap[id].PublicKeyShares)
    }
    groupPK := cryptoDKG.RecoverGroupPublicKey(pubShares)
    return &GroupPublicKey{
        Round:          round,
        QualifyIDs:     qualifyIDs,
        QualifyNodeIDs: qualifyNodeIDs,
        IDMap:          idMap,
        Threshold:      threshold,
        GroupPublicKey: groupPK,
    }, nil
}

// NodePublicKeys is the result of DKG protocol.
type NodePublicKeys struct {
    Round          uint64
    QualifyIDs     cryptoDKG.IDs
    QualifyNodeIDs map[types.NodeID]struct{}
    IDMap          map[types.NodeID]cryptoDKG.ID
    PublicKeys     map[types.NodeID]*cryptoDKG.PublicKey
    Threshold      int
}

// NewNodePublicKeys creats a NodePublicKeys instance.
func NewNodePublicKeys(
    round uint64,
    mpks []*MasterPublicKey, complaints []*Complaint,
    threshold int) (
    *NodePublicKeys, error) {
    qualifyIDs, qualifyNodeIDs, err :=
        CalcQualifyNodes(mpks, complaints, threshold)
    if err != nil {
        return nil, err
    }
    mpkMap := make(map[cryptoDKG.ID]*MasterPublicKey, cap(qualifyIDs))
    idMap := make(map[types.NodeID]cryptoDKG.ID)
    for _, mpk := range mpks {
        if _, exist := qualifyNodeIDs[mpk.ProposerID]; !exist {
            continue
        }
        mpkMap[mpk.DKGID] = mpk
        idMap[mpk.ProposerID] = mpk.DKGID
    }
    // Recover qualify members' public key.
    pubKeys := make(map[types.NodeID]*cryptoDKG.PublicKey, len(qualifyIDs))
    for _, recvID := range qualifyIDs {
        pubShares := cryptoDKG.NewEmptyPublicKeyShares()
        for _, id := range qualifyIDs {
            pubShare, err := mpkMap[id].PublicKeyShares.Share(recvID)
            if err != nil {
                return nil, err
            }
            if err := pubShares.AddShare(id, pubShare); err != nil {
                return nil, err
            }
        }
        pubKey, err := pubShares.RecoverPublicKey(qualifyIDs)
        if err != nil {
            return nil, err
        }
        pubKeys[mpkMap[recvID].ProposerID] = pubKey
    }
    return &NodePublicKeys{
        Round:          round,
        QualifyIDs:     qualifyIDs,
        QualifyNodeIDs: qualifyNodeIDs,
        IDMap:          idMap,
        PublicKeys:     pubKeys,
        Threshold:      threshold,
    }, nil
}