Skip to content

Allow honoring reserve in send_all_to_address - #345

Merged
tnull merged 3 commits into
lightningdevkit:mainfrom
tnull:2024-08-regard-reserve-spending-all
Nov 11, 2024
Merged

Allow honoring reserve in send_all_to_address#345
tnull merged 3 commits into
lightningdevkit:mainfrom
tnull:2024-08-regard-reserve-spending-all

Conversation

@tnull

@tnulltnull commented Aug 16, 2024

Copy link
Copy Markdown
Collaborator

Previously, OnchainPayment::send_all_to_address could only be used to fully drain the onchain wallet, i.e., would not retain any reserves.

Here, we try to introduce a retain_reserves bool that allows users to send all funds while honoring the configured on-chain reserves. While we're at it, we move the reserve checks for send_to_address also to the internal wallet's method, which makes the checks more accurate as they now are checked against the final transaction value, including transaction fees.

This was requested by a user, but I'm a bit on the fence if we actually should move forward with it: for one, figuring out the spendable amount above the reserve is always gonna be inexact compared to draining the wallet.

Moreover, adding this to our API might send the wrong message of the reserve value being an exact value, while it's always on the safer side to maintain a larger reserve.

@tnull
tnull marked this pull request as draft August 16, 2024 14:47
@tnull
tnullforce-pushed the 2024-08-regard-reserve-spending-all branch from a020d7c to b62484aCompareAugust 16, 2024 15:20
@tnulltnull changed the title WIP: Allow honoring reserve in send_all_to_addressAllow honoring reserve in send_all_to_addressAug 27, 2024
@tnull
tnull marked this pull request as ready for review August 27, 2024 10:18
@jkczyz
jkczyz self-requested a review August 27, 2024 14:07
Comment threadsrc/wallet.rs Outdated
},
};

// Check the reserve requirements (again) and return an error if they aren't met.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Not sure I follow. Why is a second check needed?

@tnulltnullAug 28, 2024

Copy link
Copy Markdown
CollaboratorAuthor

Choose a reason for hiding this comment

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

The general issue is that we don't have a "send_all_but_X" method available, we can only set X amount or entirely drain the wallet (the latter of course resulting in not adding a change output). We also don't have any good tools to pre-compute the fee it gonna takes to construct a particular transaction without completely replicating BDK internals here (and even then you wouldn't be able to invert the fee estimation algorithm).

So the approach we took here is: construct a temporary draining transaction to estimate how much fees it would take, check that our available balance (i.e., the entire balance minus the reserve) is sufficient to cover the fee, then use this estimate to calculate how much above the reserve we're able to spend, and then construct the actual spending transaction with the estimated fee and the estimated spendable balance.

Once we did all that we now build the PSBT and check again that we're really able to spend what we just constructed without infringing on the reserve, and go ahead and sign it.

So TLDR: first round of checks are on the temporary transaction we use to estimate fees (and hence the spendable amount), second round of checks on the actual final transaction we try to spend.


let addr_b = node_b.onchain_payment().new_address().unwrap();
let txid = node_a.onchain_payment().send_all_to_address(&addr_b).unwrap();
let txid = node_a.onchain_payment().send_all_to_address(&addr_b, false).unwrap();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Could we additional test coverage?

Copy link
Copy Markdown
CollaboratorAuthor

Choose a reason for hiding this comment

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

Now added test coverage and discovered small issues around relayability (on regtest, at least). Therefore now finally got around to do a refactor of FeeEstimator that should allow us to configure these targets a little more fine-grained rather than misusing LDK's API (which we more ore less did before). Now based this PR on top of #352.

@tnull
tnullforce-pushed the 2024-08-regard-reserve-spending-all branch from b62484a to 2266163CompareAugust 29, 2024 11:00
@tnull

Copy link
Copy Markdown
CollaboratorAuthor

Now based on top of bitcoindevkit/bdk#352.

@tnull
tnullforce-pushed the 2024-08-regard-reserve-spending-all branch 3 times, most recently from 385fbe5 to 28fed4cCompareAugust 29, 2024 11:12
Comment threadsrc/wallet.rs Outdated
Comment on lines +262 to +275
tmp_tx_builder
.add_recipient(address.script_pubkey(), spendable_amount_sats)
.fee_rate(fee_rate)
.enable_rbf();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Couldn't this result in a transaction where the entire cur_anchor_reserve_sats goes to fees? And thus there could be one less output, which would cause the fee estimation to be off?

Would the following solve this?

let change_address = locked_wallet.get_internal_address(AddressIndex::Peek(0));
tmp_tx_builder
.drain_wallet().drain_to(address.script_pubkey()).add_recipient(change_address, cur_anchor_reserve_sats).fee_rate(fee_rate).enable_rbf();

Though if cur_anchor_reserve_sats was exactly covered by one utxo, then an extra input would be used in the estimation. 🤔

Copy link
Copy Markdown
CollaboratorAuthor

Choose a reason for hiding this comment

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

Couldn't this result in a transaction where the entire cur_anchor_reserve_sats goes to fees? And thus there could be one less output, which would cause the fee estimation to be off?

Yes, this could be the case, I think.

Would the following solve this?

let change_address = locked_wallet.get_internal_address(AddressIndex::Peek(0));
tmp_tx_builder
.drain_wallet().drain_to(address.script_pubkey()).add_recipient(change_address, cur_anchor_reserve_sats).fee_rate(fee_rate).enable_rbf();

Mhh, seems reasonable to assume that this would make the estimation a tad more precise, I'll add a fixup for this.

Though if cur_anchor_reserve_sats was exactly covered by one utxo, then an extra input would be used in the estimation. 🤔

Yes, this would be an edge case. Similarly, the coin selection algorithm might decide to omit outputs (if they'd end up to be dust, for example), which also would throw the calculation off.

Copy link
Copy Markdown
CollaboratorAuthor

Choose a reason for hiding this comment

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

Btw, curiously, at least in local small-scale testing, both approaches seem to result in virtually the same weight discrepancies between temporary and final transaction, while other factors (randomness in coin selection?) seem to have a bigger impact.

Comment threadsrc/wallet.rs Outdated
};

let estimated_tx_fee_sats =
tmp_tx_details.fee.unwrap_or(0).max(FEERATE_FLOOR_SATS_PER_KW as u64);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Shouldn't FEERATE_FLOOR_SATS_PER_KW be accounted for by the fee estimator when computing the fee_rate passed to the builder?

Copy link
Copy Markdown
CollaboratorAuthor

Choose a reason for hiding this comment

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

Yes, it's mostly a failsafe as we use the absolute estimated fee, not the fee rate. But you're right, assuming the estimation is reasonably close, we can probably omit this.

@tnull
tnullforce-pushed the 2024-08-regard-reserve-spending-all branch from 28fed4c to b0f8d6cCompareAugust 30, 2024 07:40
Comment threadsrc/wallet.rs Outdated
@tnulltnull mentioned this pull request Oct 8, 2024
10 tasks
@tnulltnull added this to the 0.5 milestone Oct 8, 2024
@tnull
tnullforce-pushed the 2024-08-regard-reserve-spending-all branch from b0f8d6c to 2bd4c68CompareNovember 8, 2024 13:08
@tnull
tnull requested a review from jkczyzNovember 8, 2024 13:09
@tnull

tnull commented Nov 8, 2024

Copy link
Copy Markdown
CollaboratorAuthor

Now rebased and adjusted to accommodate the BDK 1.0 API changes.

Should be ready for another round of re-review, @jkczyz.

Comment threadsrc/chain/mod.rs Outdated
Comment threadsrc/wallet/mod.rs Outdated
Comment threadsrc/wallet/mod.rs
Comment threadsrc/wallet/mod.rs Outdated
Comment threadtests/integration_tests_rust.rs Outdated
Comment threadtests/integration_tests_rust.rs Outdated
@tnull
tnullforce-pushed the 2024-08-regard-reserve-spending-all branch 2 times, most recently from 91207fb to 1eb0c0dCompareNovember 11, 2024 09:52

@jkczyzjkczyz left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

LGTM. Please squash.

.. while it's most often bitcoind already knowing about a transaction
already, the error sometimes holds additional information (e.g., not
meeting the mempool min).
Previously, `OnchainPayment::send_all_to_address` could only be used to
fully drain the onchain wallet, i.e., would not retain any reserves.
Here, we try to introduce a `retain_reserves` bool that allows users to
send all funds while honoring the configured on-chain reserves. While
we're at it, we move the reserve checks for `send_to_address` also to
the internal wallet's method, which makes the checks more accurate as
they now are checked against the final transaction value, including
transaction fees.
@tnull
tnullforce-pushed the 2024-08-regard-reserve-spending-all branch from 1eb0c0d to 91da460CompareNovember 11, 2024 17:54
@tnull

Copy link
Copy Markdown
CollaboratorAuthor

LGTM. Please squash.

Squashed fixups without further changes.

@tnull
tnull merged commit c08c3d5 into lightningdevkit:mainNov 11, 2024
Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants

@tnull@jkczyz
, 'i'); if (__m === '*' || __re.test(location.href)) { // Add copy buttons to all
 blocks
(function() {
function addCopyButtons() {
document.querySelectorAll('pre code').forEach(function(codeBlock) {
if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;
codeBlock.parentElement.setAttribute('data-copy-added', 'true');
var btn = document.createElement('button');
btn.textContent = 'Copy';
btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';
btn.onmouseover = function() { this.style.opacity = '1'; };
btn.onmouseout = function() { this.style.opacity = '0.7'; };
btn.onclick = function() {
navigator.clipboard.writeText(codeBlock.textContent).then(function() {
btn.textContent = 'Copied!';
setTimeout(function() { btn.textContent = 'Copy'; }, 1500);
});
};
codeBlock.parentElement.style.position = 'relative';
codeBlock.parentElement.appendChild(btn);
});
}
addCopyButtons();
// Re-run on dynamic content
var observer = new MutationObserver(addCopyButtons);
observer.observe(document.body, { childList: true, subtree: true });
})();
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Allow honoring reserve in `send_all_to_address` by tnull · Pull Request #345 · lightningdevkit/ldk-node · GitHub
Skip to content

Allow honoring reserve in send_all_to_address - #345

Merged
tnull merged 3 commits into
lightningdevkit:mainfrom
tnull:2024-08-regard-reserve-spending-all
Nov 11, 2024
Merged

Allow honoring reserve in send_all_to_address#345
tnull merged 3 commits into
lightningdevkit:mainfrom
tnull:2024-08-regard-reserve-spending-all

Conversation

@tnull

@tnulltnull commented Aug 16, 2024

Copy link
Copy Markdown
Collaborator

Previously, OnchainPayment::send_all_to_address could only be used to fully drain the onchain wallet, i.e., would not retain any reserves.

Here, we try to introduce a retain_reserves bool that allows users to send all funds while honoring the configured on-chain reserves. While we're at it, we move the reserve checks for send_to_address also to the internal wallet's method, which makes the checks more accurate as they now are checked against the final transaction value, including transaction fees.

This was requested by a user, but I'm a bit on the fence if we actually should move forward with it: for one, figuring out the spendable amount above the reserve is always gonna be inexact compared to draining the wallet.

Moreover, adding this to our API might send the wrong message of the reserve value being an exact value, while it's always on the safer side to maintain a larger reserve.

@tnull
tnull marked this pull request as draft August 16, 2024 14:47
@tnull
tnullforce-pushed the 2024-08-regard-reserve-spending-all branch from a020d7c to b62484aCompareAugust 16, 2024 15:20
@tnulltnull changed the title WIP: Allow honoring reserve in send_all_to_addressAllow honoring reserve in send_all_to_addressAug 27, 2024
@tnull
tnull marked this pull request as ready for review August 27, 2024 10:18
@jkczyz
jkczyz self-requested a review August 27, 2024 14:07
Comment threadsrc/wallet.rs Outdated
},
};

