/
user.go
534 lines (461 loc) · 11.9 KB
/
user.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
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
package wallet
import (
"bytes"
"crypto/rand"
"encoding/hex"
"encoding/json"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strconv"
"strings"
"sync/atomic"
"time"
"github.com/anoideaopen/foundation/proto"
"github.com/anoideaopen/robot/hlf/sdkwrapper/logger"
"github.com/anoideaopen/robot/hlf/sdkwrapper/service"
"github.com/btcsuite/btcutil/base58"
pb "github.com/golang/protobuf/proto"
"github.com/hyperledger/fabric-sdk-go/pkg/common/errors/status"
"github.com/hyperledger/fabric-sdk-go/pkg/common/providers/core"
"github.com/hyperledger/fabric-sdk-go/pkg/common/providers/fab"
"github.com/hyperledger/fabric-sdk-go/pkg/core/config"
"github.com/hyperledger/fabric-sdk-go/pkg/gateway"
"go.uber.org/zap"
"golang.org/x/crypto/ed25519"
"golang.org/x/crypto/sha3"
)
const (
retryCount = 20
retrySleep = time.Millisecond * 500
)
type InvokeResponse struct {
Event *fab.TxStatusEvent
Response []byte
}
type User struct {
ID string
PublicKey ed25519.PublicKey
SecretKey ed25519.PrivateKey
config core.ConfigProvider
wallet *gateway.Wallet
backend *gateway.Gateway
robot *gateway.Gateway
isBackend bool
sem chan struct{}
}
type Option func(u *User) error
func NewUser(msp, backendCert, backendKey, connection, id, privateKey string, opts ...Option) (*User, error) {
user := &User{
ID: id,
}
for _, opt := range opts {
if err := opt(user); err != nil {
return nil, err
}
}
if user.backend == nil {
certData, err := os.Open(backendCert)
if err != nil {
return nil, err
}
cert, err := ioutil.ReadAll(certData)
certData.Close()
if err != nil {
return nil, err
}
keyData, err := os.Open(backendKey)
if err != nil {
return nil, err
}
key, err := ioutil.ReadAll(keyData)
keyData.Close()
if err != nil {
return nil, err
}
user.wallet = gateway.NewInMemoryWallet()
if err = user.wallet.Put("user", gateway.NewX509Identity(msp, string(cert), string(key))); err != nil {
return nil, err
}
user.config = config.FromFile(filepath.Clean(connection))
backend, err := gateway.Connect(gateway.WithConfig(user.config), gateway.WithIdentity(user.wallet, "user"))
if err != nil {
return nil, err
}
user.backend = backend
}
if !user.isBackend {
sKey, pKey, err := NewKeyPair(privateKey)
if err != nil {
return nil, err
}
user.SecretKey = sKey
user.PublicKey = pKey
return user, user.AddUser()
}
return user, nil
}
func NewKeyPair(private string) (ed25519.PrivateKey, ed25519.PublicKey, error) {
if private == "" {
pKey, sKey, err := ed25519.GenerateKey(rand.Reader)
if err != nil {
return nil, nil, err
}
return sKey, pKey, nil
}
decoded, ver, err := base58.CheckDecode(private)
if err != nil {
return nil, nil, err
}
privateKey := ed25519.PrivateKey(append([]byte{ver}, decoded...))
pk := privateKey.Public().(ed25519.PublicKey)
return privateKey, pk, nil
}
func (u *User) Base58Pk() string {
if err := checkIsNotBackend(u); err != nil {
return ""
}
return base58.Encode(u.PublicKey)
}
func (u *User) ChangeKeys(secretKey ed25519.PrivateKey, publicKey ed25519.PublicKey) {
u.SecretKey = secretKey
u.PublicKey = publicKey
}
func (u *User) Addr() string {
if err := checkIsNotBackend(u); err != nil {
return ""
}
hash := sha3.Sum256(u.PublicKey)
return base58.CheckEncode(hash[1:], hash[0])
}
func (u *User) AddrFromKey(key ed25519.PublicKey) string {
if err := checkIsNotBackend(u); err != nil {
return ""
}
hash := sha3.Sum256(key)
return base58.CheckEncode(hash[1:], hash[0])
}
func (u *User) Sign(msg []byte) []byte {
if err := checkIsNotBackend(u); err != nil {
return nil
}
return ed25519.Sign(u.SecretKey, msg)
}
func (u *User) AddUser() error {
n, err := u.backend.GetNetwork("acl")
if err != nil {
return err
}
tx, err := n.GetContract("acl").CreateTransaction("addUser")
if err != nil {
return err
}
_, err = tx.Submit(append([]string{}, u.Base58Pk(), "kychash", u.ID, "true")...)
logger.Info("add to acl", zap.String("ID", u.ID))
if err != nil && strings.Contains(err.Error(), "exists") {
logger.Info("already exists in ACL, skipping", zap.String("ID", u.ID))
} else if err != nil {
return err
}
return nil
}
func (u *User) Invoke(ch, cc, fn string, args ...string) (*InvokeResponse, error) {
n, err := u.backend.GetNetwork(ch)
if err != nil {
return nil, err
}
contract := n.GetContract(cc)
tx, err := contract.CreateTransaction(fn)
if err != nil {
return nil, err
}
resp, err := tx.Submit(args...)
if err != nil {
return nil, err
}
return &InvokeResponse{
Response: resp,
}, err
}
func (u *User) InvokeWithListener(ch, cc, fn string, args ...string) (*InvokeResponse, error) {
var (
n *gateway.Network
err error
)
if u.robot == nil {
n, err = u.backend.GetNetwork(ch)
} else {
n, err = u.robot.GetNetwork(ch)
}
if err != nil {
return nil, err
}
contract := n.GetContract(cc)
tx, err := contract.CreateTransaction(fn)
if err != nil {
return nil, err
}
listener := tx.RegisterCommitEvent()
resp, err := tx.Submit(args...)
if err != nil {
return nil, err
}
event := <-listener
return &InvokeResponse{
Event: event,
Response: resp,
}, err
}
func (u *User) SignedInvoke(nonce *int64, ch, cc, fn string, args ...string) (*InvokeResponse, error) {
if err := checkIsNotBackend(u); err != nil {
return nil, err
}
if u.sem != nil {
u.sem <- struct{}{}
}
var newnonce int64
if nonce == nil || *nonce == 0 {
newnonce = service.GetNonceInt64()
} else {
newnonce = atomic.AddInt64(nonce, 1)
}
if u.sem != nil {
<-u.sem
}
n := strconv.FormatInt(newnonce, 10)
result := append(append([]string{fn, "", ch, cc}, args...), n, base58.Encode(u.PublicKey))
message := sha3.Sum256([]byte(strings.Join(result, "")))
newArgs := append(result[1:], base58.Encode(u.Sign(message[:])))
resp, err := u.InvokeWithListener(ch, cc, fn, newArgs...)
if err != nil {
return nil, err
}
if u.robot != nil {
time.Sleep(1000 * time.Millisecond)
binaryTx, err := hex.DecodeString(resp.Event.TxID)
if err != nil {
return nil, err
}
b := &proto.Batch{
TxIDs: [][]byte{binaryTx},
}
e, batchResp, err := u.SendBatch(ch, cc, b)
if err != nil {
return nil, err
}
for _, txResp := range batchResp.TxResponses {
if bytes.Equal(txResp.Id, binaryTx) {
logger.Info("batch",
zap.String("channel", cc),
zap.String("tx ID", e.TxID),
zap.Int32("validation code:", int32(e.TxValidationCode)),
zap.String("batch ID", hex.EncodeToString(txResp.Id)),
zap.Any("writes", txResp.GetWrites()),
zap.Any("error", txResp.Error),
)
return &InvokeResponse{
Event: resp.Event,
Response: resp.Response,
}, nil
}
}
return nil, fmt.Errorf("batch doesn't contain response for transaction")
}
return &InvokeResponse{
Event: resp.Event,
Response: resp.Response,
}, nil
}
func (u *User) SignedInvokeAsync(ch, cc, fn string, args ...string) (*InvokeResponse, error) {
if err := checkIsNotBackend(u); err != nil {
return nil, err
}
nonce := strconv.FormatInt(time.Now().UnixNano()/1000000, 10)
result := append(append([]string{fn, "", ch, cc}, args...), nonce, base58.Encode(u.PublicKey))
message := sha3.Sum256([]byte(strings.Join(result, "")))
newArgs := append(result[1:], base58.Encode(u.Sign(message[:])))
resp, err := u.Invoke(ch, cc, fn, newArgs...)
if err != nil {
return nil, err
}
return &InvokeResponse{
Event: nil,
Response: resp.Response,
}, nil
}
func (u *User) Query(ch, cc, fn string, args ...string) ([]byte, error) {
var (
n *gateway.Network
err error
)
if u.robot == nil {
n, err = u.backend.GetNetwork(ch)
} else {
n, err = u.robot.GetNetwork(ch)
}
if err != nil {
return nil, err
}
t, err := n.GetContract(cc).CreateTransaction(fn)
// ToDo temporarily
/*
gateway.WithEvaluateRequestOptions(
channel.WithRetry(evaluateRetryOpts),
),*/
return t.Evaluate(args...)
}
func (u *User) QueryWithRetryIfEndorsementMismatch(ch, cc, fn string, args ...string) ([]byte, error) {
var (
n *gateway.Network
r []byte
err error
)
if u.robot == nil {
n, err = u.backend.GetNetwork(ch)
} else {
n, err = u.robot.GetNetwork(ch)
}
if err != nil {
return nil, err
}
t, err := n.GetContract(cc).CreateTransaction(fn)
if err != nil {
return nil, err
}
for i := 0; i < retryCount; i++ {
r, err = t.Evaluate(args...)
if err != nil {
if isEndorsementMismatchErr(err) {
time.Sleep(retrySleep)
continue
}
return r, err
}
return r, err
}
return r, err
}
func (u *User) BalanceShouldBe(expected uint64) error {
expectedBalance := "\"" + strconv.FormatUint(expected, 10) + "\""
var (
balance string
n int = 0
)
for balance == "" && n < 10 {
tokenBalanceResponse, err := u.QueryWithRetryIfEndorsementMismatch("fiat", "fiat", "balanceOf", u.Addr())
if err != nil {
break
}
tokenBalanceString := string(tokenBalanceResponse)
if expectedBalance == tokenBalanceString {
balance = tokenBalanceString
break
}
time.Sleep(500 * time.Millisecond)
n++
}
if expectedBalance != balance {
return fmt.Errorf("expected %s, got %s", expectedBalance, balance)
}
return nil
}
func (u *User) SwapAnswerAndDone(ch, cc, swapId string, swapKey string) error {
swapBytes, err := u.Query(ch, cc, "swapGet", swapId)
if err != nil {
return err
}
swap := &proto.Swap{}
if err = json.Unmarshal(swapBytes, swap); err != nil {
return err
}
swap.Creator = []byte{}
batchForTargetChan := &proto.Batch{
Swaps: []*proto.Swap{swap},
}
to := strings.ToLower(swap.To)
txEvent, batchResp, err := u.SendBatch(to, to, batchForTargetChan)
if err != nil {
return err
}
found := false
for _, swapResp := range batchResp.SwapResponses {
swapRespId := hex.EncodeToString(swapResp.Id)
if swapRespId == swapId {
logger.Info("batch",
zap.String("to", to),
zap.String("txEvent.TxID", txEvent.TxID),
zap.Int32("txEvent.TxValidationCode", int32(txEvent.TxValidationCode)),
zap.String("swapRespId", swapRespId),
zap.Any("swapResp.Writes", swapResp.Writes),
zap.Any("swapResp.Error", swapResp.Error),
)
found = true
}
}
if !found {
return fmt.Errorf("batch doesn't contain response for swap response")
}
time.Sleep(time.Millisecond * 1000)
if _, err := u.Invoke(to, to, "swapDone", swapId, swapKey); err != nil {
return err
}
binarySwapId, err := hex.DecodeString(swapId)
if err != nil {
return err
}
time.Sleep(time.Millisecond * 1000)
batchForOriginChan := &proto.Batch{
Keys: []*proto.SwapKey{{Id: binarySwapId, Key: swapKey}},
}
txEvent, batchResp, err = u.SendBatch(ch, cc, batchForOriginChan)
if err != nil {
return err
}
for _, swapResp := range batchResp.SwapKeyResponses {
swapRespId := hex.EncodeToString(swapResp.Id)
if swapRespId == swapId {
logger.Info("batch",
zap.String("channel", cc),
zap.String("txEvent.TxID", txEvent.TxID),
zap.Int32("txEvent.TxValidationCode", int32(txEvent.TxValidationCode)),
zap.String("swapRespId", swapRespId),
zap.Any("swapResp.Writes", swapResp.Writes),
zap.Any("swapResp.Error", swapResp.Error),
)
return nil
}
}
return fmt.Errorf("batch doesn't contain response for swap key")
}
func (u *User) SendBatch(ch, cc string, batch *proto.Batch) (*fab.TxStatusEvent, *proto.BatchResponse, error) {
data, err := pb.Marshal(batch)
if err != nil {
return nil, nil, err
}
resp, err := u.InvokeWithListener(ch, cc, "batchExecute", string(data))
if err != nil {
return nil, nil, err
}
result := &proto.BatchResponse{}
if err = pb.Unmarshal(resp.Response, result); err != nil {
return nil, nil, err
}
return resp.Event, result, nil
}
func checkIsNotBackend(u *User) error {
if u == nil {
return fmt.Errorf("user can't be nil")
}
if u.isBackend {
return fmt.Errorf("backend is not allowed to call this method")
}
return nil
}
func isEndorsementMismatchErr(err error) bool {
if err == nil {
return false
}
s, ok := status.FromError(err)
return ok && status.Code(s.Code) == status.EndorsementMismatch
}