Skip to content

[SDK] Disable onchain features if server doesn't allow them #533

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 12 additions & 3 deletions client/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -281,7 +281,10 @@ func config(ctx *cli.Context) error {
"boarding_descriptor_template": cfgData.BoardingDescriptorTemplate,
"explorer_url": cfgData.ExplorerURL,
"forfeit_address": cfgData.ForfeitAddress,
"with_transaction_feed": cfgData.WithTransactionFeed,
"utxo_min_amount": cfgData.UtxoMinAmount,
"utxo_max_amount": cfgData.UtxoMaxAmount,
"vtxo_min_amount": cfgData.VtxoMinAmount,
"vtxo_max_amount": cfgData.VtxoMaxAmount,
}

return printJSON(cfg)
Expand Down Expand Up @@ -578,11 +581,17 @@ func sendCovenantLess(ctx *cli.Context, receivers []arksdk.Receiver, withZeroFee
}
}

computeExpiration := ctx.Bool(enableExpiryCoinselectFlag.Name)
if len(onchainReceivers) > 0 {
return fmt.Errorf("onchain receivers not allowed")
txid, err := arkSdkClient.CollaborativeExit(
ctx.Context, onchainReceivers[0].To(), onchainReceivers[0].Amount(), computeExpiration,
)
if err != nil {
return err
}
return printJSON(map[string]string{"txid": txid})
}

computeExpiration := ctx.Bool(enableExpiryCoinselectFlag.Name)
redeemTx, err := arkSdkClient.SendOffChain(
ctx.Context, computeExpiration, offchainReceivers, withZeroFees,
)
Expand Down
16 changes: 15 additions & 1 deletion pkg/client-sdk/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -103,11 +103,19 @@ func (a *arkClient) Dump(ctx context.Context) (string, error) {
}

func (a *arkClient) Receive(ctx context.Context) (string, string, error) {
if a.wallet == nil {
return "", "", fmt.Errorf("wallet not initialized")
}

offchainAddr, boardingAddr, err := a.wallet.NewAddress(ctx, false)
if err != nil {
return "", "", err
}

if a.Config.UtxoMaxAmount == 0 {
boardingAddr.Address = ""
}

return offchainAddr.Address, boardingAddr.Address, nil
}

Expand Down Expand Up @@ -136,7 +144,9 @@ func (a *arkClient) Reset(ctx context.Context) {
if a.txStreamCtxCancel != nil {
a.txStreamCtxCancel()
}
a.store.Clean(ctx)
if a.store != nil {
a.store.Clean(ctx)
}
}

func (a *arkClient) Stop() error {
Expand Down Expand Up @@ -173,6 +183,10 @@ func (a *arkClient) ListVtxos(
func (a *arkClient) NotifyIncomingFunds(
ctx context.Context, addr string,
) ([]types.Vtxo, error) {
if a.client == nil {
return nil, fmt.Errorf("wallet not initialized")
}

eventCh, closeFn, err := a.client.SubscribeForAddress(ctx, addr)
if err != nil {
return nil, err
Expand Down
180 changes: 123 additions & 57 deletions pkg/client-sdk/covenantless_client.go
Original file line number Diff line number Diff line change
Expand Up @@ -194,7 +194,9 @@ func LoadCovenantlessClient(sdkStore types.Store) (ArkClient, error) {
return nil, err
}
go covenantlessClient.listenForArkTxs(txStreamCtx)
go covenantlessClient.listenForBoardingTxs(txStreamCtx)
if cfgData.UtxoMaxAmount != 0 {
go covenantlessClient.listenForBoardingTxs(txStreamCtx)
}
}

return &covenantlessClient, nil
Expand Down Expand Up @@ -248,7 +250,9 @@ func LoadCovenantlessClientWithWallet(
return nil, err
}
go covenantlessClient.listenForArkTxs(txStreamCtx)
go covenantlessClient.listenForBoardingTxs(txStreamCtx)
if cfgData.UtxoMaxAmount != 0 {
go covenantlessClient.listenForBoardingTxs(txStreamCtx)
}
}

return &covenantlessClient, nil
Expand All @@ -266,7 +270,9 @@ func (a *covenantlessArkClient) Init(ctx context.Context, args InitArgs) error {
return err
}
go a.listenForArkTxs(txStreamCtx)
go a.listenForBoardingTxs(txStreamCtx)
if a.Config.UtxoMaxAmount != 0 {
go a.listenForBoardingTxs(txStreamCtx)
}
}

return nil
Expand All @@ -284,7 +290,9 @@ func (a *covenantlessArkClient) InitWithWallet(ctx context.Context, args InitWit
return err
}
go a.listenForArkTxs(txStreamCtx)
go a.listenForBoardingTxs(txStreamCtx)
if a.Config.UtxoMaxAmount != 0 {
go a.listenForBoardingTxs(txStreamCtx)
}
}