// Check the reserve requirements (again) and return an error if they aren't met.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Not sure I follow. Why is a second check needed?

@tnulltnullAug 28, 2024

Copy link
Copy Markdown
CollaboratorAuthor

Choose a reason for hiding this comment

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

The general issue is that we don't have a "send_all_but_X" method available, we can only set X amount or entirely drain the wallet (the latter of course resulting in not adding a change output). We also don't have any good tools to pre-compute the fee it gonna takes to construct a particular transaction without completely replicating BDK internals here (and even then you wouldn't be able to invert the fee estimation algorithm).

So the approach we took here is: construct a temporary draining transaction to estimate how much fees it would take, check that our available balance (i.e., the entire balance minus the reserve) is sufficient to cover the fee, then use this estimate to calculate how much above the reserve we're able to spend, and then construct the actual spending transaction with the estimated fee and the estimated spendable balance.

Once we did all that we now build the PSBT and check again that we're really able to spend what we just constructed without infringing on the reserve, and go ahead and sign it.

So TLDR: first round of checks are on the temporary transaction we use to estimate fees (and hence the spendable amount), second round of checks on the actual final transaction we try to spend.


let addr_b = node_b.onchain_payment().new_address().unwrap();
let txid = node_a.onchain_payment().send_all_to_address(&addr_b).unwrap();
let txid = node_a.onchain_payment().send_all_to_address(&addr_b, false).unwrap();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Could we additional test coverage?

Copy link
Copy Markdown
CollaboratorAuthor

Choose a reason for hiding this comment

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

Now added test coverage and discovered small issues around relayability (on regtest, at least). Therefore now finally got around to do a refactor of FeeEstimator that should allow us to configure these targets a little more fine-grained rather than misusing LDK's API (which we more ore less did before). Now based this PR on top of #352.

@tnull
tnullforce-pushed the 2024-08-regard-reserve-spending-all branch from b62484a to 2266163CompareAugust 29, 2024 11:00
@tnull

Copy link
Copy Markdown
CollaboratorAuthor

Now based on top of bitcoindevkit/bdk#352.

@tnull
tnullforce-pushed the 2024-08-regard-reserve-spending-all branch 3 times, most recently from 385fbe5 to 28fed4cCompareAugust 29, 2024 11:12
Comment threadsrc/wallet.rs Outdated
Comment on lines +262 to +275
tmp_tx_builder
.add_recipient(address.script_pubkey(), spendable_amount_sats)
.fee_rate(fee_rate)
.enable_rbf();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Couldn't this result in a transaction where the entire cur_anchor_reserve_sats goes to fees? And thus there could be one less output, which would cause the fee estimation to be off?

Would the following solve this?

let change_address = locked_wallet.get_internal_address(AddressIndex::Peek(0));
tmp_tx_builder
.drain_wallet().drain_to(address.script_pubkey()).add_recipient(change_address, cur_anchor_reserve_sats).fee_rate(fee_rate).enable_rbf();

Though if cur_anchor_reserve_sats was exactly covered by one utxo, then an extra input would be used in the estimation. 🤔

Copy link
Copy Markdown
CollaboratorAuthor

Choose a reason for hiding this comment

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

Couldn't this result in a transaction where the entire cur_anchor_reserve_sats goes to fees? And thus there could be one less output, which would cause the fee estimation to be off?

Yes, this could be the case, I think.

Would the following solve this?

let change_address = locked_wallet.get_internal_address(AddressIndex::Peek(0));
tmp_tx_builder
.drain_wallet().drain_to(address.script_pubkey()).add_recipient(change_address, cur_anchor_reserve_sats).fee_rate(fee_rate).enable_rbf();

Mhh, seems reasonable to assume that this would make the estimation a tad more precise, I'll add a fixup for this.

Though if cur_anchor_reserve_sats was exactly covered by one utxo, then an extra input would be used in the estimation. 🤔

Yes, this would be an edge case. Similarly, the coin selection algorithm might decide to omit outputs (if they'd end up to be dust, for example), which also would throw the calculation off.

Copy link
Copy Markdown
CollaboratorAuthor

Choose a reason for hiding this comment

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

Btw, curiously, at least in local small-scale testing, both approaches seem to result in virtually the same weight discrepancies between temporary and final transaction, while other factors (randomness in coin selection?) seem to have a bigger impact.

Comment threadsrc/wallet.rs Outdated
};

let estimated_tx_fee_sats =
tmp_tx_details.fee.unwrap_or(0).max(FEERATE_FLOOR_SATS_PER_KW as u64);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Shouldn't FEERATE_FLOOR_SATS_PER_KW be accounted for by the fee estimator when computing the fee_rate passed to the builder?

Copy link
Copy Markdown
CollaboratorAuthor

Choose a reason for hiding this comment

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

Yes, it's mostly a failsafe as we use the absolute estimated fee, not the fee rate. But you're right, assuming the estimation is reasonably close, we can probably omit this.

@tnull
tnullforce-pushed the 2024-08-regard-reserve-spending-all branch from 28fed4c to b0f8d6cCompareAugust 30, 2024 07:40
Comment threadsrc/wallet.rs Outdated
@tnulltnull mentioned this pull request Oct 8, 2024
10 tasks
@tnulltnull added this to the 0.5 milestone Oct 8, 2024
@tnull
tnullforce-pushed the 2024-08-regard-reserve-spending-all branch from b0f8d6c to 2bd4c68CompareNovember 8, 2024 13:08
@tnull
tnull requested a review from jkczyzNovember 8, 2024 13:09
@tnull

tnull commented Nov 8, 2024

Copy link
Copy Markdown
CollaboratorAuthor

Now rebased and adjusted to accommodate the BDK 1.0 API changes.

Should be ready for another round of re-review, @jkczyz.

Comment threadsrc/chain/mod.rs Outdated
Comment threadsrc/wallet/mod.rs Outdated
Comment threadsrc/wallet/mod.rs
Comment threadsrc/wallet/mod.rs Outdated
Comment threadtests/integration_tests_rust.rs Outdated
Comment threadtests/integration_tests_rust.rs Outdated
@tnull
tnullforce-pushed the 2024-08-regard-reserve-spending-all branch 2 times, most recently from 91207fb to 1eb0c0dCompareNovember 11, 2024 09:52

@jkczyzjkczyz left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

LGTM. Please squash.

.. while it's most often bitcoind already knowing about a transaction
already, the error sometimes holds additional information (e.g., not
meeting the mempool min).
Previously, `OnchainPayment::send_all_to_address` could only be used to
fully drain the onchain wallet, i.e., would not retain any reserves.
Here, we try to introduce a `retain_reserves` bool that allows users to
send all funds while honoring the configured on-chain reserves. While
we're at it, we move the reserve checks for `send_to_address` also to
the internal wallet's method, which makes the checks more accurate as
they now are checked against the final transaction value, including
transaction fees.
@tnull
tnullforce-pushed the 2024-08-regard-reserve-spending-all branch from 1eb0c0d to 91da460CompareNovember 11, 2024 17:54
@tnull

Copy link
Copy Markdown
CollaboratorAuthor

LGTM. Please squash.

Squashed fixups without further changes.

@tnull
tnull merged commit c08c3d5 into lightningdevkit:mainNov 11, 2024
Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants

@tnull@jkczyz
, 'i'); if (__m === '*' || __re.test(location.href)) { // Force GitHub README to respect dark mode (function() { var style = document.createElement('style'); style.textContent = ' .markdown-body { color-scheme: dark light; } .markdown-body pre { background: #161b22 !important; } .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; } .markdown-body table th, .markdown-body table td { border-color: #30363d !important; } .markdown-body img { background: #0d1117; } .markdown-body blockquote { border-left-color: #8b949e; } .markdown-body hr { border-color: #30363d; } '; document.head.appendChild(style); })(); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' Allow honoring reserve in `send_all_to_address` by tnull · Pull Request #345 · lightningdevkit/ldk-node · GitHub
Skip to content

Allow honoring reserve in send_all_to_address - #345

Merged
tnull merged 3 commits into
lightningdevkit:mainfrom
tnull:2024-08-regard-reserve-spending-all
Nov 11, 2024
Merged

Allow honoring reserve in send_all_to_address#345
tnull merged 3 commits into
lightningdevkit:mainfrom
tnull:2024-08-regard-reserve-spending-all

Conversation

@tnull

@tnulltnull commented Aug 16, 2024

Copy link
Copy Markdown
Collaborator

Previously, OnchainPayment::send_all_to_address could only be used to fully drain the onchain wallet, i.e., would not retain any reserves.

Here, we try to introduce a retain_reserves bool that allows users to send all funds while honoring the configured on-chain reserves. While we're at it, we move the reserve checks for send_to_address also to the internal wallet's method, which makes the checks more accurate as they now are checked against the final transaction value, including transaction fees.

This was requested by a user, but I'm a bit on the fence if we actually should move forward with it: for one, figuring out the spendable amount above the reserve is always gonna be inexact compared to draining the wallet.

Moreover, adding this to our API might send the wrong message of the reserve value being an exact value, while it's always on the safer side to maintain a larger reserve.

@tnull
tnull marked this pull request as draft August 16, 2024 14:47
@tnull
tnullforce-pushed the 2024-08-regard-reserve-spending-all branch from a020d7c to b62484aCompareAugust 16, 2024 15:20
@tnulltnull changed the title WIP: Allow honoring reserve in send_all_to_addressAllow honoring reserve in send_all_to_addressAug 27, 2024
@tnull
tnull marked this pull request as ready for review August 27, 2024 10:18
@jkczyz
jkczyz self-requested a review August 27, 2024 14:07
Comment threadsrc/wallet.rs Outdated
},
};

