aboutsummaryrefslogtreecommitdiffstats
path: root/core/dkg-tsig-protocol.go
blob: 492271e98b09212244420525151f644aaecea10f (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
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
// 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 core

import (
    "fmt"
    "sync"

    "github.com/dexon-foundation/dexon-consensus/common"
    "github.com/dexon-foundation/dexon-consensus/core/crypto"
    "github.com/dexon-foundation/dexon-consensus/core/crypto/dkg"
    "github.com/dexon-foundation/dexon-consensus/core/types"
    typesDKG "github.com/dexon-foundation/dexon-consensus/core/types/dkg"
    "github.com/dexon-foundation/dexon-consensus/core/utils"
)

// Errors for dkg module.
var (
    ErrNotDKGParticipant = fmt.Errorf(
        "not a DKG participant")
    ErrNotQualifyDKGParticipant = fmt.Errorf(
        "not a qualified DKG participant")
    ErrIDShareNotFound = fmt.Errorf(
        "private share not found for specific ID")
    ErrNotReachThreshold = fmt.Errorf(
        "threshold not reach")
    ErrInvalidThreshold = fmt.Errorf(
        "invalid threshold")
    ErrIncorrectPrivateShareSignature = fmt.Errorf(
        "incorrect private share signature")
    ErrMismatchPartialSignatureHash = fmt.Errorf(
        "mismatch partialSignature hash")
    ErrIncorrectPartialSignatureSignature = fmt.Errorf(
        "incorrect partialSignature signature")
    ErrIncorrectPartialSignature = fmt.Errorf(
        "incorrect partialSignature")
    ErrNotEnoughtPartialSignatures = fmt.Errorf(
        "not enough of partial signatures")
    ErrRoundAlreadyPurged = fmt.Errorf(
        "cache of round already been purged")
)

type dkgReceiver interface {
    // ProposeDKGComplaint proposes a DKGComplaint.
    ProposeDKGComplaint(complaint *typesDKG.Complaint)

    // ProposeDKGMasterPublicKey propose a DKGMasterPublicKey.
    ProposeDKGMasterPublicKey(mpk *typesDKG.MasterPublicKey)

    // ProposeDKGPrivateShare propose a DKGPrivateShare.
    ProposeDKGPrivateShare(prv *typesDKG.PrivateShare)

    // ProposeDKGAntiNackComplaint propose a DKGPrivateShare as an anti complaint.
    ProposeDKGAntiNackComplaint(prv *typesDKG.PrivateShare)

    // ProposeDKGMPKReady propose a DKGMPKReady message.
    ProposeDKGMPKReady(ready *typesDKG.MPKReady)

    // ProposeDKGFinalize propose a DKGFinalize message.
    ProposeDKGFinalize(final *typesDKG.Finalize)
}

type dkgProtocol struct {
    ID                 types.NodeID
    recv               dkgReceiver
    round              uint64
    threshold          int
    idMap              map[types.NodeID]dkg.ID
    mpkMap             map[types.NodeID]*dkg.PublicKeyShares
    masterPrivateShare *dkg.PrivateKeyShares
    prvShares          *dkg.PrivateKeyShares
    prvSharesReceived  map[types.NodeID]struct{}
    nodeComplained     map[types.NodeID]struct{}
    // Complaint[from][to]'s anti is saved to antiComplaint[from][to].
    antiComplaintReceived map[types.NodeID]map[types.NodeID]struct{}
}

type dkgShareSecret struct {
    privateKey *dkg.PrivateKey
}

// DKGGroupPublicKey is the result of DKG protocol.
type DKGGroupPublicKey struct {
    round          uint64
    qualifyIDs     dkg.IDs
    qualifyNodeIDs map[types.NodeID]struct{}
    idMap          map[types.NodeID]dkg.ID
    publicKeys     map[types.NodeID]*dkg.PublicKey
    groupPublicKey *dkg.PublicKey
    threshold      int
}

// TSigVerifier is the interface verifying threshold signature.
type TSigVerifier interface {
    VerifySignature(hash common.Hash, sig crypto.Signature) bool
}

// TSigVerifierCacheInterface specifies interface used by TSigVerifierCache.
type TSigVerifierCacheInterface interface {
    // Configuration returns the configuration at a given round.
    // Return the genesis configuration if round == 0.
    Configuration(round uint64) *types.Config

    // DKGComplaints gets all the DKGComplaints of round.
    DKGComplaints(round uint64) []*typesDKG.Complaint

    // DKGMasterPublicKeys gets all the DKGMasterPublicKey of round.
    DKGMasterPublicKeys(round uint64) []*typesDKG.MasterPublicKey

    // IsDKGFinal checks if DKG is final.
    IsDKGFinal(round uint64) bool
}

// TSigVerifierCache is the cache for TSigVerifier.
type TSigVerifierCache struct {
    intf      TSigVerifierCacheInterface
    verifier  map[uint64]TSigVerifier
    minRound  uint64
    cacheSize int
    lock      sync.RWMutex
}

type tsigProtocol struct {
    groupPublicKey *DKGGroupPublicKey
    hash           common.Hash
    sigs           map[dkg.ID]dkg.PartialSignature
    threshold      int
}

func newDKGID(ID types.NodeID) dkg.ID {
    return dkg.NewID(ID.Hash[:])
}

func newDKGProtocol(
    ID types.NodeID,
    recv dkgReceiver,
    round uint64,
    threshold int) *dkgProtocol {

    prvShare, pubShare := dkg.NewPrivateKeyShares(threshold)

    recv.ProposeDKGMasterPublicKey(&typesDKG.MasterPublicKey{
        Round:           round,
        DKGID:           newDKGID(ID),
        PublicKeyShares: *pubShare,
    })

    return &dkgProtocol{
        ID:                    ID,
        recv:                  recv,
        round:                 round,
        threshold:             threshold,
        idMap:                 make(map[types.NodeID]dkg.ID),
        mpkMap:                make(map[types.NodeID]*dkg.PublicKeyShares),
        masterPrivateShare:    prvShare,
        prvShares:             dkg.NewEmptyPrivateKeyShares(),
        prvSharesReceived:     make(map[types.NodeID]struct{}),
        nodeComplained:        make(map[types.NodeID]struct{}),
        antiComplaintReceived: make(map[types.NodeID]map[types.NodeID]struct{}),
    }
}

func (d *dkgProtocol) processMasterPublicKeys(
    mpks []*typesDKG.MasterPublicKey) error {
    d.idMap = make(map[types.NodeID]dkg.ID, len(mpks))
    d.mpkMap = make(map[types.NodeID]*dkg.PublicKeyShares, len(mpks))
    d.prvSharesReceived = make(map[types.NodeID]struct{}, len(mpks))
    ids := make(dkg.IDs, len(mpks))
    for i := range mpks {
        nID := mpks[i].ProposerID
        d.idMap[nID] = mpks[i].DKGID
        d.mpkMap[nID] = &mpks[i].PublicKeyShares
        ids[i] = mpks[i].DKGID
    }
    d.masterPrivateShare.SetParticipants(ids)
    for _, mpk := range mpks {
        share, ok := d.masterPrivateShare.Share(mpk.DKGID)
        if !ok {
            return ErrIDShareNotFound
        }
        d.recv.ProposeDKGPrivateShare(&typesDKG.PrivateShare{
            ReceiverID:   mpk.ProposerID,
            Round:        d.round,
            PrivateShare: *share,
        })
    }
    return nil
}

func (d *dkgProtocol) proposeNackComplaints() {
    for nID := range d.mpkMap {
        if _, exist := d.prvSharesReceived[nID]; exist {
            continue
        }
        d.recv.ProposeDKGComplaint(&typesDKG.Complaint{
            Round: d.round,
            PrivateShare: typesDKG.PrivateShare{
                ProposerID: nID,
                Round:      d.round,
            },
        })
    }
}

func (d *dkgProtocol) processNackComplaints(complaints []*typesDKG.Complaint) (
    err error) {
    for _, complaint := range complaints {
        if !complaint.IsNack() {
            continue
        }
        if complaint.PrivateShare.ProposerID != d.ID {
            continue
        }
        id, exist := d.idMap[complaint.ProposerID]
        if !exist {
            err = ErrNotDKGParticipant
            continue
        }
        share, ok := d.masterPrivateShare.Share(id)
        if !ok {
            err = ErrIDShareNotFound
            continue
        }
        d.recv.ProposeDKGAntiNackComplaint(&typesDKG.PrivateShare{
            ReceiverID:   complaint.ProposerID,
            Round:        d.round,
            PrivateShare: *share,
        })
    }
    return
}

func (d *dkgProtocol) enforceNackComplaints(complaints []*typesDKG.Complaint) {
    for _, complaint := range complaints {
        if !complaint.IsNack() {
            continue
        }
        to := complaint.PrivateShare.ProposerID
        // Do not propose nack complaint to itself.
        if to == d.ID {
            continue
        }
        from := complaint.ProposerID
        // Nack complaint is already proposed.
        if from == d.ID {
            continue
        }
        if _, exist :=
            d.antiComplaintReceived[from][to]; !exist {
            d.recv.ProposeDKGComplaint(&typesDKG.Complaint{
                Round: d.round,
                PrivateShare: typesDKG.PrivateShare{
                    ProposerID: to,
                    Round:      d.round,
                },
            })
        }
    }
}

func (d *dkgProtocol) sanityCheck(prvShare *typesDKG.PrivateShare) error {
    if _, exist := d.idMap[prvShare.ProposerID]; !exist {
        return ErrNotDKGParticipant
    }
    ok, err := utils.VerifyDKGPrivateShareSignature(prvShare)
    if err != nil {
        return err
    }
    if !ok {
        return ErrIncorrectPrivateShareSignature
    }
    return nil
}

func (d *dkgProtocol) processPrivateShare(
    prvShare *typesDKG.PrivateShare) error {
    if d.round != prvShare.Round {
        return nil
    }
    receiverID, exist := d.idMap[prvShare.ReceiverID]
    // This node is not a DKG participant, ignore the private share.
    if !exist {
        return nil
    }
    if err := d.sanityCheck(prvShare); err != nil {
        return err
    }
    mpk := d.mpkMap[prvShare.ProposerID]
    ok, err := mpk.VerifyPrvShare(receiverID, &prvShare.PrivateShare)
    if err != nil {
        return err
    }
    if prvShare.ReceiverID == d.ID {
        d.prvSharesReceived[prvShare.ProposerID] = struct{}{}
    }
    if !ok {
        if _, exist := d.nodeComplained[prvShare.ProposerID]; exist {
            return nil
        }
        complaint := &typesDKG.Complaint{
            Round:        d.round,
            PrivateShare: *prvShare,
        }
        d.nodeComplained[prvShare.ProposerID] = struct{}{}
        d.recv.ProposeDKGComplaint(complaint)
    } else if prvShare.ReceiverID == d.ID {
        sender := d.idMap[prvShare.ProposerID]
        if err := d.prvShares.AddShare(sender, &prvShare.PrivateShare); err != nil {
            return err
        }
    } else {
        // The prvShare is an anti complaint.
        if _, exist := d.antiComplaintReceived[prvShare.ReceiverID]; !exist {
            d.antiComplaintReceived[prvShare.ReceiverID] =
                make(map[types.NodeID]struct{})
            d.recv.ProposeDKGAntiNackComplaint(prvShare)
        }
        d.antiComplaintReceived[prvShare.ReceiverID][prvShare.ProposerID] =
            struct{}{}
    }
    return nil
}

func (d *dkgProtocol) proposeMPKReady() {
    d.recv.ProposeDKGMPKReady(&typesDKG.MPKReady{
        ProposerID: d.ID,
        Round:      d.round,
    })
}

func (d *dkgProtocol) proposeFinalize() {
    d.recv.ProposeDKGFinalize(&typesDKG.Finalize{
        ProposerID: d.ID,
        Round:      d.round,
    })
}

func (d *dkgProtocol) recoverShareSecret(qualifyIDs dkg.IDs) (
    *dkgShareSecret, error) {
    if len(qualifyIDs) < d.threshold {
        return nil, ErrNotReachThreshold
    }
    prvKey, err := d.prvShares.RecoverPrivateKey(qualifyIDs)
    if err != nil {
        return nil, err
    }
    return &dkgShareSecret{
        privateKey: prvKey,
    }, nil
}

func (ss *dkgShareSecret) sign(hash common.Hash) dkg.PartialSignature {
    // DKG sign will always success.
    sig, _ := ss.privateKey.Sign(hash)
    return dkg.PartialSignature(sig)
}

// NewDKGGroupPublicKey creats a DKGGroupPublicKey instance.
func NewDKGGroupPublicKey(
    round uint64,
    mpks []*typesDKG.MasterPublicKey, complaints []*typesDKG.Complaint,
    threshold int) (
    *DKGGroupPublicKey, error) {

    if len(mpks) < threshold {
        return nil, ErrInvalidThreshold
    }

    // 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(dkg.IDs, 0, len(mpks)-len(disqualifyIDs))
    qualifyNodeIDs := make(map[types.NodeID]struct{})
    mpkMap := make(map[dkg.ID]*typesDKG.MasterPublicKey, cap(qualifyIDs))
    idMap := make(map[types.NodeID]dkg.ID)
    for _, mpk := range mpks {
        if _, exist := disqualifyIDs[mpk.ProposerID]; exist {
            continue
        }
        mpkMap[mpk.DKGID] = mpk
        idMap[mpk.ProposerID] = mpk.DKGID
        qualifyIDs = append(qualifyIDs, mpk.DKGID)
        qualifyNodeIDs[mpk.ProposerID] = struct{}{}
    }
    // Recover qualify members' public key.
    pubKeys := make(map[types.NodeID]*dkg.PublicKey, len(qualifyIDs))
    for _, recvID := range qualifyIDs {
        pubShares := dkg.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
    }
    // Recover Group Public Key.
    pubShares := make([]*dkg.PublicKeyShares, 0, len(qualifyIDs))
    for _, id := range qualifyIDs {
        pubShares = append(pubShares, &mpkMap[id].PublicKeyShares)
    }
    groupPK := dkg.RecoverGroupPublicKey(pubShares)
    return &DKGGroupPublicKey{
        round:          round,
        qualifyIDs:     qualifyIDs,
        qualifyNodeIDs: qualifyNodeIDs,
        idMap:          idMap,
        publicKeys:     pubKeys,
        threshold:      threshold,
        groupPublicKey: groupPK,
    }, nil
}

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

// NewTSigVerifierCache creats a DKGGroupPublicKey instance.
func NewTSigVerifierCache(
    intf TSigVerifierCacheInterface, cacheSize int) *TSigVerifierCache {
    return &TSigVerifierCache{
        intf:      intf,
        verifier:  make(map[uint64]TSigVerifier),
        cacheSize: cacheSize,
    }
}

// UpdateAndGet calls Update and then Get.
func (tc *TSigVerifierCache) UpdateAndGet(round uint64) (
    TSigVerifier, bool, error) {
    ok, err := tc.Update(round)
    if err != nil {
        return nil, false, err
    }
    if !ok {
        return nil, false, nil
    }
    v, ok := tc.Get(round)
    return v, ok, nil
}

// Update the cache and returns if success.
func (tc *TSigVerifierCache) Update(round uint64) (bool, error) {
    tc.lock.Lock()
    defer tc.lock.Unlock()
    if round < tc.minRound {
        return false, ErrRoundAlreadyPurged
    }
    if _, exist := tc.verifier[round]; exist {
        return true, nil
    }
    if !tc.intf.IsDKGFinal(round) {
        return false, nil
    }
    gpk, err := NewDKGGroupPublicKey(round,
        tc.intf.DKGMasterPublicKeys(round),
        tc.intf.DKGComplaints(round),
        int(utils.GetConfigWithPanic(tc.intf, round, nil).DKGSetSize/3)+1)
    if err != nil {
        return false, err
    }
    if len(tc.verifier) == 0 {
        tc.minRound = round
    }
    tc.verifier[round] = gpk
    if len(tc.verifier) > tc.cacheSize {
        delete(tc.verifier, tc.minRound)
    }
    for {
        if _, exist := tc.verifier[tc.minRound]; !exist {
            tc.minRound++
        } else {
            break
        }
    }
    return true, nil
}

// Get the TSigVerifier of round and returns if it exists.
func (tc *TSigVerifierCache) Get(round uint64) (TSigVerifier, bool) {
    tc.lock.RLock()
    defer tc.lock.RUnlock()
    verifier, exist := tc.verifier[round]
    return verifier, exist
}

func newTSigProtocol(
    gpk *DKGGroupPublicKey,
    hash common.Hash) *tsigProtocol {
    return &tsigProtocol{
        groupPublicKey: gpk,
        hash:           hash,
        sigs:           make(map[dkg.ID]dkg.PartialSignature, gpk.threshold+1),
    }
}

func (tsig *tsigProtocol) sanityCheck(psig *typesDKG.PartialSignature) error {
    _, exist := tsig.groupPublicKey.publicKeys[psig.ProposerID]
    if !exist {
        return ErrNotQualifyDKGParticipant
    }
    ok, err := utils.VerifyDKGPartialSignatureSignature(psig)
    if err != nil {
        return err
    }
    if !ok {
        return ErrIncorrectPartialSignatureSignature
    }
    if psig.Hash != tsig.hash {
        return ErrMismatchPartialSignatureHash
    }
    return nil
}

func (tsig *tsigProtocol) processPartialSignature(
    psig *typesDKG.PartialSignature) error {
    if psig.Round != tsig.groupPublicKey.round {
        return nil
    }
    id, exist := tsig.groupPublicKey.idMap[psig.ProposerID]
    if !exist {
        return ErrNotQualifyDKGParticipant
    }
    if err := tsig.sanityCheck(psig); err != nil {
        return err
    }
    pubKey := tsig.groupPublicKey.publicKeys[psig.ProposerID]
    if !pubKey.VerifySignature(
        tsig.hash, crypto.Signature(psig.PartialSignature)) {
        return ErrIncorrectPartialSignature
    }
    tsig.sigs[id] = psig.PartialSignature
    return nil
}

func (tsig *tsigProtocol) signature() (crypto.Signature, error) {
    if len(tsig.sigs) < tsig.groupPublicKey.threshold {
        return crypto.Signature{}, ErrNotEnoughtPartialSignatures
    }
    ids := make(dkg.IDs, 0, len(tsig.sigs))
    psigs := make([]dkg.PartialSignature, 0, len(tsig.sigs))
    for id, psig := range tsig.sigs {
        ids = append(ids, id)
        psigs = append(psigs, psig)
    }
    return dkg.RecoverSignature(psigs, ids)
}