-
Notifications
You must be signed in to change notification settings - Fork 2
/
resharing.go
407 lines (389 loc) · 15.6 KB
/
resharing.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
package tss
import (
"bytes"
"encoding/base64"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"hash/crc32"
"log"
"strings"
"time"
ecdsaKeygen "github.com/bnb-chain/tss-lib/v2/ecdsa/keygen"
ecdsaResharing "github.com/bnb-chain/tss-lib/v2/ecdsa/resharing"
eddsaKeygen "github.com/bnb-chain/tss-lib/v2/eddsa/keygen"
eddsaResharing "github.com/bnb-chain/tss-lib/v2/eddsa/resharing"
"github.com/bnb-chain/tss-lib/v2/tss"
)
func (s *ServiceImpl) ReshareECDSA(req *ReshareRequest) (*ReshareResponse, error) {
// ensure chaincode is set appropriately for ECDSA keygen
if req.ChainCodeHex == "" {
return nil, fmt.Errorf("ChainCodeHex is empty")
}
chaincode, err := hex.DecodeString(req.ChainCodeHex)
if err != nil {
return nil, fmt.Errorf("failed to decode chain code hex, error: %w", err)
}
if len(chaincode) != 32 {
return nil, fmt.Errorf("invalid chain code length")
}
oldPartiesCount := len(req.GetOldParties())
oldThreshold, err := GetThreshold(oldPartiesCount)
if err != nil {
return nil, fmt.Errorf("failed to get old threshold: %w", err)
}
newPartiesCount := len(req.GetNewParties())
threshold, err := GetThreshold(newPartiesCount)
if err != nil {
return nil, fmt.Errorf("failed to get threshold: %w", err)
}
var localECDSAPub *ecdsaKeygen.LocalPartySaveData
resharePrefix := req.ResharePrefix
// when a new member join the resharing process, it should not have the local state of the previous keygen
if req.PubKey != "" {
// restore the local saved data
localStateStr, err := s.stateAccessor.GetLocalState(req.PubKey)
if err != nil {
return nil, fmt.Errorf("failed to get local state, error: %w", err)
}
var localState LocalState
if err := json.Unmarshal([]byte(localStateStr), &localState); err != nil {
return nil, fmt.Errorf("failed to unmarshal local state, error: %w", err)
}
if localState.ECDSALocalData.ECDSAPub == nil {
return nil, errors.New("nil ecdsa pub key")
}
if localState.ChainCodeHex == "" {
return nil, errors.New("nil chain code")
}
localECDSAPub = &localState.ECDSALocalData
chainCodeBuf, err := hex.DecodeString(localState.ChainCodeHex)
if err != nil {
return nil, fmt.Errorf("failed to decode previous chain code hex, error: %w", err)
}
if !bytes.Equal(chaincode, chainCodeBuf) {
return nil, fmt.Errorf("chain code not match, previous chain code: %s, new chain code: %s", localState.ChainCodeHex, req.ChainCodeHex)
}
resharePrefix = localState.ResharePrefix
}
// old parties, it's key will start with old reshare prefix
oldPartyIDs, oldLocalPartyID := s.getParties(req.GetOldParties(), req.LocalPartyID, resharePrefix)
if req.NewResharePrefix != "" && req.NewResharePrefix == resharePrefix {
return nil, fmt.Errorf("old reshare prefix and new reshare prefix should not be the same")
}
newResharePrefix := req.NewResharePrefix
if newResharePrefix == "" {
newResharePrefix = getNewResharePrefix(req.NewParties)
s.resharePrefix = newResharePrefix
}
if newResharePrefix == resharePrefix {
return nil, fmt.Errorf("old reshare prefix and new reshare prefix should not be the same")
}
// new parties, it's key will start with a new reshare prefix
partyIDs, localPartyID := s.getParties(req.GetNewParties(), req.LocalPartyID, newResharePrefix)
oldCtx := tss.NewPeerContext(oldPartyIDs)
ctx := tss.NewPeerContext(partyIDs)
curve := tss.S256()
outCh := make(chan tss.Message, newPartiesCount+oldPartiesCount) // message channel
endCh := make(chan *ecdsaKeygen.LocalPartySaveData, newPartiesCount+oldPartiesCount) // result channel
errChan := make(chan struct{}, newPartiesCount+oldPartiesCount)
var pubKey string
var oldLocalPartyECDSA tss.Party
var newLocalPartyECDSA tss.Party
if localPartyID == nil && oldLocalPartyID == nil {
return nil, fmt.Errorf("local party id and old local party id should not be nil at the same time")
}
// when local party is in the new committee start the new committee first, since
// it will be waiting for messages from the old committee
if localPartyID != nil {
// new committee member will get new local party save data after resharing is done
newLocalPartyData := ecdsaKeygen.NewLocalPartySaveData(newPartiesCount)
newLocalPartyData.LocalPreParams = *s.preParams
params := tss.NewReSharingParameters(curve, oldCtx, ctx, localPartyID, oldPartiesCount, oldThreshold, newPartiesCount, threshold)
newLocalPartyECDSA = ecdsaResharing.NewLocalParty(params, newLocalPartyData, outCh, endCh)
go func() {
tErr := newLocalPartyECDSA.Start()
if tErr != nil {
log.Println("failed to start new party keyshare process", "error", tErr)
close(errChan)
}
}()
}
// when local party is in the old committee
// start the old committee second, since it will be sending messages to new committee
if oldLocalPartyID != nil {
if localECDSAPub == nil {
return nil, fmt.Errorf("if local party belongs to the old committee, it should have local state data, but got nil local state data, local party id: %s", req.LocalPartyID)
}
params := tss.NewReSharingParameters(curve, oldCtx, ctx, oldLocalPartyID, oldPartiesCount, oldThreshold, newPartiesCount, threshold)
oldLocalPartyECDSA = ecdsaResharing.NewLocalParty(params, *localECDSAPub, outCh, endCh)
go func() {
tErr := oldLocalPartyECDSA.Start()
if tErr != nil {
log.Println("failed to start old party keyshare process", "error", tErr)
close(errChan)
}
}()
}
newLocalState := &LocalState{
KeygenCommitteeKeys: req.GetNewParties(),
LocalPartyKey: req.LocalPartyID,
ChainCodeHex: req.ChainCodeHex, // ChainCode will be used later for ECDSA key derivation
ResharePrefix: newResharePrefix,
}
pubKey, err = s.processResharing(oldLocalPartyECDSA, newLocalPartyECDSA, errChan, outCh, endCh, nil, newLocalState, partyIDs, oldPartyIDs)
if err != nil {
log.Println("failed to process resharing", "error", err)
return nil, err
}
return &ReshareResponse{
PubKey: pubKey,
ResharePrefix: newResharePrefix,
}, nil
}
func (s *ServiceImpl) ResharingEdDSA(req *ReshareRequest) (*ReshareResponse, error) {
var localEdDSAPubData *eddsaKeygen.LocalPartySaveData
oldPartiesCount := len(req.GetOldParties())
oldThreshold, err := GetThreshold(oldPartiesCount)
if err != nil {
return nil, fmt.Errorf("failed to get old threshold: %w", err)
}
newPartiesCount := len(req.GetNewParties())
threshold, err := GetThreshold(newPartiesCount)
if err != nil {
return nil, fmt.Errorf("failed to get threshold: %w", err)
}
resharePrefix := req.ResharePrefix
if req.PubKey != "" {
// restore the local saved data
localStateStr, err := s.stateAccessor.GetLocalState(req.PubKey)
if err != nil {
return nil, fmt.Errorf("failed to get local state, error: %w", err)
}
var localState LocalState
if err := json.Unmarshal([]byte(localStateStr), &localState); err != nil {
return nil, fmt.Errorf("failed to unmarshal local state, error: %w", err)
}
if localState.EDDSALocalData.EDDSAPub == nil {
return nil, errors.New("nil EdDSA pub key")
}
localEdDSAPubData = &localState.EDDSALocalData
resharePrefix = localState.ResharePrefix
}
// old parties
oldPartyIDs, oldLocalPartyID := s.getParties(req.GetOldParties(), req.LocalPartyID, resharePrefix)
if req.NewResharePrefix != "" && req.NewResharePrefix == resharePrefix {
return nil, fmt.Errorf("old reshare prefix and new reshare prefix should not be the same")
}
newResharePrefix := req.NewResharePrefix
if newResharePrefix == "" {
newResharePrefix = getNewResharePrefix(req.NewParties)
s.resharePrefix = newResharePrefix
}
if newResharePrefix == resharePrefix {
return nil, fmt.Errorf("old reshare prefix and new reshare prefix should not be the same")
}
// new parties
partyIDs, newLocalPartyID := s.getParties(req.GetNewParties(), req.LocalPartyID, newResharePrefix)
oldCtx := tss.NewPeerContext(oldPartyIDs)
ctx := tss.NewPeerContext(partyIDs)
curve := tss.Edwards()
outCh := make(chan tss.Message, newPartiesCount+oldPartiesCount) // message channel
endCh := make(chan *eddsaKeygen.LocalPartySaveData, newPartiesCount+oldPartiesCount) // result channel
newLocalState := &LocalState{
KeygenCommitteeKeys: req.GetNewParties(),
LocalPartyKey: req.LocalPartyID,
ResharePrefix: newResharePrefix,
}
errChan := make(chan struct{}, newPartiesCount+oldPartiesCount)
var oldLocalPartyEdDSA tss.Party
var newLocalPartyEdDSA tss.Party
if newLocalPartyID == nil && oldLocalPartyID == nil {
return nil, fmt.Errorf("local party id and old local party id should not be nil at the same time")
}
// when local party is in the new committee
if newLocalPartyID != nil {
// new committee member will get new local party save data after resharing is done
newLocalPartyData := eddsaKeygen.NewLocalPartySaveData(newPartiesCount)
params := tss.NewReSharingParameters(curve, oldCtx, ctx, newLocalPartyID, oldPartiesCount, oldThreshold, newPartiesCount, threshold)
newLocalPartyEdDSA = eddsaResharing.NewLocalParty(params, newLocalPartyData, outCh, endCh)
go func() {
tErr := newLocalPartyEdDSA.Start()
if tErr != nil {
log.Println("failed to start new committee reshare process", "error", tErr)
close(errChan)
}
}()
}
if oldLocalPartyID != nil {
if localEdDSAPubData == nil {
return nil, fmt.Errorf("if local party belongs to the old committee, it should have local state data, but got nil local state data, local party id: %s", req.LocalPartyID)
}
params := tss.NewReSharingParameters(curve, oldCtx, ctx, oldLocalPartyID, oldPartiesCount, oldThreshold, newPartiesCount, threshold)
oldLocalPartyEdDSA = eddsaResharing.NewLocalParty(params, *localEdDSAPubData, outCh, endCh)
go func() {
tErr := oldLocalPartyEdDSA.Start()
if tErr != nil {
log.Println("failed to start old party keyshare process", "error", tErr)
close(errChan)
}
}()
}
pubKey, err := s.processResharing(oldLocalPartyEdDSA, newLocalPartyEdDSA, errChan, outCh, nil, endCh, newLocalState, partyIDs, oldPartyIDs)
if err != nil {
log.Println("failed to process keyshare", "error", err)
return nil, err
}
return &ReshareResponse{
PubKey: pubKey,
ResharePrefix: newResharePrefix,
}, nil
}
func getOutboundMessage(msgData []byte, from string, to string, isBroadcast bool) (string, error) {
jsonBytes, err := json.MarshalIndent(MessageFromTss{
WireBytes: msgData,
From: from,
To: to,
IsBroadcast: isBroadcast,
}, "", " ")
if err != nil {
return "", fmt.Errorf("failed to marshal message to json, error: %w", err)
}
return base64.StdEncoding.EncodeToString(jsonBytes), nil
}
func getNewResharePrefix(input string) string {
result := crc32.Checksum([]byte(input), crc32.MakeTable(crc32.IEEE))
return fmt.Sprintf("%x", result)
}
func (s *ServiceImpl) processResharing(oldLocalParty tss.Party,
newLocalParty tss.Party,
errCh <-chan struct{},
outCh <-chan tss.Message,
ecdsaEndCh <-chan *ecdsaKeygen.LocalPartySaveData,
eddsaEndCh <-chan *eddsaKeygen.LocalPartySaveData,
localState *LocalState,
newSortedPartyIds tss.SortedPartyIDs,
oldSortedPartyIds tss.SortedPartyIDs) (string, error) {
for {
select {
case <-errCh: // fail to start keygen process , exit immediately
return "", errors.New("failed to start resharing process")
case outMsg := <-outCh:
// pass the message to messenger
msgData, r, err := outMsg.WireBytes()
if err != nil {
return "", fmt.Errorf("failed to get wire bytes, error: %w", err)
}
if r.To == nil {
return "", fmt.Errorf("doesn't expect r.To to be nil during resharing")
}
for _, item := range r.To {
// when moniker is the same as local party key, it means it's sending messages to parties on the same node
if item.Moniker == localState.LocalPartyKey {
fromPartyKey := string(r.From.GetKey())
toPartyKey := string(item.GetKey())
if fromPartyKey == toPartyKey {
continue
}
if strings.HasPrefix(toPartyKey, s.resharePrefix) {
if _, err := newLocalParty.UpdateFromBytes(msgData, r.From, r.IsBroadcast); err != nil {
return "", fmt.Errorf("fail to apply message new committee local party")
}
} else {
if _, err := oldLocalParty.UpdateFromBytes(msgData, r.From, r.IsBroadcast); err != nil {
return "", fmt.Errorf("fail to apply message old committee local party")
}
}
}
outboundPayload, err := getOutboundMessage(msgData, string(r.From.GetKey()), string(item.GetKey()), r.IsBroadcast)
if err != nil {
return "", fmt.Errorf("failed to get outbound message, error: %w", err)
}
if err := s.messenger.Send(r.From.Moniker, item.Moniker, outboundPayload); err != nil {
return "", fmt.Errorf("failed to send message to peer, error: %w", err)
}
}
case msg := <-s.inboundMessageCh:
// apply the message to the tss instance
if _, err := s.applyReshareMessageToTssInstance(oldLocalParty, newLocalParty, msg, newSortedPartyIds, oldSortedPartyIds); err != nil {
return "", fmt.Errorf("failed to apply message to tss instance, error: %w", err)
}
case saveData := <-ecdsaEndCh:
if saveData.ECDSAPub == nil {
// when both new party and old party are on the same node , it should wait for both to finish
// if the node is new node only , then it should not be here , saveDave.ECDSA will not be nil
if newLocalParty != nil {
continue
} else {
return "", nil
}
}
pubKey, err := GetHexEncodedPubKey(saveData.ECDSAPub)
if err != nil {
return "", fmt.Errorf("failed to get hex encoded ecdsa pub key, error: %w", err)
}
localState.PubKey = pubKey
localState.ECDSALocalData = *saveData
if err := s.saveLocalStateData(localState); err != nil {
return "", fmt.Errorf("failed to save local state data, error: %w", err)
}
return pubKey, nil
case saveData := <-eddsaEndCh:
if saveData.EDDSAPub == nil {
if newLocalParty != nil {
continue
} else {
return "", nil
}
}
pubKey, err := GetHexEncodedPubKey(saveData.EDDSAPub)
if err != nil {
return "", fmt.Errorf("failed to get hex encoded ecdsa pub key, error: %w", err)
}
localState.PubKey = pubKey
localState.EDDSALocalData = *saveData
if err := s.saveLocalStateData(localState); err != nil {
return "", fmt.Errorf("failed to save local state data, error: %w", err)
}
return pubKey, nil
case <-time.After(2 * time.Minute):
return "", errors.New("reshare timeout, reshare didn't finish in 2 minutes")
}
}
}
func (s *ServiceImpl) applyReshareMessageToTssInstance(oldLocalParty, newLocalParty tss.Party,
msg string,
newSortedPartyIds tss.SortedPartyIDs,
oldSortedPartyIds tss.SortedPartyIDs) (string, error) {
var msgFromTss MessageFromTss
originalBytes, err := base64.StdEncoding.DecodeString(msg)
if err != nil {
return "", fmt.Errorf("failed to decode message from base64, error: %w", err)
}
if err := json.Unmarshal(originalBytes, &msgFromTss); err != nil {
return "", fmt.Errorf("failed to unmarshal message from json, error: %w", err)
}
var fromParty *tss.PartyID
for _, item := range append(oldSortedPartyIds, newSortedPartyIds...) {
if string(item.GetKey()) == msgFromTss.From {
fromParty = item
break
}
}
if fromParty == nil {
return "", fmt.Errorf("failed to find from party,from:%s", msgFromTss.From)
}
if strings.HasPrefix(msgFromTss.To, s.resharePrefix) {
_, errUpdate := newLocalParty.UpdateFromBytes(msgFromTss.WireBytes, fromParty, msgFromTss.IsBroadcast)
if errUpdate != nil {
return "", fmt.Errorf("failed to update from bytes, error: %w", errUpdate)
}
} else {
_, errUpdate := oldLocalParty.UpdateFromBytes(msgFromTss.WireBytes, fromParty, msgFromTss.IsBroadcast)
if errUpdate != nil {
return "", fmt.Errorf("failed to update from bytes, error: %w", errUpdate)
}
}
return "", nil
}