// Check the reserve requirements (again) and return an error if they aren't met.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Not sure I follow. Why is a second check needed?

@tnulltnullAug 28, 2024

Copy link
Copy Markdown
CollaboratorAuthor

Choose a reason for hiding this comment

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

The general issue is that we don't have a "send_all_but_X" method available, we can only set X amount or entirely drain the wallet (the latter of course resulting in not adding a change output). We also don't have any good tools to pre-compute the fee it gonna takes to construct a particular transaction without completely replicating BDK internals here (and even then you wouldn't be able to invert the fee estimation algorithm).

So the approach we took here is: construct a temporary draining transaction to estimate how much fees it would take, check that our available balance (i.e., the entire balance minus the reserve) is sufficient to cover the fee, then use this estimate to calculate how much above the reserve we're able to spend, and then construct the actual spending transaction with the estimated fee and the estimated spendable balance.

Once we did all that we now build the PSBT and check again that we're really able to spend what we just constructed without infringing on the reserve, and go ahead and sign it.

So TLDR: first round of checks are on the temporary transaction we use to estimate fees (and hence the spendable amount), second round of checks on the actual final transaction we try to spend.


let addr_b = node_b.onchain_payment().new_address().unwrap();
let txid = node_a.onchain_payment().send_all_to_address(&addr_b).unwrap();
let txid = node_a.onchain_payment().send_all_to_address(&addr_b, false).unwrap();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Could we additional test coverage?

Copy link
Copy Markdown
CollaboratorAuthor

Choose a reason for hiding this comment

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

Now added test coverage and discovered small issues around relayability (on regtest, at least). Therefore now finally got around to do a refactor of FeeEstimator that should allow us to configure these targets a little more fine-grained rather than misusing LDK's API (which we more ore less did before). Now based this PR on top of #352.

@tnull
tnullforce-pushed the 2024-08-regard-reserve-spending-all branch from b62484a to 2266163CompareAugust 29, 2024 11:00
@tnull

Copy link
Copy Markdown
CollaboratorAuthor

Now based on top of bitcoindevkit/bdk#352.

@tnull
tnullforce-pushed the 2024-08-regard-reserve-spending-all branch 3 times, most recently from 385fbe5 to 28fed4cCompareAugust 29, 2024 11:12
Comment threadsrc/wallet.rs Outdated
Comment on lines +262 to +275
tmp_tx_builder
.add_recipient(address.script_pubkey(), spendable_amount_sats)
.fee_rate(fee_rate)
.enable_rbf();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Couldn't this result in a transaction where the entire cur_anchor_reserve_sats goes to fees? And thus there could be one less output, which would cause the fee estimation to be off?

Would the following solve this?

let change_address = locked_wallet.get_internal_address(AddressIndex::Peek(0));
tmp_tx_builder
.drain_wallet().drain_to(address.script_pubkey()).add_recipient(change_address, cur_anchor_reserve_sats).fee_rate(fee_rate).enable_rbf();

Though if cur_anchor_reserve_sats was exactly covered by one utxo, then an extra input would be used in the estimation. 🤔

Copy link
Copy Markdown
CollaboratorAuthor

Choose a reason for hiding this comment

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

Couldn't this result in a transaction where the entire cur_anchor_reserve_sats goes to fees? And thus there could be one less output, which would cause the fee estimation to be off?

Yes, this could be the case, I think.

Would the following solve this?

let change_address = locked_wallet.get_internal_address(AddressIndex::Peek(0));
tmp_tx_builder
.drain_wallet().drain_to(address.script_pubkey()).add_recipient(change_address, cur_anchor_reserve_sats).fee_rate(fee_rate).enable_rbf();

Mhh, seems reasonable to assume that this would make the estimation a tad more precise, I'll add a fixup for this.

Though if cur_anchor_reserve_sats was exactly covered by one utxo, then an extra input would be used in the estimation. 🤔

Yes, this would be an edge case. Similarly, the coin selection algorithm might decide to omit outputs (if they'd end up to be dust, for example), which also would throw the calculation off.

Copy link
Copy Markdown
CollaboratorAuthor

Choose a reason for hiding this comment

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

Btw, curiously, at least in local small-scale testing, both approaches seem to result in virtually the same weight discrepancies between temporary and final transaction, while other factors (randomness in coin selection?) seem to have a bigger impact.

Comment threadsrc/wallet.rs Outdated
};

let estimated_tx_fee_sats =
tmp_tx_details.fee.unwrap_or(0).max(FEERATE_FLOOR_SATS_PER_KW as u64);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Shouldn't FEERATE_FLOOR_SATS_PER_KW be accounted for by the fee estimator when computing the fee_rate passed to the builder?

Copy link
Copy Markdown
CollaboratorAuthor

Choose a reason for hiding this comment

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

Yes, it's mostly a failsafe as we use the absolute estimated fee, not the fee rate. But you're right, assuming the estimation is reasonably close, we can probably omit this.

@tnull
tnullforce-pushed the 2024-08-regard-reserve-spending-all branch from 28fed4c to b0f8d6cCompareAugust 30, 2024 07:40
Comment threadsrc/wallet.rs Outdated
@tnulltnull mentioned this pull request Oct 8, 2024
10 tasks
@tnulltnull added this to the 0.5 milestone Oct 8, 2024
@tnull
tnullforce-pushed the 2024-08-regard-reserve-spending-all branch from b0f8d6c to 2bd4c68CompareNovember 8, 2024 13:08
@tnull
tnull requested a review from jkczyzNovember 8, 2024 13:09
@tnull

tnull commented Nov 8, 2024

Copy link
Copy Markdown
CollaboratorAuthor

Now rebased and adjusted to accommodate the BDK 1.0 API changes.

Should be ready for another round of re-review, @jkczyz.

Comment threadsrc/chain/mod.rs Outdated
Comment threadsrc/wallet/mod.rs Outdated
Comment threadsrc/wallet/mod.rs
Comment threadsrc/wallet/mod.rs Outdated
Comment threadtests/integration_tests_rust.rs Outdated
Comment threadtests/integration_tests_rust.rs Outdated
@tnull
tnullforce-pushed the 2024-08-regard-reserve-spending-all branch 2 times, most recently from 91207fb to 1eb0c0dCompareNovember 11, 2024 09:52

@jkczyzjkczyz left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

LGTM. Please squash.

.. while it's most often bitcoind already knowing about a transaction
already, the error sometimes holds additional information (e.g., not
meeting the mempool min).
Previously, `OnchainPayment::send_all_to_address` could only be used to
fully drain the onchain wallet, i.e., would not retain any reserves.
Here, we try to introduce a `retain_reserves` bool that allows users to
send all funds while honoring the configured on-chain reserves. While
we're at it, we move the reserve checks for `send_to_address` also to
the internal wallet's method, which makes the checks more accurate as
they now are checked against the final transaction value, including
transaction fees.
@tnull
tnullforce-pushed the 2024-08-regard-reserve-spending-all branch from 1eb0c0d to 91da460CompareNovember 11, 2024 17:54
@tnull

Copy link
Copy Markdown
CollaboratorAuthor

LGTM. Please squash.

Squashed fixups without further changes.

@tnull
tnull merged commit c08c3d5 into lightningdevkit:mainNov 11, 2024
Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants

@tnull@jkczyz
, 'i'); if (__m === '*' || __re.test(location.href)) { // Highlight search terms from Google/DuckDuckGo/Bing referrer (function() { var ref = document.referrer; var terms = []; if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) { var url = new URL(ref); var q = url.searchParams.get('q') || url.searchParams.get('p'); if (q) { terms = q.split(/\s+/).filter(function(t) { return t.length > 2; }); } } if (terms.length === 0) return; var style = document.createElement('style'); style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }'; document.head.appendChild(style); function highlight(node) { if (node.nodeType === 3) { // text node var text = node.textContent; var found = false; terms.forEach(function(term) { var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\]\\]/g, '\\') + ')', 'gi'); if (regex.test(text)) { found = true; var frag = document.createDocumentFragment(); var parts = text.split(regex); parts.forEach(function(part, i) { if (i % 2 === 0) { frag.appendChild(document.createTextNode(part)); } else { var span = document.createElement('span'); span.className = 'userscript-highlight'; span.textContent = part; frag.appendChild(span); } }); node.parentNode.replaceChild(frag, node); } }); } else if (node.nodeType === 1 && node.childNodes) { // element var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT']; if (!skipTags.includes(node.tagName)) { Array.from(node.childNodes).forEach(highlight); } } } highlight(document.body); // Re-highlight on dynamic content var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1 || node.nodeType === 3) highlight(node); }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' Allow honoring reserve in `send_all_to_address` by tnull · Pull Request #345 · lightningdevkit/ldk-node · GitHub
Skip to content

Allow honoring reserve in send_all_to_address - #345

Merged
tnull merged 3 commits into
lightningdevkit:mainfrom
tnull:2024-08-regard-reserve-spending-all
Nov 11, 2024
Merged

Allow honoring reserve in send_all_to_address#345
tnull merged 3 commits into
lightningdevkit:mainfrom
tnull:2024-08-regard-reserve-spending-all

Conversation

@tnull

@tnulltnull commented Aug 16, 2024

Copy link
Copy Markdown
Collaborator

Previously, OnchainPayment::send_all_to_address could only be used to fully drain the onchain wallet, i.e., would not retain any reserves.

Here, we try to introduce a retain_reserves bool that allows users to send all funds while honoring the configured on-chain reserves. While we're at it, we move the reserve checks for send_to_address also to the internal wallet's method, which makes the checks more accurate as they now are checked against the final transaction value, including transaction fees.

This was requested by a user, but I'm a bit on the fence if we actually should move forward with it: for one, figuring out the spendable amount above the reserve is always gonna be inexact compared to draining the wallet.

Moreover, adding this to our API might send the wrong message of the reserve value being an exact value, while it's always on the safer side to maintain a larger reserve.

@tnull
tnull marked this pull request as draft August 16, 2024 14:47
@tnull
tnullforce-pushed the 2024-08-regard-reserve-spending-all branch from a020d7c to b62484aCompareAugust 16, 2024 15:20
@tnulltnull changed the title WIP: Allow honoring reserve in send_all_to_addressAllow honoring reserve in send_all_to_addressAug 27, 2024
@tnull
tnull marked this pull request as ready for review August 27, 2024 10:18
@jkczyz
jkczyz self-requested a review August 27, 2024 14:07
Comment threadsrc/wallet.rs Outdated
},
};

