Skip to content

Commit c7d2160

Browse files
committed
add all in one commit for the moment
1 parent 396f2f5 commit c7d2160

24 files changed

+2258
-250
lines changed

cmd/loop/staticaddr.go

Lines changed: 116 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,13 @@ package main
22

33
import (
44
"context"
5+
"encoding/hex"
6+
"errors"
57
"fmt"
8+
"strconv"
9+
"strings"
610

11+
"github.com/btcsuite/btcd/chaincfg/chainhash"
712
"github.com/lightninglabs/loop/looprpc"
813
"github.com/urfave/cli"
914
)
@@ -16,6 +21,7 @@ var staticAddressCommands = cli.Command{
1621
Subcommands: []cli.Command{
1722
newStaticAddressCommand,
1823
listUnspentCommand,
24+
withdrawalCommand,
1925
},
2026
}
2127

@@ -104,3 +110,113 @@ func listUnspent(ctx *cli.Context) error {
104110

105111
return nil
106112
}
113+
114+
var withdrawalCommand = cli.Command{
115+
Name: "withdraw",
116+
ShortName: "w",
117+
Usage: "Withdraw from static address deposits.",
118+
Description: `
119+
Withdraws from all or selected static address deposits by sweeping them
120+
back to our lnd wallet.
121+
`,
122+
Flags: []cli.Flag{
123+
cli.StringSliceFlag{
124+
Name: "utxo",
125+
Usage: "specify utxos as outpoints(tx:idx) which will" +
126+
"be closed.",
127+
},
128+
cli.BoolFlag{
129+
Name: "all",
130+
Usage: "withdraws all static address deposits.",
131+
},
132+
},
133+
Action: withdraw,
134+
}
135+
136+
func withdraw(ctx *cli.Context) error {
137+
if ctx.NArg() > 0 {
138+
return cli.ShowCommandHelp(ctx, "withdraw")
139+
}
140+
141+
client, cleanup, err := getClient(ctx)
142+
if err != nil {
143+
return err
144+
}
145+
defer cleanup()
146+
147+
var (
148+
req = &looprpc.WithdrawDepositsRequest{}
149+
isAllSelected = ctx.IsSet("all")
150+
isUtxoSelected = ctx.IsSet("utxo")
151+
outpoints []*looprpc.OutPoint
152+
ctxb = context.Background()
153+
)
154+
155+
switch {
156+
case isAllSelected == isUtxoSelected:
157+
return errors.New("must select either all or some utxos")
158+
159+
case isAllSelected:
160+
case isUtxoSelected:
161+
utxos := ctx.StringSlice("utxo")
162+
outpoints, err = utxosToOutpoints(utxos)
163+
if err != nil {
164+
return err
165+
}
166+
167+
req.Outpoints = outpoints
168+
169+
default:
170+
return fmt.Errorf("unknown withdrawal request")
171+
}
172+
173+
resp, err := client.WithdrawDeposits(ctxb, &looprpc.WithdrawDepositsRequest{
174+
Outpoints: outpoints,
175+
All: isAllSelected,
176+
})
177+
if err != nil {
178+
return err
179+
}
180+
181+
printRespJSON(resp)
182+
183+
return nil
184+
}
185+
186+
func utxosToOutpoints(utxos []string) ([]*looprpc.OutPoint, error) {
187+
var outpoints []*looprpc.OutPoint
188+
if len(utxos) == 0 {
189+
return nil, fmt.Errorf("no utxos specified")
190+
}
191+
for _, utxo := range utxos {
192+
outpoint, err := NewProtoOutPoint(utxo)
193+
if err != nil {
194+
return nil, err
195+
}
196+
outpoints = append(outpoints, outpoint)
197+
}
198+
199+
return outpoints, nil
200+
}
201+
202+
// NewProtoOutPoint parses an OutPoint into its corresponding lnrpc.OutPoint
203+
// type.
204+
func NewProtoOutPoint(op string) (*looprpc.OutPoint, error) {
205+
parts := strings.Split(op, ":")
206+
if len(parts) != 2 {
207+
return nil, errors.New("outpoint should be of the form " +
208+
"txid:index")
209+
}
210+
txid := parts[0]
211+
if hex.DecodedLen(len(txid)) != chainhash.HashSize {
212+
return nil, fmt.Errorf("invalid hex-encoded txid %v", txid)
213+
}
214+
outputIndex, err := strconv.Atoi(parts[1])
215+
if err != nil {
216+
return nil, fmt.Errorf("invalid output index: %v", err)
217+
}
218+
return &looprpc.OutPoint{
219+
TxidStr: txid,
220+
OutputIndex: uint32(outputIndex),
221+
}, nil
222+
}

