Repository navigation
wallet: don't back-date locktime below input locktime - #34480
danielabrozzoni wants to merge 6 commits into
Conversation
|
The following sections might be updated with supplementary metadata relevant to reviewers and maintainers. ReviewsSee the guideline for information on the review process.
If your review is incorrectly listed, please copy-paste |
|
@ishaanam: I put you as a co-author for the first commit, because I started working from your code here #26902 (review) :) |
achow101
left a comment
There was a problem hiding this comment.
The
sendtoaddressandsendmanyRPCs don't spend unconfirmed inputs
They can spend unconfirmed change, and I would prefer for these to be tested as well since the calling of DiscourageFeeSniping is different between these RPCs and send and sendall.
When creating a transaction with anti fee sniping enabled, the wallet could previously select an nLockTime that was lower than the nLockTime of its input transactions. This can break the "transaction signed earlier but broadcast later" explanation and may act as a wallet fingerprint. This is fixed by constraining the anti fee sniping logic to never select an nLockTime lower than the maximum nLockTime of the wallet-owned input transactions. The minimum allowed value is passed to DiscourageFeeSniping(). Co-Authored-By: ishaanam <[email protected]>
The previous assertion only verified that nLockTime was non-zero. Tighten the check to ensure the locktime is within the allowed range, up to 100 blocks in the past.
6dd81c2 to
c3e79df
Compare
|
Thanks for your review Ava! I picked up your suggestions, and the idea in #26527 (comment). Changes since last push:
One concern I have, which I just realized: since we cannot know the I thought about a couple of ways to mitigate this but could not implement either. Let me know if I missed something:
Otherwise, we could disallow backdating if there's at least one external input, by setting |
Add a test to verify that when the anti fee sniping logic randomly backdates a transaction locktime, the send RPC never selects a value lower than the nLockTime of its input transactions.
Add a test to verify that when the anti fee sniping logic randomly backdates a transaction locktime, the send RPC never selects a value lower than the nLockTime of its input transactions.
Add a test to verify that when the anti fee sniping logic randomly backdates a transaction locktime, the send RPC never selects a value lower than the nLockTime of its input transactions.
Add a test to verify that when the anti fee sniping logic randomly backdates a transaction locktime, the send RPC never selects a value lower than the nLockTime of its input transactions.
c3e79df to
8bd6857
Compare
|
Thanks! Last push (8bd6857): |
|
Concept ACK 8bd6857, reviewing at the moment. |
| * Set a height-based locktime for new transactions (uses the height of the | ||
| * current chain tip unless we are not synced with the current chain | ||
| * |
There was a problem hiding this comment.
In 8c537a1 "wallet: don't back-date locktime below input locktime"
Nit: Might as well close the unclosed parenthesis in the comment.
| * | ||
| */ | ||
| void DiscourageFeeSniping(CMutableTransaction& tx, FastRandomContext& rng_fast, interfaces::Chain& chain, const uint256& block_hash, int block_height); | ||
| void DiscourageFeeSniping(CMutableTransaction& tx, FastRandomContext& rng_fast, interfaces::Chain& chain, const uint256& block_hash, int block_height, unsigned int min_allowed_locktime); |
There was a problem hiding this comment.
In 8c537a1 "wallet: don't back-date locktime below input locktime"
- void DiscourageFeeSniping(CMutableTransaction& tx, FastRandomContext& rng_fast, interfaces::Chain& chain, const uint256& block_hash, int block_height, unsigned int min_allowed_locktime);
+ void DiscourageFeeSniping(CMutableTransaction& tx, FastRandomContext& rng_fast, interfaces::Chain& chain, const uint256& block_hash, int block_height, uint32_t min_allowed_locktime);Reference:
bitcoin/src/primitives/transaction.h
Line 294 in 64294c8
| for (const auto& coin : selected_coins) { | ||
| if (const CWalletTx* coin_wtx{wallet.GetWalletTx(coin->outpoint.hash)}) { | ||
| max_input_locktime = std::max(max_input_locktime, coin_wtx->tx->nLockTime); | ||
| } | ||
| } |
There was a problem hiding this comment.
In 8c537a1 "wallet: don't back-date locktime below input locktime"
Can we loop this over txNew.vin similar to the implementation in rpc/spend? Then, we would be able to extract it out in a helper function and could avoid the code duplication.
The verbose comment is helpful but doesn't need to be duplicated imo.
There was a problem hiding this comment.
This helpful function, which would be extracted, most likely could be reused for fixing the related issue for replacement transactions later: #26526.
| void DiscourageFeeSniping(CMutableTransaction& tx, FastRandomContext& rng_fast, | ||
| interfaces::Chain& chain, const uint256& block_hash, int block_height) | ||
| interfaces::Chain& chain, const uint256& block_hash, int block_height, | ||
| unsigned int min_allowed_locktime) |
There was a problem hiding this comment.
In 8bd6857 "test: check sendmany respects input locktimes with anti fee sniping"
For the commit message:
locktime, the send RPC never selects
Either the last 4 test commits could be squashed into one, or the correct RPC name should be mentioned in the commit description. send is mentioned even for other RPCs.
| # Create 100 parent transactions, all with the same | ||
| # explicit backdated nLockTime. This avoids relying on the random | ||
| # anti fee sniping behavior and provides several inputs to spend from. | ||
| num_parents = 100 | ||
| tip_height = self.nodes[0].getblockcount() | ||
| parent_locktime = tip_height - 80 | ||
| for _ in range(num_parents): | ||
| wallet_rpc.send(outputs=[{test_wallet.getnewaddress(): 10}], locktime=parent_locktime) | ||
| self.generate(self.nodes[0], 5) | ||
| tip_height = self.nodes[0].getblockcount() | ||
| # Spend parents one by one until we observe a backdated | ||
| # nLockTime on a child transaction. Backdating happens randomly, so | ||
| # retry until the locktime is less than the current block height. | ||
| child_nlocktime = tip_height | ||
| num_tries = 0 | ||
| while child_nlocktime == tip_height: | ||
| child_txid = test_wallet.sendtoaddress(wallet_rpc.getnewaddress(), 9) | ||
| child_nlocktime = test_wallet.gettransaction(txid=child_txid, verbose=True)["decoded"]["locktime"] | ||
| num_tries += 1 | ||
| if num_tries >= num_parents: |
There was a problem hiding this comment.
In 4d8bedb "test: check sendtoaddress respects input locktimes with anti fee sniping"
In agreement with using multiple unspents, the previous 2 test commits didn't. However, few points:
- This doesn't test spending multiple utxos in one transaction, so we never fully test the logic that the max among them is picked up.
- In order to test the above point, the parent transactions should have different locktimes.
- I don't see why 100 unspents need to be tested and I'm unable to see the correlation between
num_triesandnum_parents. There's await_untilhelper that waits for the passed predicate to be true until a configurable timeout is reached. We want to avoid the assertion error that's one line below as much as possible.
Reference:
bitcoin/test/functional/test_framework/test_framework.py
Lines 745 to 746 in 64294c8
There was a problem hiding this comment.
In agreement with using multiple unspents, the previous 2 test commits didn't.
Yes, sorry if it wasn't clear in the commit message.
What I'm doing here is:
- creating 100 parent transactions
- creating children transactions over and over again, each one of them spending exactly one parent (child_tx
ispends parent_txi), until I find one child transaction that has a backdated nlocktime. At that point, I check that the nlocktime is >= the one of the parent.
The reason why only the sendtoaddress and sendmany tests do this is because with send/sendall I can set add_to_wallet=False, not adding the tx to the wallet or broadcasting it, and so I can keep re-using the same parent transaction. (See #34480 (comment))
I can absolutely modify the test to have multiple parents, and update the variable names/comments to make everything clearer!
There's a wait_until helper that waits for the passed predicate to be true until a configurable timeout is reached.
Ah, thanks! I'll try refactoring the test in order to use wait_until :)
There was a problem hiding this comment.
The reason why only the sendtoaddress and sendmany tests do this is because with send/sendall I can set add_to_wallet=False, not adding the tx to the wallet or broadcasting it, and so I can keep re-using the same parent transaction.
I see, add_to_wallet does seem quite handy but unfortunate that it's not available to sendtoaddress/sendmany. I guess the current idea seems alright but would suggest the following:
- The transactions should spend 2 inputs with different nlocktimes instead of one.
- If somehow in all these tries, the backdated nlocktime is not generated, we should not raise the below assertion error - it would make the test flaky and might fail CI of unrelated PRs later. I don't believe the
wait_untilapproach would be foolproof as well. The only complete solution I see is to fund the wallet with more inputs and keep retrying until the backdate nlocktime is generated.
if num_tries >= num_parents:
raise AssertionError("RPC call sendtoaddress() did not produce a backdated nLockTime")| self.nodes[1].createwallet("test_fee_sniping") | ||
| wallet = self.nodes[1].get_wallet_rpc("test_fee_sniping") | ||
| tip_height = self.nodes[0].getblockcount() | ||
| # Create a parent transaction with an explicit backdated nLockTime | ||
| parent_nlocktime = tip_height - 80 | ||
| self.nodes[0].send(outputs=[{wallet.getnewaddress(): 10}], locktime=parent_nlocktime) | ||
| self.sync_mempools() | ||
| # Create child transactions until we observe a backdated nLockTime. | ||
| # Backdating happens randomly, so retry until the locktime is less than | ||
| # the current block height. | ||
| utxos = wallet.listunspent(0, 0) | ||
| child_nlocktime = tip_height | ||
| while child_nlocktime == tip_height: | ||
| # We set add_to_wallet=False, so that the transaction won't get added to the wallet or broadcasted. | ||
| # This way we can continue creating transactions spending the same input, until we find one with | ||
| # a backdated nlocktime | ||
| child_hex = wallet.send([{wallet.getnewaddress(): 9}], inputs=utxos, add_to_wallet=False)["hex"] |
There was a problem hiding this comment.
In 4100ee8 "test: check send respects input locktimes with anti fee sniping"
From this PR comment #34480 (comment):
One concern I have, which I just realized: since we cannot know the nLockTime for external inputs, we might still end up backdating below those inputs’ nLockTime. This could be problematic, since it may leak some information about which inputs are wallet-owned. Is this acceptable?
I thought about a couple of ways to mitigate this but could not implement either. Let me know if I missed something:
Getting external unconfirmed inputs from the mempool. Unfortunately, I could use wallet.chain to check whether a tx is in the mempool (isInMempool), but couldn't retrieve the whole transaction
Is this concern still valid? IIUC, this test successfully tests the external unconfirmed inputs. The wallet in node0 sends some funds to the wallet in node1 that are unconfirmed at the moment.
There was a problem hiding this comment.
I think I misused the word "external", I meant "inputs that are not owned by the wallet". In this test case, node1 receives the funds and spends them, so the input is owned by the wallet.
Before calling DiscourageFeeSniping, I'm finding the highest input nlocktime using GetWalletTx, but this means that if the transaction input is not owned by the wallet, I won't be able to see the nlocktime.
I think I can hit this edge case in a couple of ways... For example, using send + add_to_wallet=False + inputs:
❯ ./build/bin/bitcoin-cli -datadir=signet-datadir -named send outputs='[{"tb1p4tp4l6glyr2gs94neqcpr5gha7344nfyznfkc8szkreflscsdkgqsdent4": 0.00001}]' add_to_wallet=false fee_rate=1 inputs='[{"txid": "fb20af6c84b3fc1baff2f915140d0445b3479549093de35bdbe9e7d7d1008333", "vout": 0}]'
{
"psbt": "cHNidP8BAIkCAAAAATODANHX5+nbW+M9CUmVR7NFBA0UFfnyrxv8s4RsryD7AAAAAAD9////Am5QPJMYAAAAIlEgR/Kst32gSmc8pi48WvNByPA4RzliEXhWybc25kgAUpnoAwAAAAAAACJRIKrDX+kfINSIFrPIMBHRF++jWs0kFNNsHgKw8p/DEG2Q0XAEAAAAAQUgtEB0iqlfBOJ0PlRRM3ubBOQxa5Kq4XSqozDCQ/cjgDUhB7RAdIqpXwTidD5UUTN7mwTkMWuSquF0qqMwwkP3I4A1GQAIf5iUVgAAgAEAAIAAAACAAQAAAH0AAAAAAA==",
"complete": false
}
I picked these addresses and txid from a block explorer, and they are not in my wallet. The resulting psbt was signed at block height 291092, but the nlocktime was backdated to 291025. If I understand correctly the core wallet would have had no way of knowing whether it was backlocking before the input tx nlocktime, because it didn't know the input tx.
There was a problem hiding this comment.
I meant "inputs that are not owned by the wallet".
When I read this statement, the first things that pops up in my mind is that wallet can't spend the inputs that it doesn't own, which seems fine.
For example, using send + add_to_wallet=False + inputs
I picked these addresses and txid from a block explorer, and they are not in my wallet.
I think I now get what you mean. However, this seems like quite a contrived example, can you explain how this can happen in a real world scenario - as in what would motivate the user go about using this approach?
{"add_to_wallet", RPCArg::Type::BOOL, RPCArg::Default{true}, "When false, returns the serialized transaction without broadcasting or adding it to the wallet"},If add_to_wallet is used, then the user is responsible for storing the serialized transaction because there is no other way for the wallet to get it. If the user intends to create a child transaction of such a transaction, then the full transaction hex must be provided by the user, an option that I could not find in these RPCs. All I can see are the following arguments for inputs in these RPCs that allude to the assumption that the wallet can find the hex of the transaction pointed to by txid - something that doesn't hold true for the above example.
{"inputs", RPCArg::Type::ARR, RPCArg::Default{UniValue::VARR}, "Specify inputs instead of adding them automatically.",
{
{"", RPCArg::Type::OBJ, RPCArg::Optional::OMITTED, "", {
{"txid", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "The transaction id"},
{"vout", RPCArg::Type::NUM, RPCArg::Optional::NO, "The output number"},
{"sequence", RPCArg::Type::NUM, RPCArg::DefaultHint{"depends on the value of the 'replaceable' and 'locktime' arguments"}, "The sequence number"},
{"weight", RPCArg::Type::NUM, RPCArg::DefaultHint{"Calculated from wallet and solving data"}, "The maximum weight for this input, "
"including the weight of the outpoint and sequence number. "
"Note that signature sizes are not guaranteed to be consistent, "
"so the maximum DER signatures size of 73 bytes should be used when considering ECDSA signatures."
"Remember to convert serialized sizes to weight units when necessary."},
}},
},
},| int locktime_range = std::min(100, int(block_height - min_allowed_locktime)); | ||
| tx.nLockTime = std::max(int(min_allowed_locktime), int(tx.nLockTime) - int(rng_fast.randrange(locktime_range))); |
There was a problem hiding this comment.
In 8c537a1 "wallet: don't back-date locktime below input locktime"
Building up on this previous comment for the nLockTime data type #34480 (comment): I find these intermediate int conversions unnecessary because the tx.nLockTime type is already uint32_t. These casts also make the code difficult to read and promotes the tendency in the reader to skip reading altogether.
The following diff removes all of them except the block_height one. Though it can be argued that its type can also be changed but that would be an unrelated change, so to keep the diff minimal:
- int locktime_range = std::min(100, int(block_height - min_allowed_locktime));
- tx.nLockTime = std::max(int(min_allowed_locktime), int(tx.nLockTime) - int(rng_fast.randrange(locktime_range)));
+ uint32_t locktime_range = std::min(100U, uint32_t(block_height) - min_allowed_locktime);
+ tx.nLockTime = std::max(min_allowed_locktime, tx.nLockTime - rng_fast.randrange(locktime_range));|
NACK. On its face this is kind of a pointless change: A transaction can have any locktime before where was created, it's not a "time the transaction was created" except as a side effect of anti-fee sniping and then only if it was anti-fee-sniping that set the lock time... and so it's not weird for a transaction to have a locktime after one of its inputs. It leaks no information to do this, so it's harmless if semantically meaningless since you can't confirm a transaction before its inputs. The practice is not, however, necessarily semantically meaningless. It is if SIGHASH_ALL is used, but if the transaction uses ANYONECANPAY or just doesn't have signatures, then it may be completely semantically sensible to have the locktime of a transaction lower than an input it uses when it does get confirmed. On these basis I believe #26527 was just mistaken, it's not a problem. All this seemed like pointless churn to me, and harmless within the context of core's wallet and anti-fee-sniping where the simplified understanding (e.g. no ANYONECANPAY) usually applies... I wasn't going to comment at all, other than to maybe mention it to the authors so they didn't think they could make these assumptions outside of the wallet. But then I realized this PR has more serious problems: Applying the clamping only to wallet transactions is a distinguisher which identifies inputs as belonging to the wallet or not, and would potentially leak which inputs belong to the author (e.g. in a payjoin/coinjoin transactions). It doesn't follow the causality argument (for non-anyonecanpay inputs) that a tx cannot be confirmed before its inputs, which doesn't care who authored the inputs. I think this is a fatal privacy vulnerability. Even though nothing in the wallet's UI creates payjoins or coinjoins right now AFAIK people do it via the RPC, and future features could implement stuff like payjoin support without noticing this leak. The approach here is also incorrect in that even among wallet transactions it would apply deeply and not just to the immediate inputs: We cannot assume that all transactions in the wallet were authored with the same code we're currently. So if C spends B which spends A then C's locktime would need to be checked against A too and not just B. Correctly applying that causality limit would require applying it to all transactions in the causative transaction history, regardless of who owns them. -- This data isn't tracked at all right now not even in the chainstate, so there is no trivial fix. Even making it just go one deep (which still doesn't completely 'fix' the behavior) is also not trivial due to needing non-wallet data. The code also doesn't appear to correctly (or at least intentionally) handle the fact that locktime is logically a union type between a lock height and a lock time. How does one construct a maximum between inputs that are lock heights and lock times? (I believe the current code just blindly changes things to locktimes if any input is a time-- probably not the intended behavior!). It also doesn't appear to check if the locktime is actually active through non-maximal sequence. So I think to implement the intent of this would require tracking in the UTXO set a maximum locktime and lock height for the casual history of every output in the change (taking care to inspect sequences to only include active locks), and then apply it. That would be conceptually correct absent the existence of ANYONECANPAY (which I think can't ever be made to make sense with this behavior). Sensibly handling mixed locktimes also seems hard even once you've correctly tracked them, as you may not always be able to convert between them until very close to locked in (when heights are convertible to MTP times). But I think ultimately pointless because it's an attempt to fix a non-issue, and would be a complex, invasive, and runtime expensive change, and the half measure should not be done due to the privacy issue. |
Currently doing those via the
This probably needs a recommendation in the BIPs as well.
Hmm, good point. It looks like it would change to timestamps, and then immediately assert.
There are checks prior to calling |
That helps only if you can presume all in-wallet transactions (including potentially ones created before anti-fee-sniping was invented) were created by code that makes them final! :) |
|
Thanks for the feedback @gmaxwell! I agree with you that this change is a half measure, and your message helped me understand that it's a smaller improvement than what I initially thought. I still think it might be worth pursuing, since the privacy issue seems solvable. However, I'm not sure if this particular half measure is worth the review time and slight increase in code complexity. The goal of this PR is to make anti-fee-sniping less obvious in certain (very) specific cases. The benefit is that an external observer would not be able to clearly distinguish between a wallet that implements anti-fee-sniping and one that simply supports nLockTime where the user selected it manually. That said, there are a couple of issues, so thanks for pointing them out and taking the time to explain!
As far as I can see, there are two ways to create a multiparty transaction:
Case 1) can be hit at the moment, using We can't hit 2) at the moment, since we don't have a way to create a transaction and sign it with ANYONECANPAY with any RPCs affected by this change (
Yes, true. I agree with you that implementing the full fix wouldn't be worth the effort, and without implementing it, this is just a half measure.
Yes, thanks for catching this. I didn't consider time-based locktime when writing the current code, which currently would simply not backdate at all if any parent had a time-based nlocktime. (It doesn’t crash, but that’s not because I handled time-based locktimes properly, just because it happens to work out :)) I think there could be two ways to go about this:
I don't have a strong preference either way.
Yes, thank you. All code paths that lead to calling DiscourageFeeSniping already check that the sequence is non-final so anti-fee-sniping can work. However, when calculating Where this puts usOne approach for this PR could be: a) Only consider the immediate parents of a transaction, instead of all the ancestor history. As you pointed out, considering the whole history would be extremely complex and not worth it. b) Check that the previous locktime is active, ofc :) We can check each inputs' nSequence, ignore the transaction nlocktime if all are SEQUENCE_FINAL Then, regarding time based locktimes, one of the following: c1) Only consider height based timelocks from the parents, and ignore time based ones. And finally d) Disable backdating if there are non-wallet inputs The result would be: In the specific case this PR targets, if I create B spending A and A has a height-based locktime, then B’s locktime would not be set below A’s. However, there are still cases this does not address:
Overall, this would be a small improvement over the current behavior, but I am still unsure whether it justifies the effort. |
I don't completely agree. I think that when the locktime is older than its inputs, it reveals two things:
This could be used to fingerprint the transaction. I believe this topic is worth investigating, and it would be useful to have some data to know how often this occurs and to extract some information on how to solve it.
I absolutely agree. Applying this only to the inputs that the wallet owns is dangerous, since it can reveal which inputs belong to the wallet and which don't. Daniela’s solution, not backdating when there are external inputs, would expose transactions that contain only wallet owned inputs. If we backdate when applying this approach, if for other reasons it is possible to know the transactions come from a Core wallet, it becomes easy to see that the transaction only have inputs owned by the wallet.
I do think it matters. If we limit the backdating to the previous transaction’s locktime, we are simply ensuring that the locktime is equal to or newer than its inputs. It doesn’t really matter if it is older than the grandparent transaction, as that doesn’t reveal any new information beyond what the current behavior already exposes. We would just be preventing new transactions from introducing that behavior. Regarding time-based locktime, I think Daniela’s solution of not backdating is the correct one. If a transaction has an input with a time-based locktime and the locktime height is set to an older value, it becomes very obvious that it comes from Core (since it is the only wallet doing this). However, if the locktime base height is set based on the current height, the assumption that it comes from Core becomes less obvious. Overall, I think it would be useful to have more data on how often this occurs, as that could help us make better decisions about the right approach. However, regardless of the solution we choose, I feel there will likely still be some fingerprinting concerns, since Core may be the only wallet implementing it. |
Yes. Thanks for catching this, it wasn't clear to me at first :) I think it makes sense to go back to what the original issue suggested - not backdating for unconfirmed inputs only. However, I'm closing this as I'm not interested in working on this anymore. Thanks everyone for the reviews! |
Fixes #26527
The Bitcoin Core wallet implements an anti-fee-sniping mechanism that sets a transaction's nLockTime to the current block height, and occasionally to an earlier height.
Previously, when creating a transaction, the wallet could choose an nLockTime that was lower than the nLockTime of one of its inputs. This creates an unrealistic "transaction signed earlier but only broadcast now" scenario and may act as a wallet fingerprint.
This PR fixes the issue by adding a
min_allowed_locktimeparameter toDiscourageFeeSniping. When creating a transaction, the wallet now sets this minimum to the highest locktime among all parent transactions. This ensures that while the locktime can still be backdated for anti-fee-sniping, it won't go below any input's locktime.DiscourageFeeSnipingis invoked by the following RPCs:sendallsendsendtoaddresssendmanyfundrawtransactionwalletcreatefundedpsbtTests are added for
sendall,send,sendtoaddressandsendmany.fundrawtransactionandwalletcreatefundedpsbtcan't hit this edge case, because they don't use the anti-fee-sniping logic and instead always set nLockTime to 0 unless explicitly provided by the user.