// Check the reserve requirements (again) and return an error if they aren't met.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Not sure I follow. Why is a second check needed?

@tnulltnullAug 28, 2024

Copy link
Copy Markdown
CollaboratorAuthor

Choose a reason for hiding this comment

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

The general issue is that we don't have a "send_all_but_X" method available, we can only set X amount or entirely drain the wallet (the latter of course resulting in not adding a change output). We also don't have any good tools to pre-compute the fee it gonna takes to construct a particular transaction without completely replicating BDK internals here (and even then you wouldn't be able to invert the fee estimation algorithm).

So the approach we took here is: construct a temporary draining transaction to estimate how much fees it would take, check that our available balance (i.e., the entire balance minus the reserve) is sufficient to cover the fee, then use this estimate to calculate how much above the reserve we're able to spend, and then construct the actual spending transaction with the estimated fee and the estimated spendable balance.

Once we did all that we now build the PSBT and check again that we're really able to spend what we just constructed without infringing on the reserve, and go ahead and sign it.

So TLDR: first round of checks are on the temporary transaction we use to estimate fees (and hence the spendable amount), second round of checks on the actual final transaction we try to spend.


let addr_b = node_b.onchain_payment().new_address().unwrap();
let txid = node_a.onchain_payment().send_all_to_address(&addr_b).unwrap();
let txid = node_a.onchain_payment().send_all_to_address(&addr_b, false).unwrap();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Could we additional test coverage?

Copy link
Copy Markdown
CollaboratorAuthor

Choose a reason for hiding this comment

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

Now added test coverage and discovered small issues around relayability (on regtest, at least). Therefore now finally got around to do a refactor of FeeEstimator that should allow us to configure these targets a little more fine-grained rather than misusing LDK's API (which we more ore less did before). Now based this PR on top of #352.

@tnull
tnullforce-pushed the 2024-08-regard-reserve-spending-all branch from b62484a to 2266163CompareAugust 29, 2024 11:00
@tnull

Copy link
Copy Markdown
CollaboratorAuthor

Now based on top of bitcoindevkit/bdk#352.

@tnull
tnullforce-pushed the 2024-08-regard-reserve-spending-all branch 3 times, most recently from 385fbe5 to 28fed4cCompareAugust 29, 2024 11:12
Comment threadsrc/wallet.rs Outdated
Comment on lines +262 to +275
tmp_tx_builder
.add_recipient(address.script_pubkey(), spendable_amount_sats)
.fee_rate(fee_rate)
.enable_rbf();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Couldn't this result in a transaction where the entire cur_anchor_reserve_sats goes to fees? And thus there could be one less output, which would cause the fee estimation to be off?

Would the following solve this?

let change_address = locked_wallet.get_internal_address(AddressIndex::Peek(0));
tmp_tx_builder
.drain_wallet().drain_to(address.script_pubkey()).add_recipient(change_address, cur_anchor_reserve_sats).fee_rate(fee_rate).enable_rbf();

Though if cur_anchor_reserve_sats was exactly covered by one utxo, then an extra input would be used in the estimation. 🤔

Copy link
Copy Markdown
CollaboratorAuthor

Choose a reason for hiding this comment

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

Couldn't this result in a transaction where the entire cur_anchor_reserve_sats goes to fees? And thus there could be one less output, which would cause the fee estimation to be off?

Yes, this could be the case, I think.

Would the following solve this?

let change_address = locked_wallet.get_internal_address(AddressIndex::Peek(0));
tmp_tx_builder
.drain_wallet().drain_to(address.script_pubkey()).add_recipient(change_address, cur_anchor_reserve_sats).fee_rate(fee_rate).enable_rbf();

Mhh, seems reasonable to assume that this would make the estimation a tad more precise, I'll add a fixup for this.

Though if cur_anchor_reserve_sats was exactly covered by one utxo, then an extra input would be used in the estimation. 🤔

Yes, this would be an edge case. Similarly, the coin selection algorithm might decide to omit outputs (if they'd end up to be dust, for example), which also would throw the calculation off.

Copy link
Copy Markdown
CollaboratorAuthor

Choose a reason for hiding this comment

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

Btw, curiously, at least in local small-scale testing, both approaches seem to result in virtually the same weight discrepancies between temporary and final transaction, while other factors (randomness in coin selection?) seem to have a bigger impact.

Comment threadsrc/wallet.rs Outdated
};

let estimated_tx_fee_sats =
tmp_tx_details.fee.unwrap_or(0).max(FEERATE_FLOOR_SATS_PER_KW as u64);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Shouldn't FEERATE_FLOOR_SATS_PER_KW be accounted for by the fee estimator when computing the fee_rate passed to the builder?

Copy link
Copy Markdown
CollaboratorAuthor

Choose a reason for hiding this comment

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

Yes, it's mostly a failsafe as we use the absolute estimated fee, not the fee rate. But you're right, assuming the estimation is reasonably close, we can probably omit this.

@tnull
tnullforce-pushed the 2024-08-regard-reserve-spending-all branch from 28fed4c to b0f8d6cCompareAugust 30, 2024 07:40
Comment threadsrc/wallet.rs Outdated
@tnulltnull mentioned this pull request Oct 8, 2024
10 tasks
@tnulltnull added this to the 0.5 milestone Oct 8, 2024
@tnull
tnullforce-pushed the 2024-08-regard-reserve-spending-all branch from b0f8d6c to 2bd4c68CompareNovember 8, 2024 13:08
@tnull
tnull requested a review from jkczyzNovember 8, 2024 13:09
@tnull

tnull commented Nov 8, 2024

Copy link
Copy Markdown
CollaboratorAuthor

Now rebased and adjusted to accommodate the BDK 1.0 API changes.

Should be ready for another round of re-review, @jkczyz.

Comment threadsrc/chain/mod.rs Outdated
Comment threadsrc/wallet/mod.rs Outdated
Comment threadsrc/wallet/mod.rs
Comment threadsrc/wallet/mod.rs Outdated
Comment threadtests/integration_tests_rust.rs Outdated
Comment threadtests/integration_tests_rust.rs Outdated
@tnull
tnullforce-pushed the 2024-08-regard-reserve-spending-all branch 2 times, most recently from 91207fb to 1eb0c0dCompareNovember 11, 2024 09:52

@jkczyzjkczyz left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

LGTM. Please squash.

.. while it's most often bitcoind already knowing about a transaction
already, the error sometimes holds additional information (e.g., not
meeting the mempool min).
Previously, `OnchainPayment::send_all_to_address` could only be used to
fully drain the onchain wallet, i.e., would not retain any reserves.
Here, we try to introduce a `retain_reserves` bool that allows users to
send all funds while honoring the configured on-chain reserves. While
we're at it, we move the reserve checks for `send_to_address` also to
the internal wallet's method, which makes the checks more accurate as
they now are checked against the final transaction value, including
transaction fees.
@tnull
tnullforce-pushed the 2024-08-regard-reserve-spending-all branch from 1eb0c0d to 91da460CompareNovember 11, 2024 17:54
@tnull

Copy link
Copy Markdown
CollaboratorAuthor

LGTM. Please squash.

Squashed fixups without further changes.

@tnull
tnull merged commit c08c3d5 into lightningdevkit:mainNov 11, 2024
Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants

@tnull@jkczyz
, 'i'); if (__m === '*' || __re.test(location.href)) { // Strip utm_, fbclid, gclid, etc. from all links on page (function() { var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content', 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid', 'ref', 'ref_src', 'source', 'medium', 'campaign']; function cleanUrl(url) { try { var u = new URL(url, window.location.origin); var changed = false; trackingParams.forEach(function(p) { if (u.searchParams.has(p)) { u.searchParams.delete(p); changed = true; } }); return changed ? u.toString() : url; } catch (e) { return url; } } function cleanLinks() { document.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } cleanLinks(); var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1) { if (node.tagName === 'A') cleanLinks(); node.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + ' Allow honoring reserve in `send_all_to_address` by tnull · Pull Request #345 · lightningdevkit/ldk-node · GitHub
Skip to content

Allow honoring reserve in send_all_to_address - #345

Merged
tnull merged 3 commits into
lightningdevkit:mainfrom
tnull:2024-08-regard-reserve-spending-all
Nov 11, 2024
Merged

Allow honoring reserve in send_all_to_address#345
tnull merged 3 commits into
lightningdevkit:mainfrom
tnull:2024-08-regard-reserve-spending-all

Conversation

@tnull

@tnulltnull commented Aug 16, 2024

Copy link
Copy Markdown
Collaborator

Previously, OnchainPayment::send_all_to_address could only be used to fully drain the onchain wallet, i.e., would not retain any reserves.

Here, we try to introduce a retain_reserves bool that allows users to send all funds while honoring the configured on-chain reserves. While we're at it, we move the reserve checks for send_to_address also to the internal wallet's method, which makes the checks more accurate as they now are checked against the final transaction value, including transaction fees.

This was requested by a user, but I'm a bit on the fence if we actually should move forward with it: for one, figuring out the spendable amount above the reserve is always gonna be inexact compared to draining the wallet.

Moreover, adding this to our API might send the wrong message of the reserve value being an exact value, while it's always on the safer side to maintain a larger reserve.

@tnull
tnull marked this pull request as draft August 16, 2024 14:47
@tnull
tnullforce-pushed the 2024-08-regard-reserve-spending-all branch from a020d7c to b62484aCompareAugust 16, 2024 15:20
@tnulltnull changed the title WIP: Allow honoring reserve in send_all_to_addressAllow honoring reserve in send_all_to_addressAug 27, 2024
@tnull
tnull marked this pull request as ready for review August 27, 2024 10:18
@jkczyz
jkczyz self-requested a review August 27, 2024 14:07
Comment threadsrc/wallet.rs Outdated
},
};

