-
Notifications
You must be signed in to change notification settings - Fork 0
/
swap.go
106 lines (92 loc) · 2.59 KB
/
swap.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
package test_cases
import (
"context"
"encoding/hex"
"errors"
"fmt"
"strconv"
"time"
base_token "github.com/anoideaopen/robot/hlf/sdkwrapper/chaincode-api/base-token"
"github.com/anoideaopen/robot/hlf/sdkwrapper/logger"
"github.com/hyperledger/fabric-protos-go/peer"
"github.com/hyperledger/fabric-sdk-go/pkg/client/channel"
"go.uber.org/zap"
"golang.org/x/crypto/sha3"
)
// Swap user token from one cc to another cc
// fromChaincodeAPI - source chaincode api
// toChaincodeAPI - target chaincode api
// user - who will swap token - token owner
// token - title token
// swapAmount - amount of token
func Swap(fromChaincodeAPI base_token.BaseTokenInterface, toChaincodeAPI base_token.BaseTokenInterface, keyPair *base_token.KeyPair, token string, swapAmount uint64) error {
swapKey := strconv.Itoa(int(time.Now().UnixNano()))
swapHash := sha3.Sum256([]byte(swapKey))
response, err := fromChaincodeAPI.SwapBegin(
keyPair,
token,
toChaincodeAPI.GetChannelName(),
swapAmount,
hex.EncodeToString(swapHash[:]),
)
if err != nil {
panic(err)
}
if response.TxValidationCode != peer.TxValidationCode_VALID {
err = errors.New(fmt.Sprintf("TxValidationCode %d", response.TxValidationCode))
panic(err)
}
swapTransactionId := string(response.TransactionID)
// check swap is created in both channels
resp, err := WaitSwapInOtherChannel(fromChaincodeAPI, swapTransactionId)
if err != nil {
panic(err)
}
logger.Info("waitSwapInOtherChannel", zap.ByteString("from fiat to cc", resp.Payload))
resp, err = WaitSwapInOtherChannel(toChaincodeAPI, swapTransactionId)
if err != nil {
panic(err)
}
logger.Info("waitSwapInOtherChannel", zap.ByteString("from fiat to cc", resp.Payload))
ctx, cancel := context.WithTimeout(
context.Background(),
10*time.Second,
)
defer cancel()
err = Retry(ctx, func() error {
response, err = toChaincodeAPI.SwapDone(swapTransactionId, swapKey)
return err
}, 5000*time.Millisecond)
return err
}
func WaitSwapInOtherChannel(chaincodeAPI base_token.BaseTokenInterface, swapTransactionId string) (*channel.Response, error) {
var response *channel.Response
var err error
ctx, cancel := context.WithTimeout(
context.Background(),
10*time.Second,
)
defer cancel()
err = Retry(ctx, func() error {
response, err = chaincodeAPI.SwapGet(swapTransactionId)
return err
}, 5000*time.Millisecond)
return response, err
}
func Retry(
ctx context.Context,
what func() error,
d time.Duration,
) error {
for {
err := what()
if err == nil {
return nil
}
select {
case <-ctx.Done():
return fmt.Errorf("timeout (%w)", err)
case <-time.After(d):
}
}
}