Skip to content

rpc: Merge joinpsbts locktimes correctly - #35100

Closed
nervana21 wants to merge 5 commits into
bitcoin:masterfrom
nervana21:20260416_locktime
Closed

nervana21 wants to merge 5 commits into
bitcoin:masterfrom
nervana21:20260416_locktime

Conversation

@nervana21

@nervana21 nervana21 commented Apr 17, 2026 •

Copy link
Copy Markdown
Contributor

joinpsbts previously took the minimum nLockTime across the PSBTs being merged, so the combined transaction could be minable earlier than the strictest party’s locktime. A merged PSBT should use the maximum nLockTime amongst the PSBTs that have at least one input with nSequence != SEQUENCE_FINAL and with nLockTime != 0.

PSBTs whose inputs are all SEQUENCE_FINAL or with nLockTime == 0 do not constrain the locktime.

This PR implements the fix, updates RPC documentation, adds test_joinpsbts, and updates the release notes.

@DrahtBot

DrahtBot commented Apr 17, 2026 •

Copy link
Copy Markdown
Contributor

The following sections might be updated with supplementary metadata relevant to reviewers and maintainers.

Code Coverage & Benchmarks

For details see: https://corecheck.dev/bitcoin/bitcoin/pulls/35100.

Reviews

See the guideline for information on the review process.

Type Reviewers
ACK w0xlt, frankomosh
Concept ACK rkrux
Stale ACK ViniciusCestarii

If your review is incorrectly listed, please copy-paste <!--meta-tag:bot-skip--> into the comment that the bot should ignore.

Conflicts

Reviewers, this pull request conflicts with the following ones:

  • #35516 (rpc: preserve global xpubs and proprietary fields in joinpsbts by thomasbuilds)
  • #33014 (rpc: Fix internal bug in descriptorprocesspsbt when encountering invalid signatures by b-l-u-e)

If you consider this pull request important, please also help to review the conflicting pull requests. Ideally, start with the one that should be merged first.

@Bicaru20 Bicaru20 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.

Left some comment son the code.

Still, I think it should be discuss how to approach the case where we have a height-based timelock and time-based timelock. If I am not wrong, it is considered height-based if 0 < locktime < 500_000_000, and if it is higher than that it is time-based.

With the current approach, if we had a locktime of each type, the time-based would always be the max_locktime, whether or not the height-based is older. I am not sure if this should be the expected behavior, or if it is at least better than what we currently have, which selects the min_locktime.