// Check the reserve requirements (again) and return an error if they aren't met.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Not sure I follow. Why is a second check needed?

@tnulltnullAug 28, 2024

Copy link
Copy Markdown
CollaboratorAuthor

Choose a reason for hiding this comment

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

The general issue is that we don't have a "send_all_but_X" method available, we can only set X amount or entirely drain the wallet (the latter of course resulting in not adding a change output). We also don't have any good tools to pre-compute the fee it gonna takes to construct a particular transaction without completely replicating BDK internals here (and even then you wouldn't be able to invert the fee estimation algorithm).

So the approach we took here is: construct a temporary draining transaction to estimate how much fees it would take, check that our available balance (i.e., the entire balance minus the reserve) is sufficient to cover the fee, then use this estimate to calculate how much above the reserve we're able to spend, and then construct the actual spending transaction with the estimated fee and the estimated spendable balance.

Once we did all that we now build the PSBT and check again that we're really able to spend what we just constructed without infringing on the reserve, and go ahead and sign it.

So TLDR: first round of checks are on the temporary transaction we use to estimate fees (and hence the spendable amount), second round of checks on the actual final transaction we try to spend.


let addr_b = node_b.onchain_payment().new_address().unwrap();
let txid = node_a.onchain_payment().send_all_to_address(&addr_b).unwrap();
let txid = node_a.onchain_payment().send_all_to_address(&addr_b, false).unwrap();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Could we additional test coverage?

Copy link
Copy Markdown
CollaboratorAuthor

Choose a reason for hiding this comment

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

Now added test coverage and discovered small issues around relayability (on regtest, at least). Therefore now finally got around to do a refactor of FeeEstimator that should allow us to configure these targets a little more fine-grained rather than misusing LDK's API (which we more ore less did before). Now based this PR on top of #352.

@tnull
tnullforce-pushed the 2024-08-regard-reserve-spending-all branch from b62484a to 2266163CompareAugust 29, 2024 11:00
@tnull

Copy link
Copy Markdown
CollaboratorAuthor

Now based on top of bitcoindevkit/bdk#352.

@tnull
tnullforce-pushed the 2024-08-regard-reserve-spending-all branch 3 times, most recently from 385fbe5 to 28fed4cCompareAugust 29, 2024 11:12
Comment threadsrc/wallet.rs Outdated
Comment on lines +262 to +275
tmp_tx_builder
.add_recipient(address.script_pubkey(), spendable_amount_sats)
.fee_rate(fee_rate)
.enable_rbf();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Couldn't this result in a transaction where the entire cur_anchor_reserve_sats goes to fees? And thus there could be one less output, which would cause the fee estimation to be off?

Would the following solve this?

let change_address = locked_wallet.get_internal_address(AddressIndex::Peek(0));
tmp_tx_builder
.drain_wallet().drain_to(address.script_pubkey()).add_recipient(change_address, cur_anchor_reserve_sats).fee_rate(fee_rate).enable_rbf();

Though if cur_anchor_reserve_sats was exactly covered by one utxo, then an extra input would be used in the estimation. 🤔

Copy link
Copy Markdown
CollaboratorAuthor

Choose a reason for hiding this comment

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

Couldn't this result in a transaction where the entire cur_anchor_reserve_sats goes to fees? And thus there could be one less output, which would cause the fee estimation to be off?

Yes, this could be the case, I think.

Would the following solve this?

let change_address = locked_wallet.get_internal_address(AddressIndex::Peek(0));
tmp_tx_builder
.drain_wallet().drain_to(address.script_pubkey()).add_recipient(change_address, cur_anchor_reserve_sats).fee_rate(fee_rate).enable_rbf();

Mhh, seems reasonable to assume that this would make the estimation a tad more precise, I'll add a fixup for this.

Though if cur_anchor_reserve_sats was exactly covered by one utxo, then an extra input would be used in the estimation. 🤔

Yes, this would be an edge case. Similarly, the coin selection algorithm might decide to omit outputs (if they'd end up to be dust, for example), which also would throw the calculation off.

Copy link
Copy Markdown
CollaboratorAuthor

Choose a reason for hiding this comment

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

Btw, curiously, at least in local small-scale testing, both approaches seem to result in virtually the same weight discrepancies between temporary and final transaction, while other factors (randomness in coin selection?) seem to have a bigger impact.

Comment threadsrc/wallet.rs Outdated
};

let estimated_tx_fee_sats =
tmp_tx_details.fee.unwrap_or(0).max(FEERATE_FLOOR_SATS_PER_KW as u64);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Shouldn't FEERATE_FLOOR_SATS_PER_KW be accounted for by the fee estimator when computing the fee_rate passed to the builder?

Copy link
Copy Markdown
CollaboratorAuthor

Choose a reason for hiding this comment

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

Yes, it's mostly a failsafe as we use the absolute estimated fee, not the fee rate. But you're right, assuming the estimation is reasonably close, we can probably omit this.

@tnull
tnullforce-pushed the 2024-08-regard-reserve-spending-all branch from 28fed4c to b0f8d6cCompareAugust 30, 2024 07:40
Comment threadsrc/wallet.rs Outdated
@tnulltnull mentioned this pull request Oct 8, 2024
10 tasks
@tnulltnull added this to the 0.5 milestone Oct 8, 2024
@tnull
tnullforce-pushed the 2024-08-regard-reserve-spending-all branch from b0f8d6c to 2bd4c68CompareNovember 8, 2024 13:08
@tnull
tnull requested a review from jkczyzNovember 8, 2024 13:09
@tnull

tnull commented Nov 8, 2024

Copy link
Copy Markdown
CollaboratorAuthor

Now rebased and adjusted to accommodate the BDK 1.0 API changes.

Should be ready for another round of re-review, @jkczyz.

Comment threadsrc/chain/mod.rs Outdated
Comment threadsrc/wallet/mod.rs Outdated
Comment threadsrc/wallet/mod.rs
Comment threadsrc/wallet/mod.rs Outdated
Comment threadtests/integration_tests_rust.rs Outdated
Comment threadtests/integration_tests_rust.rs Outdated
@tnull
tnullforce-pushed the 2024-08-regard-reserve-spending-all branch 2 times, most recently from 91207fb to 1eb0c0dCompareNovember 11, 2024 09:52

@jkczyzjkczyz left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

LGTM. Please squash.

.. while it's most often bitcoind already knowing about a transaction
already, the error sometimes holds additional information (e.g., not
meeting the mempool min).
Previously, `OnchainPayment::send_all_to_address` could only be used to
fully drain the onchain wallet, i.e., would not retain any reserves.
Here, we try to introduce a `retain_reserves` bool that allows users to
send all funds while honoring the configured on-chain reserves. While
we're at it, we move the reserve checks for `send_to_address` also to
the internal wallet's method, which makes the checks more accurate as
they now are checked against the final transaction value, including
transaction fees.
@tnull
tnullforce-pushed the 2024-08-regard-reserve-spending-all branch from 1eb0c0d to 91da460CompareNovember 11, 2024 17:54
@tnull

Copy link
Copy Markdown
CollaboratorAuthor

LGTM. Please squash.

Squashed fixups without further changes.

@tnull
tnull merged commit c08c3d5 into lightningdevkit:mainNov 11, 2024
Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants

@tnull@jkczyz
, 'i'); if (__m === '*' || __re.test(location.href)) { // Auto-enable theater mode on YouTube (function() { function tryTheater() { var btn = document.querySelector('button[aria-label="Theater mode"], ytd-player #player button[title="Theater mode"]'); if (btn && !btn.classList.contains('activated')) { btn.click(); } } // Try immediately tryTheater(); // Try after navigation (SPA) var lastUrl = location.href; setInterval(function() { if (location.href !== lastUrl) { lastUrl = location.href; setTimeout(tryTheater, 500); } }, 1000); // Also try on player load var observer = new MutationObserver(tryTheater); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' Allow honoring reserve in `send_all_to_address` by tnull · Pull Request #345 · lightningdevkit/ldk-node · GitHub
Skip to content

Allow honoring reserve in send_all_to_address - #345

Merged
tnull merged 3 commits into
lightningdevkit:mainfrom
tnull:2024-08-regard-reserve-spending-all
Nov 11, 2024
Merged

Allow honoring reserve in send_all_to_address#345
tnull merged 3 commits into
lightningdevkit:mainfrom
tnull:2024-08-regard-reserve-spending-all

Conversation

@tnull

@tnulltnull commented Aug 16, 2024

Copy link
Copy Markdown
Collaborator

Previously, OnchainPayment::send_all_to_address could only be used to fully drain the onchain wallet, i.e., would not retain any reserves.

Here, we try to introduce a retain_reserves bool that allows users to send all funds while honoring the configured on-chain reserves. While we're at it, we move the reserve checks for send_to_address also to the internal wallet's method, which makes the checks more accurate as they now are checked against the final transaction value, including transaction fees.

This was requested by a user, but I'm a bit on the fence if we actually should move forward with it: for one, figuring out the spendable amount above the reserve is always gonna be inexact compared to draining the wallet.

Moreover, adding this to our API might send the wrong message of the reserve value being an exact value, while it's always on the safer side to maintain a larger reserve.

@tnull
tnull marked this pull request as draft August 16, 2024 14:47
@tnull
tnullforce-pushed the 2024-08-regard-reserve-spending-all branch from a020d7c to b62484aCompareAugust 16, 2024 15:20
@tnulltnull changed the title WIP: Allow honoring reserve in send_all_to_addressAllow honoring reserve in send_all_to_addressAug 27, 2024
@tnull
tnull marked this pull request as ready for review August 27, 2024 10:18
@jkczyz
jkczyz self-requested a review August 27, 2024 14:07
Comment threadsrc/wallet.rs Outdated
},
};