return nil
Expand All @@ -293,11 +301,34 @@ func (a *covenantlessArkClient) InitWithWallet(ctx context.Context, args InitWit
func (a *covenantlessArkClient) Balance(
ctx context.Context, computeVtxoExpiration bool,
) (*Balance, error) {
if a.wallet == nil {
return nil, fmt.Errorf("wallet not initialized")
}

offchainAddrs, boardingAddrs, redeemAddrs, err := a.wallet.GetAddresses(ctx)
if err != nil {
return nil, err
}

if a.Config.UtxoMaxAmount == 0 {
balance, amountByExpiration, err := a.getOffchainBalance(
ctx, computeVtxoExpiration,
)
if err != nil {
return nil, err
}

nextExpiration, details := getOffchainBalanceDetails(amountByExpiration)

return &Balance{
OffchainBalance: OffchainBalance{
Total: balance,
NextExpiration: getFancyTimeExpiration(nextExpiration),
Details: details,
},
}, nil
}

const nbWorkers = 3
wg := &sync.WaitGroup{}
wg.Add(nbWorkers * len(offchainAddrs))
Expand Down Expand Up @@ -362,22 +393,8 @@ func (a *covenantlessArkClient) Balance(
if res.onchainSpendableBalance > 0 {
onchainBalance += res.onchainSpendableBalance
}
if res.offchainBalanceByExpiration != nil {
for timestamp, amount := range res.offchainBalanceByExpiration {
if nextExpiration == 0 || timestamp < nextExpiration {
nextExpiration = timestamp
}
nextExpiration, details = getOffchainBalanceDetails(res.offchainBalanceByExpiration)

fancyTime := time.Unix(timestamp, 0).Format(time.RFC3339)
details = append(
details,
VtxoDetails{
ExpiryTime: fancyTime,
Amount: amount,
},
)
}
}
if res.onchainLockedBalance != nil {
for timestamp, amount := range res.onchainLockedBalance {
fancyTime := time.Unix(timestamp, 0).Format(time.RFC3339)
Expand All @@ -397,43 +414,17 @@ func (a *covenantlessArkClient) Balance(
}
}

fancyTimeExpiration := ""
if nextExpiration != 0 {
t := time.Unix(nextExpiration, 0)
if t.Before(time.Now().Add(48 * time.Hour)) {
// print the duration instead of the absolute time
until := time.Until(t)
seconds := math.Abs(until.Seconds())
minutes := math.Abs(until.Minutes())
hours := math.Abs(until.Hours())

if hours < 1 {
if minutes < 1 {
fancyTimeExpiration = fmt.Sprintf("%d seconds", int(seconds))
} else {
fancyTimeExpiration = fmt.Sprintf("%d minutes", int(minutes))
}
} else {
fancyTimeExpiration = fmt.Sprintf("%d hours", int(hours))
}
} else {
fancyTimeExpiration = t.Format(time.RFC3339)
}
}

response := &Balance{
return &Balance{
OnchainBalance: OnchainBalance{
SpendableAmount: onchainBalance,
LockedAmount: lockedOnchainBalance,
},
OffchainBalance: OffchainBalance{
Total: offchainBalance,
NextExpiration: fancyTimeExpiration,
NextExpiration: getFancyTimeExpiration(nextExpiration),
Details: details,
},
}

return response, nil
}, nil
}

func (a *covenantlessArkClient) OnboardAgainAllExpiredBoardings(
Expand All @@ -443,6 +434,10 @@ func (a *covenantlessArkClient) OnboardAgainAllExpiredBoardings(
return "", err
}

if a.Config.UtxoMaxAmount == 0 {
return "", fmt.Errorf("operation not allowed by the server")
}

_, boardingAddr, err := a.wallet.NewAddress(ctx, false)
if err != nil {
return "", err
Expand Down Expand Up @@ -470,6 +465,10 @@ func (a *covenantlessArkClient) SendOffChain(
withExpiryCoinselect bool, receivers []Receiver,
withZeroFees bool,
) (string, error) {
if err := a.safeCheck(); err != nil {
return "", err
}

if len(receivers) <= 0 {
return "", fmt.Errorf("missing receivers")
}
Expand Down Expand Up @@ -593,6 +592,10 @@ func (a *covenantlessArkClient) SendOffChain(
}

func (a *covenantlessArkClient) RedeemNotes(ctx context.Context, notes []string, opts ...Option) (string, error) {
if err := a.safeCheck(); err != nil {
return "", err
}

amount := uint64(0)

options := &SettleOptions{}
Expand Down Expand Up @@ -704,17 +707,21 @@ func (a *covenantlessArkClient) CollaborativeExit(
addr string, amount uint64, withExpiryCoinselect bool,
opts ...Option,
) (string, error) {
if err := a.safeCheck(); err != nil {
return "", err
}

if a.Config.UtxoMaxAmount == 0 {
return "", fmt.Errorf("operation not allowed by the server")
}

options := &SettleOptions{}
for _, opt := range opts {
if err := opt(options); err != nil {
return "", err
}
}

if a.wallet.IsLocked() {
return "", fmt.Errorf("wallet is locked")
}

netParams := utils.ToBitcoinNetwork(a.Network)
if _, err := btcutil.DecodeAddress(addr, &netParams); err != nil {
return "", fmt.Errorf("invalid onchain address")
Expand Down Expand Up @@ -803,14 +810,18 @@ func (a *covenantlessArkClient) CollaborativeExit(
}

func (a *covenantlessArkClient) Settle(ctx context.Context, opts ...Option) (string, error) {
if err := a.safeCheck(); err != nil {
return "", err
}

return a.sendOffchain(ctx, false, nil, opts...)
}

func (a *covenantlessArkClient) GetTransactionHistory(
ctx context.Context,
) ([]types.Transaction, error) {
if a.Config == nil {
return nil, fmt.Errorf("client not initialized")
if err := a.safeCheck(); err != nil {
return nil, err
}

if a.Config.WithTransactionFeed {
Expand Down Expand Up @@ -1002,10 +1013,16 @@ func (a *covenantlessArkClient) refreshDb(ctx context.Context) error {
if err != nil {
return err
}
boardingTxs, roundsToIgnore, err := a.getBoardingTxs(ctx)
if err != nil {
return err

boardingTxs := make([]types.Transaction, 0)
roundsToIgnore := make(map[string]struct{})
if a.Config.UtxoMaxAmount != 0 {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@altafan imagine the following scenario:

  • user is using Fulmine for a few weeks, made a couple of boarding txs
  • yesterday the server decided to stop allowing UTXO tx, so UtxoMaxAmount is now 0
  • does this code means that today the user will stop seeing the past boarding txs in his history?

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actually, this is what happens:

  • I received 4 boarding txs of 21, 32, 44 and 50 k sats
  • I received 2 offchain txs of 4 and 5 k sats
  • Then I put UTXO_MAX_AMOUNT=0 on server and restore Fulmine wallet
  • Now I see JUST ONE boarding tx with the total value of 147 k sats (the value is correct btw)

Screenshot 2025-04-21 at 11 03 25

boardingTxs, roundsToIgnore, err = a.getBoardingTxs(ctx)
if err != nil {
return err
}
}

offchainTxs, err := vtxosToTxsCovenantless(spendableVtxos, spentVtxos, roundsToIgnore)
if err != nil {
return err
Expand Down Expand Up @@ -3371,6 +3388,55 @@ func inputsToDerivationPath(inputs []client.Outpoint, notesInputs []string) stri
return path
}

func getOffchainBalanceDetails(amountByExpiration map[int64]uint64) (int64, []VtxoDetails) {
nextExpiration := int64(0)
details := make([]VtxoDetails, 0)
for timestamp, amount := range amountByExpiration {
if nextExpiration == 0 || timestamp < nextExpiration {
nextExpiration = timestamp
}

fancyTime := time.Unix(timestamp, 0).Format(time.RFC3339)
details = append(
details,
VtxoDetails{
ExpiryTime: fancyTime,
Amount: amount,
},
)
}
return nextExpiration, details
}

func getFancyTimeExpiration(nextExpiration int64) string {
if nextExpiration == 0 {
return ""
}

fancyTimeExpiration := ""
t := time.Unix(nextExpiration, 0)
if t.Before(time.Now().Add(48 * time.Hour)) {
// print the duration instead of the absolute time
until := time.Until(t)
seconds := math.Abs(until.Seconds())
minutes := math.Abs(until.Minutes())
hours := math.Abs(until.Hours())

if hours < 1 {
if minutes < 1 {
fancyTimeExpiration = fmt.Sprintf("%d seconds", int(seconds))
} else {
fancyTimeExpiration = fmt.Sprintf("%d minutes", int(minutes))
}
} else {
fancyTimeExpiration = fmt.Sprintf("%d hours", int(hours))
}
} else {
fancyTimeExpiration = t.Format(time.RFC3339)
}
return fancyTimeExpiration
}

func toTypesVtxo(src client.Vtxo) types.Vtxo {
return types.Vtxo{
VtxoKey: types.VtxoKey{
Expand Down
4 changes: 4 additions & 0 deletions pkg/client-sdk/store/file/config_store.go
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,10 @@ func (s *configStore) AddData(ctx context.Context, data types.Config) error {
MarketHourEndTime: fmt.Sprintf("%d", data.MarketHourEndTime),
MarketHourPeriod: fmt.Sprintf("%d", data.MarketHourPeriod),
MarketHourRoundInterval: fmt.Sprintf("%d", data.MarketHourRoundInterval),
UtxoMinAmount: fmt.Sprintf("%d", data.UtxoMinAmount),
UtxoMaxAmount: fmt.Sprintf("%d", data.UtxoMaxAmount),
VtxoMinAmount: fmt.Sprintf("%d", data.VtxoMinAmount),
VtxoMaxAmount: fmt.Sprintf("%d", data.VtxoMaxAmount),
}

if err := s.write(sd); err != nil {
Expand Down
Loading