-
Notifications
You must be signed in to change notification settings - Fork 84
/
livetest.go
382 lines (342 loc) · 10.7 KB
/
livetest.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
package livetest
// Regnet tests expect the BTC test harness to be running.
//
// Sim harness info:
// The harness has three wallets, alpha, beta, and gamma.
// All three wallets have confirmed UTXOs.
// The beta wallet has only coinbase outputs.
// The alpha wallet has coinbase outputs too, but has sent some to the gamma
// wallet, so also has some change outputs.
// The gamma wallet has regular transaction outputs of varying size and
// confirmation count. Value:Confirmations =
// 10:8, 18:7, 5:6, 7:5, 1:4, 15:3, 3:2, 25:1
import (
"bytes"
"context"
"crypto/sha256"
"fmt"
"math/rand"
"os/exec"
"os/user"
"path/filepath"
"sync/atomic"
"testing"
"time"
"decred.org/dcrdex/client/asset"
"decred.org/dcrdex/dex"
"decred.org/dcrdex/dex/config"
)
type WalletConstructor func(cfg *asset.WalletConfig, logger dex.Logger, network dex.Network) (asset.Wallet, error)
func tBackend(ctx context.Context, t *testing.T, newWallet WalletConstructor, symbol, node, name string,
logger dex.Logger, blkFunc func(string, error), splitTx bool) (asset.Wallet, *dex.ConnectionMaster) {
t.Helper()
user, err := user.Current()
if err != nil {
t.Fatalf("error getting current user: %v", err)
}
cfgPath := filepath.Join(user.HomeDir, "dextest", symbol, node, node+".conf")
settings, err := config.Parse(cfgPath)
if err != nil {
t.Fatalf("error reading config options: %v", err)
}
settings["walletname"] = name
if splitTx {
settings["txsplit"] = "1"
}
reportName := fmt.Sprintf("%s:%s", symbol, node)
walletCfg := &asset.WalletConfig{
Settings: settings,
TipChange: func(err error) {
blkFunc(reportName, err)
},
}
backend, err := newWallet(walletCfg, logger, dex.Regtest)
if err != nil {
t.Fatalf("error creating backend: %v", err)
}
cm := dex.NewConnectionMaster(backend)
err = cm.Connect(ctx)
if err != nil {
t.Fatalf("error connecting backend: %v", err)
}
return backend, cm
}
type testRig struct {
t *testing.T
symbol string
backends map[string]asset.Wallet
connectionMasters map[string]*dex.ConnectionMaster
}
func (rig *testRig) alpha() asset.Wallet {
return rig.backends["alpha"]
}
func (rig *testRig) beta() asset.Wallet {
return rig.backends["beta"]
}
func (rig *testRig) gamma() asset.Wallet {
return rig.backends["gamma"]
}
func (rig *testRig) close() {
for name, cm := range rig.connectionMasters {
closed := make(chan struct{})
go func() {
cm.Disconnect()
close(closed)
}()
select {
case <-closed:
case <-time.NewTimer(time.Second).C:
rig.t.Fatalf("failed to disconnect from %s", name)
}
}
}
func (rig *testRig) mineAlpha() error {
return exec.Command("tmux", "send-keys", "-t", rig.symbol+"-harness:2", "./mine-alpha 1", "C-m").Run()
}
func randBytes(l int) []byte {
b := make([]byte, l)
rand.Read(b)
return b
}
func Run(t *testing.T, newWallet WalletConstructor, address string, dexAsset *dex.Asset, splitTx bool) {
tLogger := dex.StdOutLogger("TEST", dex.LevelTrace)
tCtx, shutdown := context.WithCancel(context.Background())
defer shutdown()
tBlockTick := time.Second
tBlockWait := tBlockTick + time.Millisecond*50
walletPassword := "abc"
var blockReported uint32
blkFunc := func(name string, err error) {
atomic.StoreUint32(&blockReported, 1)
tLogger.Infof("%s has reported a new block, error = %v", name, err)
}
rig := &testRig{
t: t,
symbol: dexAsset.Symbol,
backends: make(map[string]asset.Wallet),
connectionMasters: make(map[string]*dex.ConnectionMaster, 3),
}
rig.backends["alpha"], rig.connectionMasters["alpha"] = tBackend(tCtx, t, newWallet, dexAsset.Symbol, "alpha", "", tLogger, blkFunc, splitTx)
rig.backends["beta"], rig.connectionMasters["beta"] = tBackend(tCtx, t, newWallet, dexAsset.Symbol, "beta", "", tLogger, blkFunc, splitTx)
rig.backends["gamma"], rig.connectionMasters["gamma"] = tBackend(tCtx, t, newWallet, dexAsset.Symbol, "alpha", "gamma", tLogger, blkFunc, splitTx)
defer rig.close()
var lots uint64 = 2
contractValue := lots * dexAsset.LotSize
inUTXOs := func(utxo asset.Coin, utxos []asset.Coin) bool {
for _, u := range utxos {
if bytes.Equal(u.ID(), utxo.ID()) {
return true
}
}
return false
}
// Check available amount.
for name, wallet := range rig.backends {
bal, err := wallet.Balance()
if err != nil {
t.Fatalf("error getting available: %v", err)
}
tLogger.Debugf("%s %f available, %f immature, %f locked",
name, float64(bal.Available)/1e8, float64(bal.Immature)/1e8, float64(bal.Locked)/1e8)
}
// Unlock the wallet for use.
err := rig.alpha().Unlock(walletPassword)
if err != nil {
t.Fatalf("error unlocking gamma wallet: %v", err)
}
ord := &asset.Order{
Value: contractValue * 3,
MaxSwapCount: lots * 3,
DEXConfig: dexAsset,
}
setOrderValue := func(v uint64) {
ord.Value = v
ord.MaxSwapCount = v / dexAsset.LotSize
}
// Gamma should only have 10 BTC utxos, so calling fund for less should only
// return 1 utxo.
utxos, _, err := rig.gamma().FundOrder(ord)
if err != nil {
t.Fatalf("Funding error: %v", err)
}
utxo := utxos[0]
// UTXOs should be locked
utxos, _, _ = rig.gamma().FundOrder(ord)
if inUTXOs(utxo, utxos) {
t.Fatalf("received locked output")
}
rig.gamma().ReturnCoins([]asset.Coin{utxo})
rig.gamma().ReturnCoins(utxos)
// Make sure we get the first utxo back with Fund.
utxos, _, _ = rig.gamma().FundOrder(ord)
if !splitTx && !inUTXOs(utxo, utxos) {
t.Fatalf("unlocked output not returned")
}
rig.gamma().ReturnCoins(utxos)
// Get a separate set of UTXOs for each contract.
setOrderValue(contractValue)
utxos1, _, err := rig.gamma().FundOrder(ord)
if err != nil {
t.Fatalf("error funding first contract: %v", err)
}
// Get a separate set of UTXOs for each contract.
setOrderValue(contractValue * 2)
utxos2, _, err := rig.gamma().FundOrder(ord)
if err != nil {
t.Fatalf("error funding second contract: %v", err)
}
secretKey1 := randBytes(32)
keyHash1 := sha256.Sum256(secretKey1)
secretKey2 := randBytes(32)
keyHash2 := sha256.Sum256(secretKey2)
lockTime := time.Now().Add(time.Hour * 8).UTC()
// Have gamma send a swap contract to the alpha address.
contract1 := &asset.Contract{
Address: address,
Value: contractValue,
SecretHash: keyHash1[:],
LockTime: uint64(lockTime.Unix()),
}
contract2 := &asset.Contract{
Address: address,
Value: contractValue * 2,
SecretHash: keyHash2[:],
LockTime: uint64(lockTime.Unix()),
}
swaps := &asset.Swaps{
Inputs: append(utxos1, utxos2...),
Contracts: []*asset.Contract{contract1, contract2},
FeeRate: dexAsset.MaxFeeRate,
}
receipts, _, _, err := rig.gamma().Swap(swaps)
if err != nil {
t.Fatalf("error sending swap transaction: %v", err)
}
if len(receipts) != 2 {
t.Fatalf("expected 1 receipt, got %d", len(receipts))
}
confCoin := receipts[0].Coin()
checkConfs := func(n uint32, expSpent bool) {
t.Helper()
confs, spent, err := rig.gamma().Confirmations(context.Background(), confCoin.ID())
if err != nil {
t.Fatalf("error getting %d confs: %v", n, err)
}
if confs != n {
t.Fatalf("expected %d confs, got %d", n, confs)
}
if spent != expSpent {
t.Fatalf("checkConfs: expected spent = %t, got %t", expSpent, spent)
}
}
// Check that there are 0 confirmations.
checkConfs(0, false)
makeRedemption := func(swapVal uint64, receipt asset.Receipt, secret []byte) *asset.Redemption {
t.Helper()
// Alpha should be able to redeem.
ci, err := rig.alpha().AuditContract(receipt.Coin().ID(), receipt.Contract(), nil)
if err != nil {
t.Fatalf("error auditing contract: %v", err)
}
auditCoin := ci.Coin
if ci.Recipient != address {
t.Fatalf("wrong address. %s != %s", ci.Recipient, address)
}
if auditCoin.Value() != swapVal {
t.Fatalf("wrong contract value. wanted %d, got %d", swapVal, auditCoin.Value())
}
confs, spent, err := rig.alpha().Confirmations(context.TODO(), receipt.Coin().ID())
if err != nil {
t.Fatalf("error getting confirmations: %v", err)
}
if confs != 0 {
t.Fatalf("unexpected number of confirmations. wanted 0, got %d", confs)
}
if spent {
t.Fatalf("makeRedemption: expected unspent, got spent")
}
if ci.Expiration.Equal(lockTime) {
t.Fatalf("wrong lock time. wanted %s, got %s", lockTime, ci.Expiration)
}
return &asset.Redemption{
Spends: ci,
Secret: secret,
}
}
redemptions := []*asset.Redemption{
makeRedemption(contractValue, receipts[0], secretKey1),
makeRedemption(contractValue*2, receipts[1], secretKey2),
}
_, _, _, err = rig.alpha().Redeem(&asset.RedeemForm{
Redemptions: redemptions,
})
if err != nil {
t.Fatalf("redemption error: %v", err)
}
// Find the redemption
swapReceipt := receipts[0]
ctx, cancel := context.WithDeadline(tCtx, time.Now().Add(time.Second*5))
defer cancel()
_, checkKey, err := rig.gamma().FindRedemption(ctx, swapReceipt.Coin().ID())
if err != nil {
t.Fatalf("error finding unconfirmed redemption: %v", err)
}
if !bytes.Equal(checkKey, secretKey1) {
t.Fatalf("findRedemption (unconfirmed) key mismatch. %x != %x", checkKey, secretKey1)
}
// Mine a block and find the redemption again.
rig.mineAlpha()
time.Sleep(tBlockWait)
if atomic.LoadUint32(&blockReported) == 0 {
t.Fatalf("no block reported")
}
// Check that there is 1 confirmation on the swap
checkConfs(1, true)
_, _, err = rig.gamma().FindRedemption(ctx, swapReceipt.Coin().ID())
if err != nil {
t.Fatalf("error finding confirmed redemption: %v", err)
}
// Now send another one with lockTime = now and try to refund it.
secretKey := randBytes(32)
keyHash := sha256.Sum256(secretKey)
lockTime = time.Now().Add(-8 * time.Hour)
// Have gamma send a swap contract to the alpha address.
setOrderValue(contractValue)
utxos, _, _ = rig.gamma().FundOrder(ord)
contract := &asset.Contract{
Address: address,
Value: contractValue,
SecretHash: keyHash[:],
LockTime: uint64(lockTime.Unix()),
}
swaps = &asset.Swaps{
Inputs: utxos,
Contracts: []*asset.Contract{contract},
FeeRate: dexAsset.MaxFeeRate,
}
time.Sleep(time.Second)
receipts, _, _, err = rig.gamma().Swap(swaps)
if err != nil {
t.Fatalf("error sending swap transaction: %v", err)
}
if len(receipts) != 1 {
t.Fatalf("expected 1 receipt, got %d", len(receipts))
}
swapReceipt = receipts[0]
_, err = rig.gamma().Refund(swapReceipt.Coin().ID(), swapReceipt.Contract())
if err != nil {
t.Fatalf("refund error: %v", err)
}
// Test PayFee
coin, err := rig.gamma().PayFee(address, 1e8)
if err != nil {
t.Fatalf("error paying fees: %v", err)
}
tLogger.Infof("fee paid with tx %s", coin.String())
// Test Withdraw
coin, err = rig.gamma().Withdraw(address, 5e7)
if err != nil {
t.Fatalf("error withdrawing: %v", err)
}
tLogger.Infof("withdrew with tx %s", coin.String())
}