Skip to content

Commit

Permalink
chappjc 5
Browse files Browse the repository at this point in the history
  • Loading branch information
buck54321 committed Oct 18, 2021
1 parent 5ce2e16 commit 1d7f5a6
Show file tree
Hide file tree
Showing 16 changed files with 129 additions and 166 deletions.
45 changes: 7 additions & 38 deletions client/asset/btc/btc.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,6 @@ import (
"github.com/btcsuite/btcwallet/wallet"
"github.com/decred/dcrd/dcrjson/v4" // for dcrjson.RPCError returns from rpcclient
"github.com/decred/dcrd/rpcclient/v7"
"github.com/jrick/logrotate/rotator"
"golang.org/x/text/language"
)

const (
Expand Down Expand Up @@ -415,7 +413,6 @@ type Driver struct{}
// Check that Driver implements Driver and Creator.
var _ asset.Driver = (*Driver)(nil)
var _ asset.Creator = (*Driver)(nil)
var _ asset.Initializer = (*Driver)(nil)

// Exists checks the existence of the wallet. Part of the Creator interface, so
// only used for wallets with WalletDefinition.Seeded = true.
Expand Down Expand Up @@ -474,31 +471,6 @@ func (d *Driver) Info() *asset.WalletInfo {
return WalletInfo
}

var (
logRotator atomic.Value
teardownWaitGroup sync.WaitGroup
initialized uint32
)

// Initialize sets up a routine to close any existing log rotator.
func (d *Driver) Initialize(ctx context.Context, wg *sync.WaitGroup, logger dex.Logger, lang language.Tag) {
if !atomic.CompareAndSwapUint32(&initialized, 0, 1) {
return
}
wg.Add(1)
go func() {
defer wg.Done()
<-ctx.Done()
if rotatorI := logRotator.Load(); rotatorI != nil {
teardownWaitGroup.Wait()
rotator := rotatorI.(*rotator.Rotator)
if err := rotator.Close(); err != nil {
logger.Errorf("error closing log rotator: %v", err)
}
}
}()
}

func init() {
asset.Register(BipID, &Driver{})
}
Expand Down Expand Up @@ -615,9 +587,6 @@ func NewWallet(cfg *asset.WalletConfig, logger dex.Logger, net dex.Network) (ass

switch cfg.Type {
case walletTypeSPV:
if atomic.LoadUint32(&initialized) == 0 {
return nil, fmt.Errorf("must call asset.Initialize if you want to create an SPV wallet")
}
return openSPVWallet(cloneCFG)
case walletTypeRPC, walletTypeLegacy:
return BTCCloneWallet(cloneCFG)
Expand Down Expand Up @@ -1620,7 +1589,7 @@ func (btc *ExchangeWallet) Swap(swaps *asset.Swaps) ([]asset.Receipt, asset.Coin
txHash := msgTx.TxHash()
for i, contract := range swaps.Contracts {
output := newOutput(&txHash, uint32(i), contract.Value)
signedRefundTx, err := btc.refundTx(output.txHash(), output.vout(), contracts[i], contract.Value, refundAddrs[i])
signedRefundTx, err := btc.refundTx(output.txHash(), output.vout(), contracts[i], contract.Value, refundAddrs[i], swaps.FeeRate)
if err != nil {
return nil, nil, 0, fmt.Errorf("error creating refund tx: %w", err)
}
Expand Down Expand Up @@ -2202,7 +2171,7 @@ func (btc *ExchangeWallet) tryRedemptionRequests(ctx context.Context, startBlock
// wallet does not store it, even though it was known when the init transaction
// was created. The client should store this information for persistence across
// sessions.
func (btc *ExchangeWallet) Refund(coinID, contract dex.Bytes) (dex.Bytes, error) {
func (btc *ExchangeWallet) Refund(coinID, contract dex.Bytes, feeSuggestion uint64) (dex.Bytes, error) {
txHash, vout, err := decodeCoinID(coinID)
if err != nil {
return nil, err
Expand All @@ -2220,7 +2189,7 @@ func (btc *ExchangeWallet) Refund(coinID, contract dex.Bytes) (dex.Bytes, error)
if utxo == nil {
return nil, asset.CoinNotFoundError
}
msgTx, err := btc.refundTx(txHash, vout, contract, uint64(utxo.Value), nil)
msgTx, err := btc.refundTx(txHash, vout, contract, uint64(utxo.Value), nil, feeSuggestion)
if err != nil {
return nil, fmt.Errorf("error creating refund tx: %w", err)
}
Expand All @@ -2239,14 +2208,14 @@ func (btc *ExchangeWallet) Refund(coinID, contract dex.Bytes) (dex.Bytes, error)

// refundTx creates and signs a contract`s refund transaction. If refundAddr is
// not supplied, one will be requested from the wallet.
func (btc *ExchangeWallet) refundTx(txHash *chainhash.Hash, vout uint32, contract dex.Bytes, val uint64, refundAddr btcutil.Address) (*wire.MsgTx, error) {
func (btc *ExchangeWallet) refundTx(txHash *chainhash.Hash, vout uint32, contract dex.Bytes, val uint64, refundAddr btcutil.Address, feeSuggestion uint64) (*wire.MsgTx, error) {
sender, _, lockTime, _, err := dexbtc.ExtractSwapDetails(contract, btc.segwit, btc.chainParams)
if err != nil {
return nil, fmt.Errorf("error extracting swap addresses: %w", err)
}

// Create the transaction that spends the contract.
feeRate := btc.feeRateWithFallback(2, 0) // meh level urgency
feeRate := btc.feeRateWithFallback(2, feeSuggestion) // meh level urgency
msgTx := wire.NewMsgTx(wire.TxVersion)
msgTx.LockTime = uint32(lockTime)
prevOut := wire.NewOutPoint(txHash, vout)
Expand Down Expand Up @@ -2329,8 +2298,8 @@ func (btc *ExchangeWallet) PayFee(address string, regFee, feeRateSuggestion uint

// Withdraw withdraws funds to the specified address. Fees are subtracted from
// the value. feeRate is in units of atoms/byte.
func (btc *ExchangeWallet) Withdraw(address string, value uint64) (asset.Coin, error) {
txHash, vout, sent, err := btc.send(address, value, btc.feeRateWithFallback(2, 0), true)
func (btc *ExchangeWallet) Withdraw(address string, value, feeSuggestion uint64) (asset.Coin, error) {
txHash, vout, sent, err := btc.send(address, value, btc.feeRateWithFallback(2, feeSuggestion), true)
if err != nil {
btc.log.Errorf("Withdraw error - address = '%s', amount = %s: %v", address, amount(value), err)
return nil, err
Expand Down
14 changes: 8 additions & 6 deletions client/asset/btc/btc_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2139,6 +2139,7 @@ func testRefund(t *testing.T, segwit bool, walletType string) {
bigTxOut := newTxOutResult(nil, 1e8, 2)
node.txOutRes = bigTxOut // rpc
node.changeAddr = addr.String()
const feeSuggestion = 100

privBytes, _ := hex.DecodeString("b07209eec1a8fb6cfe5cb6ace36567406971a75c330db7101fb21bc679bc5330")
privKey, _ := btcec.PrivKeyFromBytes(btcec.S256(), privBytes)
Expand All @@ -2158,7 +2159,7 @@ func testRefund(t *testing.T, segwit bool, walletType string) {
node.getTransactionErr = WalletTransactionNotFound

contractOutput := newOutput(&txHash, 0, 1e8)
_, err = wallet.Refund(contractOutput.ID(), contract)
_, err = wallet.Refund(contractOutput.ID(), contract, feeSuggestion)
if err != nil {
t.Fatalf("refund error: %v", err)
}
Expand All @@ -2167,14 +2168,14 @@ func testRefund(t *testing.T, segwit bool, walletType string) {
badReceipt := &tReceipt{
coin: &tCoin{id: make([]byte, 15)},
}
_, err = wallet.Refund(badReceipt.coin.id, badReceipt.Contract())
_, err = wallet.Refund(badReceipt.coin.id, badReceipt.Contract(), feeSuggestion)
if err == nil {
t.Fatalf("no error for bad receipt")
}

ensureErr := func(tag string) {
delete(node.checkpoints, outPt)
_, err = wallet.Refund(contractOutput.ID(), contract)
_, err = wallet.Refund(contractOutput.ID(), contract, feeSuggestion)
if err == nil {
t.Fatalf("no error for %q", tag)
}
Expand All @@ -2190,7 +2191,7 @@ func testRefund(t *testing.T, segwit bool, walletType string) {
// bad contract
badContractOutput := newOutput(tTxHash, 0, 1e8)
badContract := randBytes(50)
_, err = wallet.Refund(badContractOutput.ID(), badContract)
_, err = wallet.Refund(badContractOutput.ID(), badContract, feeSuggestion)
if err == nil {
t.Fatalf("no error for bad contract")
}
Expand Down Expand Up @@ -2225,7 +2226,7 @@ func testRefund(t *testing.T, segwit bool, walletType string) {
node.badSendHash = nil

// Sanity check that we can succeed again.
_, err = wallet.Refund(contractOutput.ID(), contract)
_, err = wallet.Refund(contractOutput.ID(), contract, feeSuggestion)
if err != nil {
t.Fatalf("re-refund error: %v", err)
}
Expand Down Expand Up @@ -2285,12 +2286,13 @@ func testSender(t *testing.T, senderType tSenderType, segwit bool, walletType st
if err != nil {
t.Fatal(err)
}
const feeSuggestion = 100
sender := func(addr string, val uint64) (asset.Coin, error) {
return wallet.PayFee(addr, val, defaultFee)
}
if senderType == tWithdrawSender {
sender = func(addr string, val uint64) (asset.Coin, error) {
return wallet.Withdraw(addr, val)
return wallet.Withdraw(addr, val, feeSuggestion)
}
}
addr := btcAddr(segwit)
Expand Down
6 changes: 3 additions & 3 deletions client/asset/btc/livetest/livetest.go
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ func tBackend(ctx context.Context, t *testing.T, cfg *Config, node, name string,
},
}

w, err := cfg.New(walletCfg, logger, dex.Regtest)
w, err := cfg.NewWallet(walletCfg, logger, dex.Regtest)
if err != nil {
t.Fatalf("error creating backend: %v", err)
}
Expand Down Expand Up @@ -444,7 +444,7 @@ func Run(t *testing.T, cfg *Config) {
mine()
}

coinID, err := rig.gamma().Refund(swapReceipt.Coin().ID(), swapReceipt.Contract())
coinID, err := rig.gamma().Refund(swapReceipt.Coin().ID(), swapReceipt.Contract(), 100)
if err != nil {
t.Fatalf("refund error: %v", err)
}
Expand All @@ -462,7 +462,7 @@ func Run(t *testing.T, cfg *Config) {
tLogger.Info("Testing Withdraw")

// Test Withdraw
coin, err = rig.gamma().Withdraw(address, 5e7)
coin, err = rig.gamma().Withdraw(address, 5e7, 100)
if err != nil {
t.Fatalf("error withdrawing: %v", err)
}
Expand Down
49 changes: 22 additions & 27 deletions client/asset/btc/livetest/regnet_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ import (
"os/exec"
"os/user"
"path/filepath"
"sync"
"testing"
"time"

Expand All @@ -20,13 +19,13 @@ import (
"decred.org/dcrdex/dex"
"decred.org/dcrdex/dex/encode"
dexbtc "decred.org/dcrdex/dex/networks/btc"
"golang.org/x/text/language"
)

const (
alphaAddress = "bcrt1qaujcvxuvp9vdcqaa6s3acyh8kxmuyqnyg4jcfl"
betaAddress = "bcrt1qwhxklx3vms6xc0lxlunez93m9wn8qzxkkn5dy2"
gammaAddress = "bcrt1qll362edf4levwg7yqyt7kawjklvejvj74w87py"
alphaAddress = "bcrt1qaujcvxuvp9vdcqaa6s3acyh8kxmuyqnyg4jcfl"
betaAddress = "bcrt1qwhxklx3vms6xc0lxlunez93m9wn8qzxkkn5dy2"
gammaAddress = "bcrt1qll362edf4levwg7yqyt7kawjklvejvj74w87py"
walletTypeSPV = "SPV"
)

var (
Expand All @@ -46,25 +45,21 @@ var (
)

func TestWallet(t *testing.T) {
var ctx, cancel = context.WithCancel(context.Background())
defer cancel()
(&btc.Driver{}).Initialize(ctx, &sync.WaitGroup{}, dex.StdOutLogger("INIT", dex.LevelWarn), language.AmericanEnglish)

const lotSize = 1e6

fmt.Println("////////// RPC WALLET W/O SPLIT //////////")
Run(t, &Config{
New: btc.NewWallet,
LotSize: lotSize,
Asset: tBTC,
NewWallet: btc.NewWallet,
LotSize: lotSize,
Asset: tBTC,
})

fmt.Println("////////// RPC WALLET WITH SPLIT //////////")
Run(t, &Config{
New: btc.NewWallet,
LotSize: lotSize,
Asset: tBTC,
SplitTx: true,
NewWallet: btc.NewWallet,
LotSize: lotSize,
Asset: tBTC,
SplitTx: true,
})

spvDir, err := os.MkdirTemp("", "")
Expand All @@ -79,7 +74,7 @@ func TestWallet(t *testing.T) {
seed := encode.RandomBytes(32)

err = (&btc.Driver{}).Create(&asset.CreateWalletParams{
Type: btc.WalletTypeSPV,
Type: walletTypeSPV,
Seed: seed[:],
Pass: tPW, // match walletPassword in livetest.go -> Run
DataDir: cfg.DataDir,
Expand Down Expand Up @@ -139,7 +134,7 @@ func TestWallet(t *testing.T) {

spvConstructor := func(cfg *asset.WalletConfig, logger dex.Logger, network dex.Network) (asset.Wallet, error) {
token := hex.EncodeToString(encode.RandomBytes(4))
cfg.Type = btc.WalletTypeSPV
cfg.Type = walletTypeSPV
cfg.DataDir = filepath.Join(spvDir, token)

name := parseName(cfg.Settings)
Expand All @@ -164,19 +159,19 @@ func TestWallet(t *testing.T) {

fmt.Println("////////// SPV WALLET W/O SPLIT //////////")
Run(t, &Config{
New: spvConstructor,
LotSize: lotSize,
Asset: tBTC,
SPV: true,
NewWallet: spvConstructor,
LotSize: lotSize,
Asset: tBTC,
SPV: true,
})

fmt.Println("////////// SPV WALLET WITH SPLIT //////////")
Run(t, &Config{
New: spvConstructor,
LotSize: lotSize,
Asset: tBTC,
SPV: true,
SplitTx: true,
NewWallet: spvConstructor,
LotSize: lotSize,
Asset: tBTC,
SPV: true,
SplitTx: true,
})
}

Expand Down
Loading

0 comments on commit 1d7f5a6

Please sign in to comment.