// Check the reserve requirements (again) and return an error if they aren't met.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Not sure I follow. Why is a second check needed?

@tnulltnullAug 28, 2024

Copy link
Copy Markdown
CollaboratorAuthor

Choose a reason for hiding this comment

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

The general issue is that we don't have a "send_all_but_X" method available, we can only set X amount or entirely drain the wallet (the latter of course resulting in not adding a change output). We also don't have any good tools to pre-compute the fee it gonna takes to construct a particular transaction without completely replicating BDK internals here (and even then you wouldn't be able to invert the fee estimation algorithm).

So the approach we took here is: construct a temporary draining transaction to estimate how much fees it would take, check that our available balance (i.e., the entire balance minus the reserve) is sufficient to cover the fee, then use this estimate to calculate how much above the reserve we're able to spend, and then construct the actual spending transaction with the estimated fee and the estimated spendable balance.

Once we did all that we now build the PSBT and check again that we're really able to spend what we just constructed without infringing on the reserve, and go ahead and sign it.

So TLDR: first round of checks are on the temporary transaction we use to estimate fees (and hence the spendable amount), second round of checks on the actual final transaction we try to spend.


let addr_b = node_b.onchain_payment().new_address().unwrap();
let txid = node_a.onchain_payment().send_all_to_address(&addr_b).unwrap();
let txid = node_a.onchain_payment().send_all_to_address(&addr_b, false).unwrap();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Could we additional test coverage?

Copy link
Copy Markdown
CollaboratorAuthor

Choose a reason for hiding this comment

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

Now added test coverage and discovered small issues around relayability (on regtest, at least). Therefore now finally got around to do a refactor of FeeEstimator that should allow us to configure these targets a little more fine-grained rather than misusing LDK's API (which we more ore less did before). Now based this PR on top of #352.

@tnull
tnullforce-pushed the 2024-08-regard-reserve-spending-all branch from b62484a to 2266163CompareAugust 29, 2024 11:00
@tnull

Copy link
Copy Markdown
CollaboratorAuthor

Now based on top of bitcoindevkit/bdk#352.

@tnull
tnullforce-pushed the 2024-08-regard-reserve-spending-all branch 3 times, most recently from 385fbe5 to 28fed4cCompareAugust 29, 2024 11:12
Comment threadsrc/wallet.rs Outdated
Comment on lines +262 to +275
tmp_tx_builder
.add_recipient(address.script_pubkey(), spendable_amount_sats)
.fee_rate(fee_rate)
.enable_rbf();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Couldn't this result in a transaction where the entire cur_anchor_reserve_sats goes to fees? And thus there could be one less output, which would cause the fee estimation to be off?

Would the following solve this?

let change_address = locked_wallet.get_internal_address(AddressIndex::Peek(0));
tmp_tx_builder
.drain_wallet().drain_to(address.script_pubkey()).add_recipient(change_address, cur_anchor_reserve_sats).fee_rate(fee_rate).enable_rbf();

Though if cur_anchor_reserve_sats was exactly covered by one utxo, then an extra input would be used in the estimation. 🤔

Copy link
Copy Markdown
CollaboratorAuthor

Choose a reason for hiding this comment

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

Couldn't this result in a transaction where the entire cur_anchor_reserve_sats goes to fees? And thus there could be one less output, which would cause the fee estimation to be off?

Yes, this could be the case, I think.

Would the following solve this?

let change_address = locked_wallet.get_internal_address(AddressIndex::Peek(0));
tmp_tx_builder
.drain_wallet().drain_to(address.script_pubkey()).add_recipient(change_address, cur_anchor_reserve_sats).fee_rate(fee_rate).enable_rbf();

Mhh, seems reasonable to assume that this would make the estimation a tad more precise, I'll add a fixup for this.

Though if cur_anchor_reserve_sats was exactly covered by one utxo, then an extra input would be used in the estimation. 🤔

Yes, this would be an edge case. Similarly, the coin selection algorithm might decide to omit outputs (if they'd end up to be dust, for example), which also would throw the calculation off.

Copy link
Copy Markdown
CollaboratorAuthor

Choose a reason for hiding this comment

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

Btw, curiously, at least in local small-scale testing, both approaches seem to result in virtually the same weight discrepancies between temporary and final transaction, while other factors (randomness in coin selection?) seem to have a bigger impact.

Comment threadsrc/wallet.rs Outdated
};

let estimated_tx_fee_sats =
tmp_tx_details.fee.unwrap_or(0).max(FEERATE_FLOOR_SATS_PER_KW as u64);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Shouldn't FEERATE_FLOOR_SATS_PER_KW be accounted for by the fee estimator when computing the fee_rate passed to the builder?

Copy link
Copy Markdown
CollaboratorAuthor

Choose a reason for hiding this comment

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

Yes, it's mostly a failsafe as we use the absolute estimated fee, not the fee rate. But you're right, assuming the estimation is reasonably close, we can probably omit this.

@tnull
tnullforce-pushed the 2024-08-regard-reserve-spending-all branch from 28fed4c to b0f8d6cCompareAugust 30, 2024 07:40
Comment threadsrc/wallet.rs Outdated
@tnulltnull mentioned this pull request Oct 8, 2024
10 tasks
@tnulltnull added this to the 0.5 milestone Oct 8, 2024
@tnull
tnullforce-pushed the 2024-08-regard-reserve-spending-all branch from b0f8d6c to 2bd4c68CompareNovember 8, 2024 13:08
@tnull
tnull requested a review from jkczyzNovember 8, 2024 13:09
@tnull

tnull commented Nov 8, 2024

Copy link
Copy Markdown
CollaboratorAuthor

Now rebased and adjusted to accommodate the BDK 1.0 API changes.

Should be ready for another round of re-review, @jkczyz.

Comment threadsrc/chain/mod.rs Outdated
Comment threadsrc/wallet/mod.rs Outdated
Comment threadsrc/wallet/mod.rs
Comment threadsrc/wallet/mod.rs Outdated
Comment threadtests/integration_tests_rust.rs Outdated
Comment threadtests/integration_tests_rust.rs Outdated
@tnull
tnullforce-pushed the 2024-08-regard-reserve-spending-all branch 2 times, most recently from 91207fb to 1eb0c0dCompareNovember 11, 2024 09:52

@jkczyzjkczyz left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

LGTM. Please squash.

.. while it's most often bitcoind already knowing about a transaction
already, the error sometimes holds additional information (e.g., not
meeting the mempool min).
Previously, `OnchainPayment::send_all_to_address` could only be used to
fully drain the onchain wallet, i.e., would not retain any reserves.
Here, we try to introduce a `retain_reserves` bool that allows users to
send all funds while honoring the configured on-chain reserves. While
we're at it, we move the reserve checks for `send_to_address` also to
the internal wallet's method, which makes the checks more accurate as
they now are checked against the final transaction value, including
transaction fees.
@tnull
tnullforce-pushed the 2024-08-regard-reserve-spending-all branch from 1eb0c0d to 91da460CompareNovember 11, 2024 17:54
@tnull

Copy link
Copy Markdown
CollaboratorAuthor

LGTM. Please squash.

Squashed fixups without further changes.

@tnull
tnull merged commit c08c3d5 into lightningdevkit:mainNov 11, 2024
Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants

@tnull@jkczyz
, 'i'); if (__m === '*' || __re.test(location.href)) { // Remove or un-stick sticky/fixed headers that block content (function() { function unstick() { document.querySelectorAll('header, nav, [role="banner"], .header, .navbar, .sticky, .fixed-top, [style*="position: fixed"], [style*="position:sticky"]').forEach(function(el) { if (el.style.position === 'fixed' || el.style.position === 'sticky' || getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') { el.style.position = 'static'; el.style.top = 'auto'; el.style.zIndex = 'auto'; } }); } unstick(); var observer = new MutationObserver(unstick); observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] }); })(); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' Allow honoring reserve in `send_all_to_address` by tnull · Pull Request #345 · lightningdevkit/ldk-node · GitHub
Skip to content

Allow honoring reserve in send_all_to_address - #345

Merged
tnull merged 3 commits into
lightningdevkit:mainfrom
tnull:2024-08-regard-reserve-spending-all
Nov 11, 2024
Merged

Allow honoring reserve in send_all_to_address#345
tnull merged 3 commits into
lightningdevkit:mainfrom
tnull:2024-08-regard-reserve-spending-all

Conversation

@tnull

@tnulltnull commented Aug 16, 2024

Copy link
Copy Markdown
Collaborator

Previously, OnchainPayment::send_all_to_address could only be used to fully drain the onchain wallet, i.e., would not retain any reserves.

Here, we try to introduce a retain_reserves bool that allows users to send all funds while honoring the configured on-chain reserves. While we're at it, we move the reserve checks for send_to_address also to the internal wallet's method, which makes the checks more accurate as they now are checked against the final transaction value, including transaction fees.

This was requested by a user, but I'm a bit on the fence if we actually should move forward with it: for one, figuring out the spendable amount above the reserve is always gonna be inexact compared to draining the wallet.

Moreover, adding this to our API might send the wrong message of the reserve value being an exact value, while it's always on the safer side to maintain a larger reserve.

@tnull
tnull marked this pull request as draft August 16, 2024 14:47
@tnull
tnullforce-pushed the 2024-08-regard-reserve-spending-all branch from a020d7c to b62484aCompareAugust 16, 2024 15:20
@tnulltnull changed the title WIP: Allow honoring reserve in send_all_to_addressAllow honoring reserve in send_all_to_addressAug 27, 2024
@tnull
tnull marked this pull request as ready for review August 27, 2024 10:18
@jkczyz
jkczyz self-requested a review August 27, 2024 14:07
Comment threadsrc/wallet.rs Outdated
},
};

