-
Notifications
You must be signed in to change notification settings - Fork 162
/
replaceswap.go
265 lines (239 loc) · 8.09 KB
/
replaceswap.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
package worker
import (
"errors"
"fmt"
"math/big"
"strings"
"sync"
"github.com/anyswap/CrossChain-Bridge/mongodb"
"github.com/anyswap/CrossChain-Bridge/params"
"github.com/anyswap/CrossChain-Bridge/tokens"
)
var (
errSwapTxWithHeight = errors.New("swaptx with block height")
errSwapTxIsOnChain = errors.New("swaptx exist in chain")
errGetNonceFailed = errors.New("get nonce failed")
errSwapNoncePassed = errors.New("can not replace swap with old nonce")
errSwapNonceTooBig = errors.New("forbid replace swap with too big nonce than latest")
errBuildTxFailed = errors.New("build tx failed")
errSignTxFailed = errors.New("sign tx failed")
errUpdateOldTxsFailed = errors.New("update old swaptxs failed")
errNotNonceSupport = errors.New("not nonce support bridge")
updateOldSwapTxsLock sync.Mutex
maxDistanceOfSwapNonce = uint64(5)
)
// ReplaceSwapin api
func ReplaceSwapin(txid, pairID, bind, gasPrice string) (string, error) {
return replaceSwap(txid, pairID, bind, gasPrice, true)
}
// ReplaceSwapout api
func ReplaceSwapout(txid, pairID, bind, gasPrice string) (string, error) {
return replaceSwap(txid, pairID, bind, gasPrice, false)
}
func verifyReplaceSwap(txid, pairID, bind string, isSwapin bool) (*mongodb.MgoSwap, *mongodb.MgoSwapResult, error) {
swap, err := mongodb.FindSwap(isSwapin, txid, pairID, bind)
if err != nil {
return nil, nil, err
}
res, err := mongodb.FindSwapResult(isSwapin, txid, pairID, bind)
if err != nil {
return nil, nil, err
}
if res.SwapHeight != 0 {
return nil, nil, errSwapTxWithHeight
}
bridge := tokens.GetCrossChainBridge(!isSwapin)
err = checkIfSwapNonceHasPassed(bridge, res, true)
if err != nil {
return nil, nil, err
}
err = preventReplaceswapByHistory(res, isSwapin)
if err != nil {
return nil, nil, err
}
return swap, res, nil
}
func checkIfSwapNonceHasPassed(bridge tokens.CrossChainBridge, res *mongodb.MgoSwapResult, isReplace bool) error {
nonceSetter, ok := bridge.(tokens.NonceSetter)
if !ok {
return errNotNonceSupport
}
// only check if nonce has passed when tx is not onchain.
if isSwapResultTxOnChain(nonceSetter, res) {
if isReplace {
return errSwapTxIsOnChain
}
return nil
}
pairID := res.PairID
txid := res.TxID
bind := res.Bind
isSwapin := tokens.SwapType(res.SwapType) == tokens.SwapinType
tokenCfg := bridge.GetTokenConfig(pairID)
if tokenCfg == nil {
return fmt.Errorf("no token config for pairID '%v'", pairID)
}
nonce, err := nonceSetter.GetPoolNonce(tokenCfg.DcrmAddress, "latest")
if err != nil {
return errGetNonceFailed
}
if isReplace && res.SwapNonce > nonce+maxDistanceOfSwapNonce {
return errSwapNonceTooBig
}
if nonce > res.SwapNonce && res.SwapNonce > 0 {
var iden string
if isReplace {
iden = "[replace]"
} else {
iden = "[stable]"
}
if res.Timestamp < getSepTimeInFind(treatAsNoncePassedInterval) {
logWorkerWarn(iden, "mark swap result failed with nonce passed", "pairID", pairID, "txid", txid, "bind", bind, "isSwapin", isSwapin, "swaptime", res.Timestamp, "nowtime", now(), "swapNonce", res.SwapNonce, "latestNonce", nonce)
_ = markSwapResultFailed(txid, pairID, bind, isSwapin)
}
if isReplace {
return errSwapNoncePassed
}
}
return nil
}
func replaceSwap(txid, pairID, bind, gasPriceStr string, isSwapin bool) (txHash string, err error) {
var gasPrice *big.Int
if gasPriceStr != "" {
var ok bool
gasPrice, ok = new(big.Int).SetString(gasPriceStr, 0)
if !ok {
return "", errors.New("wrong gas price: " + gasPriceStr)
}
}
swap, res, err := verifyReplaceSwap(txid, pairID, bind, isSwapin)
if err != nil {
return "", err
}
srcBridge := tokens.GetCrossChainBridge(isSwapin)
swapInfo, err := verifySwapTransaction(srcBridge, pairID, txid, bind, tokens.SwapTxType(swap.TxType))
if err != nil {
return "", fmt.Errorf("[replace] reverify swap failed, %w", err)
}
if swapInfo.Value.String() != res.Value {
return "", fmt.Errorf("[replace] reverify swap value mismatch, in db %v != %v", res.Value, swapInfo.Value)
}
if !strings.EqualFold(swapInfo.Bind, bind) {
return "", fmt.Errorf("[replace] reverify swap bind address mismatch, in db %v != %v", bind, swapInfo.Bind)
}
bridge := tokens.GetCrossChainBridge(!isSwapin)
tokenCfg := bridge.GetTokenConfig(pairID)
swapType := getSwapType(isSwapin)
replaceNum := uint64(len(res.OldSwapTxs))
if replaceNum == 0 {
replaceNum++
}
nonce := res.SwapNonce
args := &tokens.BuildTxArgs{
SwapInfo: tokens.SwapInfo{
//#Identifier: params.GetReplaceIdentifier(),
Identifier: params.GetIdentifier(),
PairID: pairID,
SwapID: txid,
SwapType: swapType,
TxType: tokens.SwapTxType(swap.TxType),
Bind: bind,
},
From: tokenCfg.DcrmAddress,
OriginValue: swapInfo.Value,
ReplaceNum: replaceNum,
Extra: &tokens.AllExtras{
EthExtra: &tokens.EthExtraArgs{
GasPrice: gasPrice,
Nonce: &nonce,
},
},
}
rawTx, err := bridge.BuildRawTransaction(args)
if err != nil {
logWorkerError("replaceSwap", "build tx failed", err, "txid", txid, "bind", bind, "isSwapin", isSwapin)
return "", errBuildTxFailed
}
var signedTx interface{}
var signTxHash string
if tokenCfg.GetDcrmAddressPrivateKey() != nil {
signedTx, signTxHash, err = bridge.SignTransaction(rawTx, pairID)
} else {
signedTx, signTxHash, err = bridge.DcrmSignTransaction(rawTx, args.GetExtraArgs())
}
if err != nil {
logWorkerError("replaceSwap", "sign tx failed", err, "txid", txid, "bind", bind, "isSwapin", isSwapin)
return "", errSignTxFailed
}
swapValue := ""
if args.SwapValue != nil {
swapValue = args.SwapValue.String()
}
err = replaceSwapResult(txid, pairID, bind, signTxHash, swapValue, isSwapin)
if err != nil {
return "", errUpdateOldTxsFailed
}
txHash, err = sendSignedTransaction(bridge, signedTx, txid, pairID, bind, isSwapin)
if err == nil && txHash != signTxHash {
logWorkerError("replaceSwap", "send tx success but with different hash", errSendTxWithDiffHash, "pairID", pairID, "txid", txid, "bind", bind, "isSwapin", isSwapin, "swapNonce", nonce, "txHash", txHash, "signTxHash", signTxHash)
_ = replaceSwapResult(txid, pairID, bind, txHash, swapValue, isSwapin)
}
return txHash, err
}
func replaceSwapResult(txid, pairID, bind, txHash, swapValue string, isSwapin bool) (err error) {
updateOldSwapTxsLock.Lock()
defer updateOldSwapTxsLock.Unlock()
res, err := mongodb.FindSwapResult(isSwapin, txid, pairID, bind)
if err != nil {
return err
}
oldSwapTxs := res.OldSwapTxs
oldSwapVals := res.OldSwapVals
if len(oldSwapTxs) > 0 {
for _, oldSwapTx := range oldSwapTxs {
if oldSwapTx == txHash {
return nil
}
}
oldSwapTxs = append(oldSwapTxs, txHash)
oldSwapVals = append(oldSwapVals, swapValue)
} else {
if txHash == res.SwapTx {
return nil
}
if res.SwapTx == "" {
oldSwapTxs = []string{txHash}
oldSwapVals = []string{swapValue}
} else {
oldSwapTxs = []string{res.SwapTx, txHash}
oldSwapVals = []string{res.SwapValue, swapValue}
}
}
swapType := tokens.SwapType(res.SwapType).String()
err = updateOldSwapTxs(txid, pairID, bind, txHash, oldSwapTxs, oldSwapVals, isSwapin)
if err != nil {
logWorkerError("replace", "replaceSwapResult", err, "txid", txid, "pairID", pairID, "bind", bind, "swaptx", txHash, "swapType", swapType, "nonce", res.SwapNonce, "swapValue", swapValue)
} else {
logWorker("replace", "replaceSwapResult", "txid", txid, "pairID", pairID, "bind", bind, "swaptx", txHash, "swapType", swapType, "nonce", res.SwapNonce, "swapValue", swapValue)
}
return err
}
func preventReplaceswapByHistory(res *mongodb.MgoSwapResult, isSwapin bool) error {
swapHistories, _ := mongodb.GetSwapHistory(isSwapin, res.TxID, res.Bind)
if len(swapHistories) == 0 {
return nil
}
resBridge := tokens.GetCrossChainBridge(!isSwapin)
nonceSetter, ok := resBridge.(tokens.NonceSetter)
if !ok {
return errNotNonceSupport
}
for _, swaphist := range swapHistories {
if isTransactionOnChain(nonceSetter, swaphist.SwapTx) {
logWorkerError("[replace]", "forbid replace by history", errSwapTxIsOnChain,
"isSwapin", isSwapin, "txid", res.TxID, "bind", res.Bind, "swaptx", swaphist.SwapTx)
return errSwapTxIsOnChain
}
}
return nil
}