Comment thread src/rpc/rawtransaction.cpp Outdated
Comment on lines +1833 to +1835
if (locktime_enabled && (!has_locktime_constraint || psbtx.tx->nLockTime > max_locktime)) {
max_locktime = psbtx.tx->nLockTime;
has_locktime_constraint = true;

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.

I don't understand why you need the has_locktime_constarint. If I am not wrong, remvoing it would not alter the logic of the if as it would still enter always that the current locktime is higher. I would suggest to eliminate it:

Suggested change
if (locktime_enabled && (!has_locktime_constraint || psbtx.tx->nLockTime > max_locktime)) {
max_locktime = psbtx.tx->nLockTime;
has_locktime_constraint = true;
// Choose the highest lock time
if (locktime_enabled && psbtx.tx->nLockTime > max_locktime) {
max_locktime = psbtx.tx->nLockTime;

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

has_locktime_constraint is meant to be based on the logic found here:

// Even if tx.nLockTime isn't satisfied by nBlockHeight/nBlockTime, a
// transaction is still considered final if all inputs' nSequence ==
// SEQUENCE_FINAL (0xffffffff), in which case nLockTime is ignored.
//
// Because of this behavior OP_CHECKLOCKTIMEVERIFY/CheckLockTime() will
// also check that the spending input's nSequence != SEQUENCE_FINAL,
// ensuring that an unsatisfied nLockTime value will actually cause
// IsFinalTx() to return false here:
for (const auto& txin : tx.vin) {
if (!(txin.nSequence == CTxIn::SEQUENCE_FINAL))
return false;
}

It’s my understanding that not all inputs’ locktimes should contribute to the overall transaction locktime constraint. Specifically, if all inputs have nSequence set to SEQUENCE_FINAL, then nLockTime is ignored. So, in joinpsbts, I think we should only consider a PSBT’s nLockTime if it has at least one input with nSequence != SEQUENCE_FINAL.

Does that make sense, or am I still overlooking something?

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.

Yes, if in al the inputs the nSequence is set to SEQUENCE_FINAL the locktime shouldn't be considered. However, I do not see how the variable has_locktime_constraint helps you checks this. This is done in locktime_enabled, which checks if at least one inputs doesn't have SEQUENCE_FINAL.

My logic tells me that has_locktime_constraint will just be needed the first time this condition is evaluated:

 if (locktime_enabled && (!has_locktime_constraint || psbtx.tx->nLockTime > max_locktime)) {

The locktime_enabled is needed since it is checking that at least one input has SEQUENCE_FINAL.

The !has_locktime_constraint will always be true the first time since it is initialized to false and then it is changed to true after the first valid assignment.

On the other hand, the condition psbtx.tx->nLockTime > max_locktime will also typically be true on the first iteration, since max_locktime is initialized to 0. Therefore, almost any locktime will satisfy it. But even if the LockTime = 0, the behavior remains consistent, since max_locktime would remain unchanged.

What I am trying to say is that has_locktime_constraint is redundant since usually psbtx.tx->nLockTime > max_locktime will also usually be staisfied. And even when it is not statifaied (Locktime = 0), there is no need to enter in the if.

I hope I explained myself clearly

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Okay, I see. I've updated the code.

Comment thread test/functional/rpc_psbt.py Resolved
@nervana21

Copy link
Copy Markdown
Contributor Author

With the current approach, if we had a locktime of each type, the time-based would always be the max_locktime, whether or not the height-based is older. I am not sure if this should be the expected behavior, or if it is at least better than what we currently have, which selects the min_locktime.

Thanks for pointing this out. Yea, with respect to this issue, I think it would make the most sense if we never tried to compare height-based locktimes and time-based locktimes (only compare "apples to apples"). I'll look more for examples of how the is handled elsewhere in the codebase.

@Bicaru20

Copy link
Copy Markdown
Contributor

Thanks for pointing this out. Yea, with respect to this issue, I think it would make the most sense if we never tried to compare height-based locktimes and time-based locktimes (only compare "apples to apples"). I'll look more for examples of how the is handled elsewhere in the codebase.

It may be enough for now since there is almost no usage of time-based locktimes (you can check the mainnet explorer to see the exact %). And it would be even less the % of psbt convined with diferent locktime. However, I think that ideally we should think a way to handel this cases, somthing like make the user choose one of the locktimes or set a new one, or maybe even set it to 0. I am not really sure which one would be the best option.

@GerardoTaboada

Copy link
Copy Markdown
Contributor

Yeah, the old min-locktime behavior was a real footgun. Anyone who signed first with a strict locktime would silently get overridden by whoever signed last with a looser one, which kind of defeats the whole point. Glad to see this fixed.

A couple of things on top of what @Bicaru20 already raised:

Agree that has_locktime_constraint is doing nothing once max_locktime starts at 0 and the locktime-enabled gate already filters out the all-SEQUENCE_FINAL PSBTs. The plain > comparison covers the first iteration just as well.

The height-vs-time locktime thing is worth discussing more before settling. A single tx only has one nLockTime field with one interpretation, so if some incoming PSBTs are height-based and others are time-based there's no merged value that respects everyone's intent. Picking the numeric max can produce a tx that semantically locks none of the original parties the way they expected. Not sure what the cleanest answer is, could be rejecting the join, could be something else, but it feels worth nailing down before this lands rather than leaving the behavior implicit.

One test case I'd add: all PSBTs have every input as SEQUENCE_FINAL, so nobody contributes a constraint and the merged tx should come out with nLockTime = 0. The current tests cover the "one is final-only, one isn't" case but not the "all final-only" one, and that's the path where max_locktime stays at its initial value, so it'd be nice to lock that down.

Tiny doc nit: the new help line is accurate but a reader who doesn't already know the rule might not get why SEQUENCE_FINAL matters. Tagging on something like "(PSBTs with all inputs final do not constrain the locktime)" would make the help readable on its own.

@nervana21

Copy link
Copy Markdown
Contributor Author

@GerardoTaboada Thanks for the feedback!

I've updated the code to address your concerns/suggestions. This implementation disallows joining pbsts with different locktime types.

@ViniciusCestarii

Copy link
Copy Markdown
Contributor

tACK 077457b4103038cff8e781e7b09573ad73cbaa70 built and ran new functional tests and tried a single PSBT with mixed inputs (one SEQUENCE_FINAL, one non-final) and a time-based nLockTime, joined with a height-based PSBT.

@Bicaru20

Bicaru20 commented May 4, 2026 •

Copy link
Copy Markdown
Contributor

This implementation disallows joining pbsts with different locktime types.

I'm still not conviced this is the right choice, specially if the current behavior is to allow psbts with diferent locktimes to be joined. For this case, I think it would be better to leave the psbt to 0 or leave the lowest locktime (as we do rigth now) and maybe throw a warning message so the user can see two different lockitmes are present in the psbts.

It would be nice to hear other people opinion on this.

@ViniciusCestarii

ViniciusCestarii commented May 4, 2026 •

Copy link
Copy Markdown
Contributor

There's precedent for this RPC to throw an error when something is ambiguous:

joinpsbts does this on duplicate inputs rawtransaction.cpp: two PSBTs claiming the same UTXO is a real conflict the RPC could paper over by dropping one, but it throws instead. Mixed height/time locktimes is the same shape of conflict in the same RPC, so rejecting is consistent.

It's about not producing a PSBT that can violate someone's explicit constraint.

Rejection forces the caller to confront the conflict explicitly and resolve it.

That said, the breaking change concern is valid. My intuition is that few callers actually rely on the current behavior of silently picking the lower locktime but I can't back that up with data, and I genuinely don't know what the project's bar is for a breaking change of this kind.

@nervana21

Copy link
Copy Markdown
Contributor Author

Updated to rebase off master and changed the structure of functional tests. I think this approach is easier to follow and best allows for modification if a different behavior is eventually chosen.

@w0xlt w0xlt 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.

ACK 5c7a61a4b094232bf4c44c4a75afa75524ca4ad2 mod some suggestions.

Comment thread test/functional/rpc_psbt.py Resolved
Comment thread test/functional/rpc_psbt.py Resolved

@rkrux rkrux 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.

Concept ACK 5c7a61a4b094232bf4c44c4a75afa75524ca4ad2
ISTM that it's correct to use the max locktime of the psbts being joined.

Combined diff for the rawtransaction.cpp suggestions:

diff --git a/src/rpc/rawtransaction.cpp b/src/rpc/rawtransaction.cpp
index 4b3024a942..e27ceec0fd 100644
--- a/src/rpc/rawtransaction.cpp
+++ b/src/rpc/rawtransaction.cpp
@@ -1891,7 +1891,7 @@ static RPCMethod joinpsbts()
     }
 
     uint32_t best_version = 1;
-    uint32_t max_locktime = 0;
+    std::optional<uint32_t> max_locktime = std::nullopt;
     for (unsigned int i = 0; i < txs.size(); ++i) {
         util::Result<PartiallySignedTransaction> psbt_res = DecodeBase64PSBT(txs[i].get_str());
         if (!psbt_res) {
@@ -1907,24 +1907,23 @@ static RPCMethod joinpsbts()
             best_version = psbtx.tx_version;
         }
         // If every input has nSequence == SEQUENCE_FINAL, nLockTime is ignored
-        const bool locktime_enabled = std::any_of(psbtx.inputs.begin(), psbtx.inputs.end(), [](const PSBTInput& input) {
-            const uint32_t sequence_final = CTxIn::SEQUENCE_FINAL;
-            return input.sequence.value_or(sequence_final) != sequence_final;
+        const bool is_locktime_enabled = std::any_of(psbtx.inputs.begin(), psbtx.inputs.end(), [](const PSBTInput& input) {
+            return input.sequence.value_or(CTxIn::SEQUENCE_FINAL) != CTxIn::SEQUENCE_FINAL;
         });
-        const uint32_t psbt_locktime = psbtx.fallback_locktime.value_or(0);
-        if (locktime_enabled && psbt_locktime != 0) {
-            const bool is_time_locktime{psbt_locktime >= LOCKTIME_THRESHOLD};
-            if (max_locktime != 0 && (max_locktime >= LOCKTIME_THRESHOLD) != is_time_locktime) {
+        auto psbt_locktime = psbtx.fallback_locktime;
+        if (is_locktime_enabled && psbt_locktime.has_value()) {
+            const bool is_time_locktime{*psbt_locktime >= LOCKTIME_THRESHOLD};
+            if (max_locktime.has_value() && (*max_locktime >= LOCKTIME_THRESHOLD) != is_time_locktime) {
                 throw JSONRPCError(RPC_INVALID_PARAMETER, "Cannot join PSBTs with mixed height-based and time-based locktimes");
             }
-            max_locktime = std::max(max_locktime, psbt_locktime);
+            max_locktime = std::max(*max_locktime, *psbt_locktime);
         }
     }
 
     // Create a blank psbt where everything will be added
     CMutableTransaction tx;
     tx.version = best_version;
-    tx.nLockTime = max_locktime;
+    tx.nLockTime = max_locktime.value_or(0);
     PartiallySignedTransaction merged_psbt(tx, psbtxs.at(0).GetVersion());
 
     // Merge

Comment thread src/rpc/rawtransaction.cpp Resolved
Comment thread src/rpc/rawtransaction.cpp Resolved
Comment thread src/rpc/rawtransaction.cpp Resolved
Comment thread src/rpc/rawtransaction.cpp Resolved
Comment thread test/functional/rpc_psbt.py Resolved
nervana21 and others added 5 commits May 25, 2026 19:06
A merged PSBT should use the maximum nLockTime among PSBTs that
constrain it. A constraining PSBT has at least one input with
nSequence != SEQUENCE_FINAL and has a non-zero nLockTime. Reject joins
that mix height-based and time-based locktimes.

Document this in the RPC help.

Co-authored-by: rkrux <[email protected]>
Exercise max height/time locktime selection, `SEQUENCE_FINAL` and zero
locktime ignoring, and mixed locktime type rejection.
Join wallet PSBTs that spend distinct CLTV P2WSH UTXOs with different
nLockTime values. Confirm joinpsbts picks the higher locktime and that
the merged transaction passes testmempoolaccept once per-input witness
scripts are attached.

Co-authored-by: w0xlt <[email protected]>
@nervana21
nervana21 force-pushed the 20260416_locktime branch from 5c7a61a to db9c0df Compare May 25, 2026 18:46
@nervana21
nervana21 requested review from rkrux and w0xlt May 25, 2026 18:48
@nervana21

nervana21 commented May 25, 2026 •

Copy link
Copy Markdown
Contributor Author

I've taken all of the changes except the 1 case where specified. I've refactored and split the PR into more commits. I've added release notes. I've also simplified the make_locktime_psbt helper function. The logic and functionality remains the same compared to prior reviews.

@nervana21
nervana21 requested a review from Bicaru20 May 25, 2026 18:58

@w0xlt w0xlt 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.

ACK db9c0df

@frankomosh frankomosh 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.

tACK db9c0df. Applied manual mutation to check any coverage gaps. None found

logs

functional test - clean pass

2026-05-26T11:36:28.030635Z TestFramework (INFO): Test joinpsbts
2026-05-26T11:36:41.032546Z TestFramework (INFO): Tests successful

mutations

  • std::max → std::min: caught by assert_joined_locktime([psbt_150, psbt_200], expected_locktime=200)
  • Removed is_locktime_enabled gate: caught by assert_joined_locktime([psbt_200, psbt_250_seq_final], expected_locktime=200)
  • Removed mixed-type rejection: caught by assert_raises_rpc_error(-8, "Cannot join PSBTs with mixed height-based and time-based locktimes", ...)

fuzz coverage - rpc corpus (13,230 inputs)

1911|  4.53k|  is_locktime_enabled check
1915|    231|  if (is_locktime_enabled && psbt_locktime != 0)
1918|      7|  throw JSONRPCError — mixed-type rejection reached
1923|    151|  std::max(*max_locktime, psbt_locktime)
1931|    177|  tx.nLockTime = max_locktime.value_or(0)

All branches seem hit, as the existing corpus exercises the new logic, including the mixed-type rejection path, without any harness changes.

tested on Ubuntu 24.04

@achow101

Copy link
Copy Markdown
Member

Concept -0

In general, I'm not convinced that joinpsbts for PSBTv0 should be improved. It was introduced mostly as a hack, and joining PSBTv0s isn't really permitted by BIP 174. There was not much consideration for joining rules and the potential (in)validity of the resulting PSBT.

I think it would be better to make joinpsbts PSBTv2 only, and to work on supporting transaction construction with PSBTv2, rather than continuing to shoehorn PSBTv0 to do something it was not designed to do. PSBTv2 was created with transaction construction in mind, so more thought has been put into how fields interact with each other when constructing a PSBT.

@polespinasa

Copy link
Copy Markdown
Member

Concept~0

For the same reasons mentioned here: #35100 (comment)
Working towards deprecating joinpsbt for PSBTv0 and making it PSBTv2 only seems the right and logical direction.

@nervana21

Copy link
Copy Markdown
Contributor Author

Understood. Closing for now.

@nervana21 nervana21 closed this Jul 3, 2026
@nervana21
nervana21 deleted the 20260416_locktime branch August 17, 2026 02:26
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

10 participants