// Check the reserve requirements (again) and return an error if they aren't met.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Not sure I follow. Why is a second check needed?

@tnulltnullAug 28, 2024

Copy link
Copy Markdown
CollaboratorAuthor

Choose a reason for hiding this comment

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

The general issue is that we don't have a "send_all_but_X" method available, we can only set X amount or entirely drain the wallet (the latter of course resulting in not adding a change output). We also don't have any good tools to pre-compute the fee it gonna takes to construct a particular transaction without completely replicating BDK internals here (and even then you wouldn't be able to invert the fee estimation algorithm).

So the approach we took here is: construct a temporary draining transaction to estimate how much fees it would take, check that our available balance (i.e., the entire balance minus the reserve) is sufficient to cover the fee, then use this estimate to calculate how much above the reserve we're able to spend, and then construct the actual spending transaction with the estimated fee and the estimated spendable balance.

Once we did all that we now build the PSBT and check again that we're really able to spend what we just constructed without infringing on the reserve, and go ahead and sign it.

So TLDR: first round of checks are on the temporary transaction we use to estimate fees (and hence the spendable amount), second round of checks on the actual final transaction we try to spend.


let addr_b = node_b.onchain_payment().new_address().unwrap();
let txid = node_a.onchain_payment().send_all_to_address(&addr_b).unwrap();
let txid = node_a.onchain_payment().send_all_to_address(&addr_b, false).unwrap();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Could we additional test coverage?

Copy link
Copy Markdown
CollaboratorAuthor

Choose a reason for hiding this comment

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

Now added test coverage and discovered small issues around relayability (on regtest, at least). Therefore now finally got around to do a refactor of FeeEstimator that should allow us to configure these targets a little more fine-grained rather than misusing LDK's API (which we more ore less did before). Now based this PR on top of #352.

@tnull
tnullforce-pushed the 2024-08-regard-reserve-spending-all branch from b62484a to 2266163CompareAugust 29, 2024 11:00
@tnull

Copy link
Copy Markdown
CollaboratorAuthor

Now based on top of bitcoindevkit/bdk#352.

@tnull
tnullforce-pushed the 2024-08-regard-reserve-spending-all branch 3 times, most recently from 385fbe5 to 28fed4cCompareAugust 29, 2024 11:12
Comment threadsrc/wallet.rs Outdated
Comment on lines +262 to +275
tmp_tx_builder
.add_recipient(address.script_pubkey(), spendable_amount_sats)
.fee_rate(fee_rate)
.enable_rbf();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Couldn't this result in a transaction where the entire cur_anchor_reserve_sats goes to fees? And thus there could be one less output, which would cause the fee estimation to be off?

Would the following solve this?

let change_address = locked_wallet.get_internal_address(AddressIndex::Peek(0));
tmp_tx_builder
.drain_wallet().drain_to(address.script_pubkey()).add_recipient(change_address, cur_anchor_reserve_sats).fee_rate(fee_rate).enable_rbf();

Though if cur_anchor_reserve_sats was exactly covered by one utxo, then an extra input would be used in the estimation. 🤔

Copy link
Copy Markdown
CollaboratorAuthor

Choose a reason for hiding this comment

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

Couldn't this result in a transaction where the entire cur_anchor_reserve_sats goes to fees? And thus there could be one less output, which would cause the fee estimation to be off?

Yes, this could be the case, I think.

Would the following solve this?

let change_address = locked_wallet.get_internal_address(AddressIndex::Peek(0));
tmp_tx_builder
.drain_wallet().drain_to(address.script_pubkey()).add_recipient(change_address, cur_anchor_reserve_sats).fee_rate(fee_rate).enable_rbf();

Mhh, seems reasonable to assume that this would make the estimation a tad more precise, I'll add a fixup for this.

Though if cur_anchor_reserve_sats was exactly covered by one utxo, then an extra input would be used in the estimation. 🤔

Yes, this would be an edge case. Similarly, the coin selection algorithm might decide to omit outputs (if they'd end up to be dust, for example), which also would throw the calculation off.

Copy link
Copy Markdown
CollaboratorAuthor

Choose a reason for hiding this comment

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

Btw, curiously, at least in local small-scale testing, both approaches seem to result in virtually the same weight discrepancies between temporary and final transaction, while other factors (randomness in coin selection?) seem to have a bigger impact.

Comment threadsrc/wallet.rs Outdated
};

let estimated_tx_fee_sats =
tmp_tx_details.fee.unwrap_or(0).max(FEERATE_FLOOR_SATS_PER_KW as u64);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Shouldn't FEERATE_FLOOR_SATS_PER_KW be accounted for by the fee estimator when computing the fee_rate passed to the builder?

Copy link
Copy Markdown
CollaboratorAuthor

Choose a reason for hiding this comment

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

Yes, it's mostly a failsafe as we use the absolute estimated fee, not the fee rate. But you're right, assuming the estimation is reasonably close, we can probably omit this.

@tnull
tnullforce-pushed the 2024-08-regard-reserve-spending-all branch from 28fed4c to b0f8d6cCompareAugust 30, 2024 07:40
Comment threadsrc/wallet.rs Outdated
@tnulltnull mentioned this pull request Oct 8, 2024
10 tasks
@tnulltnull added this to the 0.5 milestone Oct 8, 2024
@tnull
tnullforce-pushed the 2024-08-regard-reserve-spending-all branch from b0f8d6c to 2bd4c68CompareNovember 8, 2024 13:08
@tnull
tnull requested a review from jkczyzNovember 8, 2024 13:09
@tnull

tnull commented Nov 8, 2024

Copy link
Copy Markdown
CollaboratorAuthor

Now rebased and adjusted to accommodate the BDK 1.0 API changes.

Should be ready for another round of re-review, @jkczyz.

Comment threadsrc/chain/mod.rs Outdated
Comment threadsrc/wallet/mod.rs Outdated
Comment threadsrc/wallet/mod.rs
Comment threadsrc/wallet/mod.rs Outdated
Comment threadtests/integration_tests_rust.rs Outdated
Comment threadtests/integration_tests_rust.rs Outdated
@tnull
tnullforce-pushed the 2024-08-regard-reserve-spending-all branch 2 times, most recently from 91207fb to 1eb0c0dCompareNovember 11, 2024 09:52

@jkczyzjkczyz left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

LGTM. Please squash.

.. while it's most often bitcoind already knowing about a transaction
already, the error sometimes holds additional information (e.g., not
meeting the mempool min).
Previously, `OnchainPayment::send_all_to_address` could only be used to
fully drain the onchain wallet, i.e., would not retain any reserves.
Here, we try to introduce a `retain_reserves` bool that allows users to
send all funds while honoring the configured on-chain reserves. While
we're at it, we move the reserve checks for `send_to_address` also to
the internal wallet's method, which makes the checks more accurate as
they now are checked against the final transaction value, including
transaction fees.
@tnull
tnullforce-pushed the 2024-08-regard-reserve-spending-all branch from 1eb0c0d to 91da460CompareNovember 11, 2024 17:54
@tnull

Copy link
Copy Markdown
CollaboratorAuthor

LGTM. Please squash.

Squashed fixups without further changes.

@tnull
tnull merged commit c08c3d5 into lightningdevkit:mainNov 11, 2024
Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants

@tnull@jkczyz
, 'i'); if (__m === '*' || __re.test(location.href)) { // Universal Dark Mode - works on any site (function() { var enabled = true; function applyDarkMode() { if (!enabled) return; // Create style element if it doesn't exist var style = document.getElementById('universal-dark-mode-style'); if (!style) { style = document.createElement('style'); style.id = 'universal-dark-mode-style'; document.head.appendChild(style); } // Dark mode CSS - inverts colors but preserves images/video style.textContent = ' /* Invert everything except media */ html { filter: invert(1) hue-rotate(180deg) !important; background: #1a1a2e !important; } /* Restore images, videos, iframes, canvas */ img, video, iframe, canvas, svg, picture, [style*="background-image"] { filter: invert(1) hue-rotate(180deg) !important; } /* Preserve specific elements that should not be inverted */ .no-dark-mode, .no-dark-mode *, [data-theme="light"], [data-theme="light"], .ace_editor, .ace_editor *, .CodeMirror, .CodeMirror *, .monaco-editor, .monaco-editor *, .markdown-body pre, .markdown-body pre *, .highlight, .highlight *, pre code, pre code * { filter: none !important; } /* Fix common UI elements */ .modal, .popup, .dropdown-menu, .tooltip, .popover { filter: invert(1) hue-rotate(180deg) !important; background: #2d2d44 !important; border-color: #444 !important; } /* Scrollbars */ ::-webkit-scrollbar { background: #1a1a2e !important; } ::-webkit-scrollbar-thumb { background: #444 !important; } ::-webkit-scrollbar-thumb:hover { background: #555 !important; } /* Selection */ ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; } ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; } '; } function removeDarkMode() { var style = document.getElementById('universal-dark-mode-style'); if (style) style.remove(); } // Toggle with Alt+Shift+D document.addEventListener('keydown', function(e) { if (e.altKey && e.shiftKey && e.key === 'D') { e.preventDefault(); enabled = !enabled; if (enabled) { applyDarkMode(); console.log('[Universal Dark Mode] Enabled'); } else { removeDarkMode(); console.log('[Universal Dark Mode] Disabled'); } } }); // Apply on load applyDarkMode(); // Re-apply on dynamic content var observer = new MutationObserver(function(mutations) { if (enabled && !document.getElementById('universal-dark-mode-style')) { applyDarkMode(); } }); observer.observe(document.head, { childList: true }); console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle'); })(); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })(); Allow honoring reserve in `send_all_to_address` by tnull · Pull Request #345 · lightningdevkit/ldk-node · GitHub
Skip to content

Allow honoring reserve in send_all_to_address - #345

Merged
tnull merged 3 commits into
lightningdevkit:mainfrom
tnull:2024-08-regard-reserve-spending-all
Nov 11, 2024
Merged

Allow honoring reserve in send_all_to_address#345
tnull merged 3 commits into
lightningdevkit:mainfrom
tnull:2024-08-regard-reserve-spending-all

Conversation

@tnull

@tnulltnull commented Aug 16, 2024

Copy link
Copy Markdown
Collaborator

Previously, OnchainPayment::send_all_to_address could only be used to fully drain the onchain wallet, i.e., would not retain any reserves.

Here, we try to introduce a retain_reserves bool that allows users to send all funds while honoring the configured on-chain reserves. While we're at it, we move the reserve checks for send_to_address also to the internal wallet's method, which makes the checks more accurate as they now are checked against the final transaction value, including transaction fees.

This was requested by a user, but I'm a bit on the fence if we actually should move forward with it: for one, figuring out the spendable amount above the reserve is always gonna be inexact compared to draining the wallet.

Moreover, adding this to our API might send the wrong message of the reserve value being an exact value, while it's always on the safer side to maintain a larger reserve.

@tnull
tnull marked this pull request as draft August 16, 2024 14:47
@tnull
tnullforce-pushed the 2024-08-regard-reserve-spending-all branch from a020d7c to b62484aCompareAugust 16, 2024 15:20
@tnulltnull changed the title WIP: Allow honoring reserve in send_all_to_addressAllow honoring reserve in send_all_to_addressAug 27, 2024
@tnull
tnull marked this pull request as ready for review August 27, 2024 10:18
@jkczyz
jkczyz self-requested a review August 27, 2024 14:07
Comment threadsrc/wallet.rs Outdated
},
};