loopd/daemon.go

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ import (
2323
loop_looprpc "github.com/lightninglabs/loop/looprpc"
2424
"github.com/lightninglabs/loop/staticaddr/address"
2525
"github.com/lightninglabs/loop/staticaddr/deposit"
26+
"github.com/lightninglabs/loop/staticaddr/withdraw"
2627
loop_swaprpc "github.com/lightninglabs/loop/swapserverrpc"
2728
"github.com/lightninglabs/loop/sweepbatcher"
2829
"github.com/lightningnetwork/lnd/clock"
@@ -437,6 +438,12 @@ func (d *Daemon) initialize(withMacaroonService bool) error {
437438
swapClient.Conn,
438439
)
439440

441+
// Create a static address client that cooperatively closes deposits
442+
// with the server.
443+
withdrawalClient := loop_swaprpc.NewWithdrawalServerClient(
444+
swapClient.Conn,
445+
)
446+
440447
// Both the client RPC server and the swap server client should stop
441448
// on main context cancel. So we create it early and pass it down.
442449
d.mainCtx, d.mainCtxCancel = context.WithCancel(context.Background())
@@ -500,6 +507,7 @@ func (d *Daemon) initialize(withMacaroonService bool) error {
500507

501508
staticAddressManager *address.Manager
502509
depositManager *deposit.Manager
510+
withdrawalManager *withdraw.Manager
503511
)
504512
// Create the reservation and instantout managers.
505513
if d.cfg.EnableExperimental {
@@ -561,6 +569,18 @@ func (d *Daemon) initialize(withMacaroonService bool) error {
561569
Signer: d.lnd.Signer,
562570
}
563571
depositManager = deposit.NewManager(depoCfg)
572+
573+
// Static address deposit withdrawal manager setup.
574+
closeCfg := &withdraw.ManagerConfig{
575+
WithdrawalServerClient: withdrawalClient,
576+
AddressManager: staticAddressManager,
577+
DepositManager: depositManager,
578+
WalletKit: d.lnd.WalletKit,
579+
ChainParams: d.lnd.ChainParams,
580+
ChainNotifier: d.lnd.ChainNotifier,
581+
Signer: d.lnd.Signer,
582+
}
583+
withdrawalManager = withdraw.NewManager(closeCfg)
564584
}
565585

566586
// Now finally fully initialize the swap client RPC server instance.
@@ -578,6 +598,7 @@ func (d *Daemon) initialize(withMacaroonService bool) error {
578598
instantOutManager: instantOutManager,
579599
staticAddressManager: staticAddressManager,
580600
depositManager: depositManager,
601+
withdrawalManager: withdrawalManager,
581602
}
582603

583604
// Retrieve all currently existing swaps from the database.
@@ -709,6 +730,32 @@ func (d *Daemon) initialize(withMacaroonService bool) error {
709730
depositManager.WaitInitComplete()
710731
}
711732

733+
// Start the static address deposit withdrawal manager.
734+
if withdrawalManager != nil {
735+
d.wg.Add(1)
736+
go func() {
737+
defer d.wg.Done()
738+
739+
// Lnd's GetInfo call supplies us with the current block
740+
// height.
741+
info, err := d.lnd.Client.GetInfo(d.mainCtx)
742+
if err != nil {
743+
d.internalErrChan <- err
744+
return
745+
}
746+
747+
log.Info("Starting static address deposit withdrawal " +
748+
"manager...")
749+
err = withdrawalManager.Run(d.mainCtx, info.BlockHeight)
750+
if err != nil && !errors.Is(context.Canceled, err) {
751+
d.internalErrChan <- err
752+
}
753+
log.Info("Static address deposit withdrawal manager " +
754+
"stopped")
755+
}()
756+
withdrawalManager.WaitInitComplete()
757+
}
758+
712759
// Last, start our internal error handler. This will return exactly one
713760
// error or nil on the main error channel to inform the caller that
714761
// something went wrong or that shutdown is complete. We don't add to

loopd/perms/perms.go

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -83,6 +83,13 @@ var RequiredPermissions = map[string][]bakery.Op{
8383
Entity: "loop",
8484
Action: "in",
8585
}},
86+
"/looprpc.SwapClient/WithdrawDeposits": {{
87+
Entity: "swap",
88+
Action: "execute",
89+
}, {
90+
Entity: "loop",
91+
Action: "in",
92+
}},
8693
"/looprpc.SwapClient/GetLsatTokens": {{
8794
Entity: "auth",
8895
Action: "read",

loopd/swapclient_server.go

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ import (
1515
"github.com/btcsuite/btcd/btcec/v2"
1616
"github.com/btcsuite/btcd/btcutil"
1717
"github.com/btcsuite/btcd/chaincfg"
18+
"github.com/btcsuite/btcd/wire"
1819
"github.com/lightninglabs/aperture/lsat"
1920
"github.com/lightninglabs/lndclient"
2021
"github.com/lightninglabs/loop"
@@ -26,6 +27,7 @@ import (
2627
clientrpc "github.com/lightninglabs/loop/looprpc"
2728
"github.com/lightninglabs/loop/staticaddr/address"
2829
"github.com/lightninglabs/loop/staticaddr/deposit"
30+
"github.com/lightninglabs/loop/staticaddr/withdraw"
2931
"github.com/lightninglabs/loop/swap"
3032
looprpc "github.com/lightninglabs/loop/swapserverrpc"
3133
"github.com/lightningnetwork/lnd/lnrpc/walletrpc"
@@ -87,6 +89,7 @@ type swapClientServer struct {
8789
instantOutManager *instantout.Manager
8890
staticAddressManager *address.Manager
8991
depositManager *deposit.Manager
92+
withdrawalManager *withdraw.Manager
9093
swaps map[lntypes.Hash]loop.SwapInfo
9194
subscribers map[int]chan<- interface{}
9295
statusChan chan loop.SwapInfo
@@ -1278,6 +1281,67 @@ func (s *swapClientServer) ListUnspent(ctx context.Context,
12781281
return &clientrpc.ListUnspentResponse{Utxos: respUtxos}, nil
12791282
}
12801283

1284+
// WithdrawDeposits tries to obtain a partial signature from the server to spend
1285+
// the selected deposits to the client's wallet.
1286+
func (s *swapClientServer) WithdrawDeposits(ctx context.Context,
1287+
req *clientrpc.WithdrawDepositsRequest) (
1288+
*clientrpc.WithdrawDepositsResponse, error) {
1289+
1290+
var (
1291+
isAllSelected = req.All
1292+
isUtxoSelected = req.Outpoints != nil
1293+
outpoints []wire.OutPoint
1294+
err error
1295+
)
1296+
1297+
switch {
1298+
case isAllSelected == isUtxoSelected:
1299+
return nil, fmt.Errorf("must select either all or some utxos")
1300+
1301+
case isAllSelected:
1302+
deposits, err := s.depositManager.GetActiveDepositsInState(
1303+
deposit.Deposited,
1304+
)
1305+
if err != nil {
1306+
return nil, err
1307+
}
1308+
1309+
for _, d := range deposits {
1310+
outpoints = append(outpoints, d.OutPoint)
1311+
}
1312+
1313+
case isUtxoSelected:
1314+
outpoints, err = toServerOutpoints(req.Outpoints)
1315+
if err != nil {
1316+
return nil, err
1317+
}
1318+
}
1319+
1320+
err = s.withdrawalManager.WithdrawDeposits(ctx, outpoints)
1321+
if err != nil {
1322+
return nil, err
1323+
}
1324+
1325+
return &clientrpc.WithdrawDepositsResponse{}, err
1326+
}
1327+
1328+
func toServerOutpoints(outpoints []*clientrpc.OutPoint) ([]wire.OutPoint,
1329+
error) {
1330+
1331+
var serverOutpoints []wire.OutPoint
1332+
for _, o := range outpoints {
1333+
outpointStr := fmt.Sprintf("%s:%d", o.TxidStr, o.OutputIndex)
1334+
newOutpoint, err := wire.NewOutPointFromString(outpointStr)
1335+
if err != nil {
1336+
return nil, err
1337+
}
1338+
1339+
serverOutpoints = append(serverOutpoints, *newOutpoint)
1340+
}
1341+
1342+
return serverOutpoints, nil
1343+
}
1344+
12811345
func rpcAutoloopReason(reason liquidity.Reason) (clientrpc.AutoReason, error) {
12821346
switch reason {
12831347
case liquidity.ReasonNone:

loopdb/sqlc/migrations/000008_static_address_deposits.up.sql

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,11 @@ CREATE TABLE IF NOT EXISTS deposits (
2121

2222
-- timeout_sweep_pk_script is the public key script that will be used to
2323
-- sweep the deposit after has expired.
24-
timeout_sweep_pk_script BYTEA NOT NULL
24+
timeout_sweep_pk_script BYTEA NOT NULL,
25+
26+
-- withdrawal_sweep_pk_script is the address that will be used to sweep the
27+
-- deposit cooperatively with the server before it has expired.
28+
withdrawal_sweep_address TEXT
2529
);
2630

2731
-- deposit_updates contains all the updates to a deposit.

loopdb/sqlc/models.go

Lines changed: 8 additions & 7 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

loopdb/sqlc/queries/static_address_deposits.sql

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,22 +5,25 @@ INSERT INTO deposits (
55
out_index,
66
amount,
77
confirmation_height,
8-
timeout_sweep_pk_script
8+
timeout_sweep_pk_script,
9+
withdrawal_sweep_address
910
) VALUES (
1011
$1,
1112
$2,
1213
$3,
1314
$4,
1415
$5,
15-
$6
16+
$6,
17+
$7
1618
);
1719

1820
-- name: UpdateDeposit :exec
1921
UPDATE deposits
2022
SET
2123
tx_hash = $2,
2224
out_index = $3,
23-
confirmation_height = $4
25+
confirmation_height = $4,
26+
withdrawal_sweep_address = $5
2427
WHERE
2528
deposits.deposit_id = $1;
2629

0 commit comments

Comments
 (0)