/
actions_active.go
515 lines (455 loc) 路 14.2 KB
/
actions_active.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
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
package dkg
import (
"context"
"errors"
"fmt"
"time"
"github.com/drand/drand/v2/crypto"
"github.com/drand/drand/v2/internal/metrics"
"github.com/drand/drand/v2/internal/net"
drand "github.com/drand/drand/v2/protobuf/dkg"
proto "github.com/drand/drand/v2/protobuf/drand"
"google.golang.org/protobuf/types/known/timestamppb"
"github.com/drand/drand/v2/common/key"
"github.com/drand/drand/v2/common/tracer"
"github.com/drand/drand/v2/internal/util"
)
// actions_active contains all the DKG actions that require user interaction: creating a network,
// accepting or rejecting a DKG, getting the status, etc. Both leader and follower interactions are contained herein.
//nolint:gocyclo,funlen
func (d *Process) Command(ctx context.Context, command *drand.DKGCommand) (*drand.EmptyDKGResponse, error) {
if command == nil {
return nil, errors.New("command cannot be nil")
}
if command.Metadata == nil {
return nil, errors.New("command metadata cannot be nil")
}
beaconID := command.Metadata.BeaconID
commandName := commandType(command)
d.lock.Lock()
defer d.lock.Unlock()
// fetch our keypair from the BeaconProcess and remap it into a `Participant`
me, err := d.identityForBeacon(beaconID)
if err != nil {
return nil, err
}
// pull the latest DKG state from the database
currentState, err := d.store.GetCurrent(beaconID)
if err != nil {
return nil, err
}
d.log.Infow("running DKG command", "command", commandName, "beaconID", beaconID)
// map the current state to the latest state, depending on the type of packet
var packetToGossip *drand.GossipPacket
var afterState *DBState
switch c := command.Command.(type) {
case *drand.DKGCommand_Initial:
afterState, packetToGossip, err = d.StartNetwork(ctx, beaconID, me, currentState, c.Initial)
case *drand.DKGCommand_Resharing:
afterState, packetToGossip, err = d.StartProposal(ctx, beaconID, me, currentState, c.Resharing)
case *drand.DKGCommand_Join:
afterState, packetToGossip, err = d.StartJoin(ctx, beaconID, me, currentState, c.Join)
case *drand.DKGCommand_Accept:
afterState, packetToGossip, err = d.StartAccept(ctx, beaconID, me, currentState, c.Accept)
case *drand.DKGCommand_Reject:
afterState, packetToGossip, err = d.StartReject(ctx, beaconID, me, currentState, c.Reject)
case *drand.DKGCommand_Execute:
afterState, packetToGossip, err = d.StartExecute(ctx, beaconID, me, currentState, c.Execute)
case *drand.DKGCommand_Abort:
afterState, packetToGossip, err = d.StartAbort(ctx, beaconID, currentState, c.Abort)
default:
return nil, errors.New("unrecognized DKG command")
}
if err != nil {
return nil, fmt.Errorf("error running command %s: %w", commandName, err)
}
metrics.DKGStateChange(afterState.BeaconID, afterState.Epoch, afterState.Leader == me, uint32(afterState.State))
// if there is an output packet to gossip (i.e. if the user isn't joining)
// then we sign the packet and gossip it to the network
if packetToGossip != nil {
// then we gossip to the joiners and remainers
recipients := util.Concat(afterState.Joining, afterState.Remaining)
terms := termsFromState(afterState)
metadata, err := d.signMessage(beaconID, packetToGossip, terms)
if err != nil {
return nil, err
}
packetToGossip.Metadata = metadata
done, errs := d.gossip(me, recipients, packetToGossip)
// if it's a proposal, let's block until it finishes or a timeout,
// because we want to be sure everybody received it
// QUESTION: do we _really_ want to fail on errors? we will probably have to abort if that's the case
if command.GetInitial() != nil || command.GetResharing() != nil {
select {
case err = <-errs:
return nil, err
case <-done:
break
}
}
// we gossip the leavers separately - if it fails, no big deal
_, _ = d.gossip(me, afterState.Leaving, packetToGossip)
}
return &drand.EmptyDKGResponse{}, nil
}
func (d *Process) StartNetwork(
ctx context.Context,
beaconID string,
me *drand.Participant,
state *DBState,
options *drand.FirstProposalOptions,
) (*DBState, *drand.GossipPacket, error) {
_, span := tracer.NewSpan(ctx, "dkg.StartNetwork")
defer span.End()
genesisTime := options.GenesisTime
if genesisTime == nil {
genesisTime = timestamppb.New(time.Now())
}
// remap the CLI payload into one useful for applying to the DKG state
terms := drand.ProposalTerms{
BeaconID: beaconID,
Threshold: options.Threshold,
Epoch: 1,
Timeout: options.Timeout,
Leader: me,
SchemeID: options.Scheme,
GenesisTime: genesisTime,
// GenesisSeed is created after the DKG, so it cannot exist yet
GenesisSeed: nil,
CatchupPeriodSeconds: options.CatchupPeriodSeconds,
BeaconPeriodSeconds: options.PeriodSeconds,
Joining: util.Filter(options.Joining, util.NonEmpty),
}
// apply our enriched DKG payload onto the current DKG state to create a new state
nextState, err := state.Proposing(me, &terms)
if err != nil {
return nil, nil, err
}
if err := d.store.SaveCurrent(beaconID, nextState); err != nil {
return nil, nil, err
}
return nextState, &drand.GossipPacket{
Packet: &drand.GossipPacket_Proposal{
Proposal: &terms,
},
// this gets set in the enclosing scope
Metadata: nil,
}, nil
}
func asIdentity(response *proto.IdentityResponse) (key.Identity, error) {
sch, err := crypto.GetSchemeByID(response.GetSchemeName())
if err != nil {
return key.Identity{}, fmt.Errorf("peer return key of scheme %s, which was not found", response.GetSchemeName())
}
pk := sch.KeyGroup.Point()
err = pk.UnmarshalBinary(response.Key)
if err != nil {
return key.Identity{}, err
}
return key.Identity{
Key: pk,
Addr: response.Address,
Signature: response.Signature,
Scheme: sch,
}, nil
}
//nolint:gocyclo,funlen
func (d *Process) StartProposal(
ctx context.Context,
beaconID string,
me *drand.Participant,
currentState *DBState,
options *drand.ProposalOptions,
) (*DBState, *drand.GossipPacket, error) {
_, span := tracer.NewSpan(ctx, "dkg.StartProposal")
defer span.End()
// Migration path for v1.5.8 -> v2 upgrade
// TODO: remove it in the future
if currentState.Epoch == 1 && currentState.State == Complete {
d.log.Info("First proposal after upgrade to v2 - migrating keys from group file")
// migration from v1 -> v2 makes all parties in the v1 group file 'joiners'
// the DKGProcess migration path will set old signatures to `nil`, hence we check it here
for i, r := range currentState.Joining {
if r.Signature != nil {
d.log.Debugw("proposal migration - signature not nil, skipping")
continue
}
// fetch their public key via gRPC
response, err := d.protocolClient.GetIdentity(ctx, net.CreatePeer(r.Address), &proto.IdentityRequest{Metadata: &proto.Metadata{
BeaconID: beaconID,
ChainHash: nil,
}})
if err != nil {
return nil, nil, err
}
// verify its signature
identity, err := asIdentity(response)
if err != nil {
return nil, nil, err
}
err = identity.ValidSignature()
if err != nil {
return nil, nil, err
}
// update the key mapping
updatedParticipant := drand.Participant{
Address: r.Address,
Key: response.Key,
Signature: response.Signature,
}
currentState.Joining[i] = &updatedParticipant
// if they were the last leader, update their key also
if currentState.Leader.Address == r.Address {
currentState.Leader = &updatedParticipant
}
// store it in the DB
err = d.store.SaveCurrent(beaconID, currentState)
if err != nil {
return nil, nil, err
}
err = d.store.SaveFinished(beaconID, currentState)
if err != nil {
return nil, nil, err
}
d.log.Info("Key migration complete")
}
}
var newEpoch uint32
if currentState.State == Aborted || currentState.State == TimedOut || currentState.State == Failed {
newEpoch = currentState.Epoch
} else {
newEpoch = currentState.Epoch + 1
}
terms := drand.ProposalTerms{
BeaconID: beaconID,
Threshold: options.Threshold,
Epoch: newEpoch,
SchemeID: currentState.SchemeID,
BeaconPeriodSeconds: uint32(currentState.BeaconPeriod.Seconds()),
CatchupPeriodSeconds: options.CatchupPeriodSeconds,
GenesisTime: timestamppb.New(currentState.GenesisTime),
GenesisSeed: currentState.GenesisSeed,
Timeout: options.Timeout,
Leader: me,
Joining: options.Joining,
Remaining: options.Remaining,
Leaving: options.Leaving,
}
nextState, err := currentState.Proposing(me, &terms)
if err != nil {
return nil, nil, err
}
err = d.store.SaveCurrent(beaconID, nextState)
if err != nil {
return nil, nil, err
}
return nextState,
&drand.GossipPacket{
Packet: &drand.GossipPacket_Proposal{
Proposal: &terms,
},
},
nil
}
func (d *Process) StartAbort(
ctx context.Context,
beaconID string,
current *DBState,
_ *drand.AbortOptions,
) (*DBState, *drand.GossipPacket, error) {
_, span := tracer.NewSpan(ctx, "dkg.StartAbort")
defer span.End()
nextState, err := current.StartAbort()
if err != nil {
return nil, nil, err
}
err = d.store.SaveCurrent(beaconID, nextState)
if err != nil {
return nil, nil, err
}
return nextState, &drand.GossipPacket{
Packet: &drand.GossipPacket_Abort{
Abort: &drand.AbortDKG{Reason: "none"},
},
}, nil
}
func (d *Process) StartExecute(
ctx context.Context,
beaconID string,
me *drand.Participant,
state *DBState,
_ *drand.ExecutionOptions,
) (*DBState, *drand.GossipPacket, error) {
_, span := tracer.NewSpan(ctx, "dkg.StartExecute")
defer span.End()
nextState, err := state.StartExecuting(me)
if err != nil {
return nil, nil, err
}
err = d.store.SaveCurrent(beaconID, nextState)
if err != nil {
return nil, nil, err
}
kickoffTime := time.Now().Add(d.config.KickoffGracePeriod)
err = d.executeDKG(ctx, beaconID, kickoffTime)
if err != nil {
return nil, nil, err
}
return nextState, &drand.GossipPacket{
Packet: &drand.GossipPacket_Execute{
Execute: &drand.StartExecution{
Time: timestamppb.New(kickoffTime),
},
},
}, nil
}
func (d *Process) StartJoin(
ctx context.Context,
beaconID string,
me *drand.Participant,
state *DBState,
options *drand.JoinOptions,
) (*DBState, *drand.GossipPacket, error) {
_, span := tracer.NewSpan(ctx, "dkg.StartJoin")
defer span.End()
var previousGroupFile *key.Group
if state.Epoch > 1 {
if options.GroupFile == nil {
return nil, nil, errors.New("group file required to join after the first epoch")
}
p, err := util.ParseGroupFileBytes(options.GroupFile)
if err != nil {
return nil, nil, err
}
previousGroupFile = p
}
nextState, err := state.Joined(me, previousGroupFile)
if err != nil {
return nil, nil, err
}
// joiners don't need to gossip anything
return nextState, nil, d.store.SaveCurrent(beaconID, nextState)
}
//nolint:dupl // it's similar but not the same
func (d *Process) StartAccept(
ctx context.Context,
beaconID string,
me *drand.Participant,
state *DBState,
_ *drand.AcceptOptions,
) (*DBState, *drand.GossipPacket, error) {
_, span := tracer.NewSpan(ctx, "dkg.StartAccept")
defer span.End()
nextState, err := state.Accepted(me)
if err != nil {
return nil, nil, err
}
err = d.store.SaveCurrent(beaconID, nextState)
if err != nil {
return nil, nil, err
}
return nextState, &drand.GossipPacket{
Packet: &drand.GossipPacket_Accept{
Accept: &drand.AcceptProposal{
Acceptor: me,
},
},
}, nil
}
//nolint:dupl // it's similar but not the same
func (d *Process) StartReject(
ctx context.Context,
beaconID string,
me *drand.Participant,
state *DBState,
_ *drand.RejectOptions,
) (*DBState, *drand.GossipPacket, error) {
_, span := tracer.NewSpan(ctx, "dkg.StartReject")
defer span.End()
nextState, err := state.Rejected(me)
if err != nil {
return nil, nil, err
}
err = d.store.SaveCurrent(beaconID, nextState)
if err != nil {
return nil, nil, err
}
return nextState, &drand.GossipPacket{
Packet: &drand.GossipPacket_Reject{
Reject: &drand.RejectProposal{
Rejector: me,
},
},
}, nil
}
func (d *Process) DKGStatus(ctx context.Context, request *drand.DKGStatusRequest) (*drand.DKGStatusResponse, error) {
_, span := tracer.NewSpan(ctx, "dkg.Status")
defer span.End()
finished, err := d.store.GetFinished(request.BeaconID)
if err != nil {
return nil, err
}
current, err := d.store.GetCurrent(request.BeaconID)
if err != nil {
return nil, err
}
var finalGroup []string
if current.FinalGroup != nil {
finalGroup := make([]string, len(current.FinalGroup.Nodes))
for i, v := range current.FinalGroup.Nodes {
finalGroup[i] = v.Addr
}
}
currentEntry := drand.DKGEntry{
BeaconID: current.BeaconID,
State: uint32(current.State),
Epoch: current.Epoch,
Threshold: current.Threshold,
Timeout: timestamppb.New(current.Timeout),
GenesisTime: timestamppb.New(current.GenesisTime),
GenesisSeed: current.GenesisSeed,
Leader: current.Leader,
Remaining: current.Remaining,
Joining: current.Joining,
Leaving: current.Leaving,
Acceptors: current.Acceptors,
Rejectors: current.Rejectors,
FinalGroup: finalGroup,
}
if finished == nil {
return &drand.DKGStatusResponse{
Current: ¤tEntry,
}, nil
}
finishedFinalGroup := make([]string, len(finished.FinalGroup.Nodes))
for i, v := range finished.FinalGroup.Nodes {
finishedFinalGroup[i] = v.Addr
}
return &drand.DKGStatusResponse{
Complete: &drand.DKGEntry{
BeaconID: finished.BeaconID,
State: uint32(finished.State),
Epoch: finished.Epoch,
Threshold: finished.Threshold,
Timeout: timestamppb.New(finished.Timeout),
GenesisTime: timestamppb.New(finished.GenesisTime),
GenesisSeed: finished.GenesisSeed,
Leader: finished.Leader,
Remaining: finished.Remaining,
Joining: finished.Joining,
Leaving: finished.Leaving,
Acceptors: finished.Acceptors,
Rejectors: finished.Rejectors,
FinalGroup: finishedFinalGroup,
},
Current: ¤tEntry,
}, nil
}
// identityForBeacon grabs the key.Pair from a BeaconProcess and marshals it to a drand.Participant
func (d *Process) identityForBeacon(beaconID string) (*drand.Participant, error) {
identity, err := d.beaconIdentifier.KeypairFor(beaconID)
if err != nil {
return nil, err
}
return util.PublicKeyAsParticipant(identity.Public)
}