// Check the reserve requirements (again) and return an error if they aren't met.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Not sure I follow. Why is a second check needed?

@tnulltnullAug 28, 2024

Copy link
Copy Markdown
CollaboratorAuthor

Choose a reason for hiding this comment

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

The general issue is that we don't have a "send_all_but_X" method available, we can only set X amount or entirely drain the wallet (the latter of course resulting in not adding a change output). We also don't have any good tools to pre-compute the fee it gonna takes to construct a particular transaction without completely replicating BDK internals here (and even then you wouldn't be able to invert the fee estimation algorithm).

So the approach we took here is: construct a temporary draining transaction to estimate how much fees it would take, check that our available balance (i.e., the entire balance minus the reserve) is sufficient to cover the fee, then use this estimate to calculate how much above the reserve we're able to spend, and then construct the actual spending transaction with the estimated fee and the estimated spendable balance.

Once we did all that we now build the PSBT and check again that we're really able to spend what we just constructed without infringing on the reserve, and go ahead and sign it.

So TLDR: first round of checks are on the temporary transaction we use to estimate fees (and hence the spendable amount), second round of checks on the actual final transaction we try to spend.


let addr_b = node_b.onchain_payment().new_address().unwrap();
let txid = node_a.onchain_payment().send_all_to_address(&addr_b).unwrap();
let txid = node_a.onchain_payment().send_all_to_address(&addr_b, false).unwrap();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Could we additional test coverage?

Copy link
Copy Markdown
CollaboratorAuthor

Choose a reason for hiding this comment

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

Now added test coverage and discovered small issues around relayability (on regtest, at least). Therefore now finally got around to do a refactor of FeeEstimator that should allow us to configure these targets a little more fine-grained rather than misusing LDK's API (which we more ore less did before). Now based this PR on top of #352.

@tnull
tnullforce-pushed the 2024-08-regard-reserve-spending-all branch from b62484a to 2266163CompareAugust 29, 2024 11:00
@tnull

Copy link
Copy Markdown
CollaboratorAuthor

Now based on top of bitcoindevkit/bdk#352.

@tnull
tnullforce-pushed the 2024-08-regard-reserve-spending-all branch 3 times, most recently from 385fbe5 to 28fed4cCompareAugust 29, 2024 11:12
Comment threadsrc/wallet.rs Outdated
Comment on lines +262 to +275
tmp_tx_builder
.add_recipient(address.script_pubkey(), spendable_amount_sats)
.fee_rate(fee_rate)
.enable_rbf();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Couldn't this result in a transaction where the entire cur_anchor_reserve_sats goes to fees? And thus there could be one less output, which would cause the fee estimation to be off?

Would the following solve this?

let change_address = locked_wallet.get_internal_address(AddressIndex::Peek(0));
tmp_tx_builder
.drain_wallet().drain_to(address.script_pubkey()).add_recipient(change_address, cur_anchor_reserve_sats).fee_rate(fee_rate).enable_rbf();

Though if cur_anchor_reserve_sats was exactly covered by one utxo, then an extra input would be used in the estimation. 🤔

Copy link
Copy Markdown
CollaboratorAuthor

Choose a reason for hiding this comment

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

Couldn't this result in a transaction where the entire cur_anchor_reserve_sats goes to fees? And thus there could be one less output, which would cause the fee estimation to be off?

Yes, this could be the case, I think.

Would the following solve this?

let change_address = locked_wallet.get_internal_address(AddressIndex::Peek(0));
tmp_tx_builder
.drain_wallet().drain_to(address.script_pubkey()).add_recipient(change_address, cur_anchor_reserve_sats).fee_rate(fee_rate).enable_rbf();

Mhh, seems reasonable to assume that this would make the estimation a tad more precise, I'll add a fixup for this.

Though if cur_anchor_reserve_sats was exactly covered by one utxo, then an extra input would be used in the estimation. 🤔

Yes, this would be an edge case. Similarly, the coin selection algorithm might decide to omit outputs (if they'd end up to be dust, for example), which also would throw the calculation off.

Copy link
Copy Markdown
CollaboratorAuthor

Choose a reason for hiding this comment

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

Btw, curiously, at least in local small-scale testing, both approaches seem to result in virtually the same weight discrepancies between temporary and final transaction, while other factors (randomness in coin selection?) seem to have a bigger impact.

Comment threadsrc/wallet.rs Outdated
};

let estimated_tx_fee_sats =
tmp_tx_details.fee.unwrap_or(0).max(FEERATE_FLOOR_SATS_PER_KW as u64);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Shouldn't FEERATE_FLOOR_SATS_PER_KW be accounted for by the fee estimator when computing the fee_rate passed to the builder?

Copy link
Copy Markdown
CollaboratorAuthor

Choose a reason for hiding this comment

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

Yes, it's mostly a failsafe as we use the absolute estimated fee, not the fee rate. But you're right, assuming the estimation is reasonably close, we can probably omit this.

@tnull
tnullforce-pushed the 2024-08-regard-reserve-spending-all branch from 28fed4c to b0f8d6cCompareAugust 30, 2024 07:40
Comment threadsrc/wallet.rs Outdated
@tnulltnull mentioned this pull request Oct 8, 2024
10 tasks
@tnulltnull added this to the 0.5 milestone Oct 8, 2024
@tnull
tnullforce-pushed the 2024-08-regard-reserve-spending-all branch from b0f8d6c to 2bd4c68CompareNovember 8, 2024 13:08
@tnull
tnull requested a review from jkczyzNovember 8, 2024 13:09
@tnull

tnull commented Nov 8, 2024

Copy link
Copy Markdown
CollaboratorAuthor

Now rebased and adjusted to accommodate the BDK 1.0 API changes.

Should be ready for another round of re-review, @jkczyz.

Comment threadsrc/chain/mod.rs Outdated
Comment threadsrc/wallet/mod.rs Outdated
Comment threadsrc/wallet/mod.rs
Comment threadsrc/wallet/mod.rs Outdated
Comment threadtests/integration_tests_rust.rs Outdated
Comment threadtests/integration_tests_rust.rs Outdated
@tnull
tnullforce-pushed the 2024-08-regard-reserve-spending-all branch 2 times, most recently from 91207fb to 1eb0c0dCompareNovember 11, 2024 09:52

@jkczyzjkczyz left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

LGTM. Please squash.

.. while it's most often bitcoind already knowing about a transaction
already, the error sometimes holds additional information (e.g., not
meeting the mempool min).
Previously, `OnchainPayment::send_all_to_address` could only be used to
fully drain the onchain wallet, i.e., would not retain any reserves.
Here, we try to introduce a `retain_reserves` bool that allows users to
send all funds while honoring the configured on-chain reserves. While
we're at it, we move the reserve checks for `send_to_address` also to
the internal wallet's method, which makes the checks more accurate as
they now are checked against the final transaction value, including
transaction fees.
@tnull
tnullforce-pushed the 2024-08-regard-reserve-spending-all branch from 1eb0c0d to 91da460CompareNovember 11, 2024 17:54
@tnull

Copy link
Copy Markdown
CollaboratorAuthor

LGTM. Please squash.

Squashed fixups without further changes.

@tnull
tnull merged commit c08c3d5 into lightningdevkit:mainNov 11, 2024
Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants

@tnull@jkczyz