/
execution.go
335 lines (289 loc) 路 9.44 KB
/
execution.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
package dkg
import (
"context"
"crypto/sha256"
"encoding/binary"
"errors"
"fmt"
"time"
"github.com/drand/drand/v2/common"
"github.com/drand/drand/v2/common/key"
"github.com/drand/drand/v2/common/tracer"
"github.com/drand/drand/v2/crypto"
"github.com/drand/drand/v2/internal/metrics"
"github.com/drand/drand/v2/internal/util"
drand "github.com/drand/drand/v2/protobuf/dkg"
"github.com/drand/kyber"
"github.com/drand/kyber/share/dkg"
"github.com/drand/kyber/sign/schnorr"
)
func (d *Process) executeDKG(ctx context.Context, beaconID string, executionStartTime time.Time) error {
// set up the DKG broadcaster for first so we're ready to broadcast DKG messages
dkgConfig, err := d.setupDKG(ctx, beaconID)
if err != nil {
return err
}
d.log.Infow("DKG execution setup successful", "beaconID", beaconID)
go func(config *dkg.Config) {
// wait until the time set by the leader for kicking off the DKG to allow other nodes to get
// the requisite packets
time.Sleep(time.Until(executionStartTime))
err := d.executeAndFinishDKG(ctx, beaconID, config)
if err != nil {
d.log.Errorw("there was an error during the DKG!", "beaconID", beaconID, "error", err)
}
}(dkgConfig)
return nil
}
func (d *Process) setupDKG(ctx context.Context, beaconID string) (*dkg.Config, error) {
ctx, span := tracer.NewSpan(ctx, "dkg.setupDKG")
defer span.End()
current, err := d.store.GetCurrent(beaconID)
if err != nil {
return nil, err
}
lastCompleted, err := d.store.GetFinished(beaconID)
if err != nil {
return nil, err
}
keypair, err := d.beaconIdentifier.KeypairFor(beaconID)
if err != nil {
return nil, err
}
me, err := util.PublicKeyAsParticipant(keypair.Public)
if err != nil {
return nil, err
}
sortedParticipants := util.SortedByPublicKey(append(current.Remaining, current.Joining...))
var config *dkg.Config
if lastCompleted == nil {
config, err = d.initialDKGConfig(current, keypair, sortedParticipants)
} else {
config, err = d.reshareDKGConfig(current, lastCompleted, keypair, sortedParticipants)
}
if err != nil {
return nil, err
}
// create the network over which to send all the DKG packets
board, err := newEchoBroadcast(
ctx,
d.internalClient,
d.log,
common.GetAppVersion(),
beaconID,
me.Address,
sortedParticipants,
keypair.Scheme(),
config,
)
if err != nil {
return nil, err
}
// we need some state on the DKG process in order to process any incoming gossip messages from the DKG
// if other nodes try to send us DKG messages before this is set we're in trouble
d.Executions[beaconID] = board
return config, nil
}
// this is done rarely and is a shared object: no good reason not to use a clone (and it makes the race checker happy)
func (d *Process) executeAndFinishDKG(ctx context.Context, beaconID string, config *dkg.Config) error {
ctx, span := tracer.NewSpan(ctx, "dkg.executeAndFinishDKG")
defer span.End()
current, err := d.store.GetCurrent(beaconID)
if err != nil {
return err
}
lastCompleted, err := d.store.GetFinished(beaconID)
if err != nil {
return err
}
output, err := d.startDKGExecution(ctx, beaconID, current, config)
if err != nil {
dkgErr := err
d.log.Errorw("DKG failed as too many nodes were evicted. Storing failed state")
next, err := current.Failed()
if err != nil {
return errors.Join(err, dkgErr)
}
err = d.store.SaveCurrent(beaconID, next)
metrics.DKGStateChange(next.BeaconID, next.Epoch, false, uint32(next.State))
return errors.Join(dkgErr, err)
}
finalState, err := current.Complete(output.FinalGroup, output.KeyShare)
if err != nil {
return err
}
err = d.store.SaveFinished(beaconID, finalState)
if err != nil {
return err
}
d.completedDKGs.Chan() <- SharingOutput{
BeaconID: beaconID,
Old: lastCompleted,
New: *finalState,
}
metrics.DKGStateChange(finalState.BeaconID, finalState.Epoch, false, uint32(finalState.State))
d.log.Infow("DKG completed successfully!", "beaconID", beaconID, "epoch", finalState.Epoch)
return nil
}
func (d *Process) startDKGExecution(
ctx context.Context,
beaconID string,
current *DBState,
config *dkg.Config,
) (*ExecutionOutput, error) {
ctx, span := tracer.NewSpan(ctx, "dkg.startDKGExecution")
defer span.End()
phaser := dkg.NewTimePhaser(d.config.TimeBetweenDKGPhases)
go phaser.Start()
// NewProtocol actually _starts_ the protocol on a goroutine also
d.lock.Lock()
broadcaster := d.Executions[beaconID]
d.lock.Unlock()
d.log.Info("Starting DKG protocol")
protocol, err := dkg.NewProtocol(config, broadcaster, phaser, d.config.SkipKeyVerification)
if err != nil {
return nil, err
}
// wait for the protocol to end and figure out who made it into the final group
select {
case result := <-protocol.WaitEnd():
if result.Error != nil {
return nil, result.Error
}
var transitionTime int64
if current.Epoch == 1 {
transitionTime = current.GenesisTime.Unix()
} else {
roundsUntilTransition := 10
currentRound := common.CurrentRound(time.Now().Unix(), current.BeaconPeriod, current.GenesisTime.Unix())
transitionTime = common.TimeOfRound(current.BeaconPeriod, current.GenesisTime.Unix(), currentRound+uint64(roundsUntilTransition))
}
keypair, err := d.beaconIdentifier.KeypairFor(beaconID)
if err != nil {
return nil, err
}
share := &key.Share{DistKeyShare: *result.Result.Key, Scheme: keypair.Scheme()}
var finalGroup []dkg.Node
// the index in the for loop may _not_ align with the index returned in QUAL!
for _, v := range result.Result.QUAL {
finalGroup = append(finalGroup, config.NewNodes[v.Index])
}
groupFile, err := asGroup(ctx, current, share, finalGroup, transitionTime)
if err != nil {
return nil, err
}
output := ExecutionOutput{
FinalGroup: &groupFile,
KeyShare: share,
}
return &output, nil
case <-time.After(time.Until(current.Timeout)):
return nil, errors.New("DKG timed out")
}
}
func asGroup(ctx context.Context, details *DBState, keyShare *key.Share, finalNodes []dkg.Node, transitionTime int64) (key.Group, error) {
_, span := tracer.NewSpan(ctx, "dkg.asGroup")
defer span.End()
sch, err := crypto.GetSchemeByID(details.SchemeID)
if err != nil {
return key.Group{}, fmt.Errorf("the schemeID for the given group did not exist, scheme: %s", details.SchemeID)
}
allSortedParticipants := util.SortedByPublicKey(append(details.Remaining, details.Joining...))
remainingNodes := make([]*key.Node, len(finalNodes))
for i, v := range finalNodes {
mappedNode, err := util.ToKeyNode(int(v.Index), allSortedParticipants[v.Index], keyShare.Scheme)
if err != nil {
return key.Group{}, err
}
remainingNodes[i] = &mappedNode
}
group := key.Group{
ID: details.BeaconID,
Threshold: int(details.Threshold),
Period: details.BeaconPeriod,
Scheme: sch,
CatchupPeriod: details.CatchupPeriod,
GenesisTime: details.GenesisTime.Unix(),
GenesisSeed: details.GenesisSeed,
TransitionTime: transitionTime,
Nodes: remainingNodes,
PublicKey: keyShare.Public(),
}
if len(group.GenesisSeed) == 0 {
group.GenesisSeed = group.Hash()
}
return group, nil
}
func (d *Process) initialDKGConfig(current *DBState, keypair *key.Pair, sortedParticipants []*drand.Participant) (*dkg.Config, error) {
sch := keypair.Scheme()
newNodes, err := util.TryMapEach[dkg.Node](sortedParticipants, func(index int, participant *drand.Participant) (dkg.Node, error) {
return util.ToNode(index, participant, sch)
})
if err != nil {
return nil, err
}
// although this is an "initial" DKG, we could be a joiner, and we may need to set some things
// from a prior DKG provided by the network
var nodes []dkg.Node
var publicCoeffs []kyber.Point
var oldThreshold = 0
if current.FinalGroup != nil {
nodes = current.FinalGroup.DKGNodes()
publicCoeffs = current.FinalGroup.PublicKey.Coefficients
oldThreshold = current.FinalGroup.Threshold
}
suite := sch.KeyGroup.(dkg.Suite)
return &dkg.Config{
Suite: suite,
Longterm: keypair.Key,
OldNodes: nodes,
NewNodes: newNodes,
PublicCoeffs: publicCoeffs,
OldThreshold: oldThreshold,
Share: nil,
Threshold: int(current.Threshold),
Reader: nil,
UserReaderOnly: false,
FastSync: true,
Nonce: nonceFor(current),
Auth: schnorr.NewScheme(suite),
Log: d.log,
}, nil
}
func (d *Process) reshareDKGConfig(
current, previous *DBState,
keypair *key.Pair,
sortedParticipants []*drand.Participant,
) (*dkg.Config, error) {
if previous == nil {
return nil, errors.New("cannot reshare with a nil previous DKG state")
}
newNodes, err := util.TryMapEach[dkg.Node](sortedParticipants, func(index int, participant *drand.Participant) (dkg.Node, error) {
return util.ToNode(index, participant, keypair.Scheme())
})
if err != nil {
return nil, err
}
suite := keypair.Scheme().KeyGroup.(dkg.Suite)
return &dkg.Config{
Suite: suite,
Longterm: keypair.Key,
OldNodes: previous.FinalGroup.DKGNodes(),
NewNodes: newNodes,
PublicCoeffs: previous.FinalGroup.PublicKey.Coefficients,
Share: &previous.KeyShare.DistKeyShare,
Threshold: int(current.Threshold),
OldThreshold: int(previous.Threshold),
Reader: nil,
UserReaderOnly: false,
FastSync: true,
Nonce: nonceFor(current),
Auth: schnorr.NewScheme(suite),
Log: d.log,
}, nil
}
func nonceFor(state *DBState) []byte {
h := sha256.New()
_ = binary.Write(h, binary.BigEndian, state.Epoch)
return h.Sum(nil)
}