From 5c3a2f839ca47eea859a3726556940afd580be96 Mon Sep 17 00:00:00 2001 From: Oliver Anyanwu Date: Fri, 10 Jul 2026 11:18:46 +0100 Subject: [PATCH 1/4] Validate PartiallySignedTransaction after decoding Wallet RPC methods and CLI commands accept a hex-encoded PartiallySignedTransaction and decode it with SCALE, which bypasses the invariants that PartiallySignedTransaction::new enforces. A malformed but still decodable transaction could then make the wallet panic, e.g. on a witness/input count mismatch. Call ensure_consistency right after decoding in GenericTransaction::decode_from_untagged_bytes, the shared decode path used by account_sign_raw_transaction and transaction_inspect, so such input is rejected with a proper error instead. The Basic level is used so that transactions that are still being assembled are not rejected. --- wallet/types/src/generic_transaction.rs | 70 +++++++++++++++++++++++-- 1 file changed, 65 insertions(+), 5 deletions(-) diff --git a/wallet/types/src/generic_transaction.rs b/wallet/types/src/generic_transaction.rs index 013fb41473..524cd47e30 100644 --- a/wallet/types/src/generic_transaction.rs +++ b/wallet/types/src/generic_transaction.rs @@ -14,7 +14,11 @@ // limitations under the License. use common::chain::{ - SignedTransaction, Transaction, partially_signed_transaction::PartiallySignedTransaction, + SignedTransaction, Transaction, + partially_signed_transaction::{ + PartiallySignedTransaction, PartiallySignedTransactionConsistencyCheck, + PartiallySignedTransactionError, + }, }; use serialization::DecodeAll as _; @@ -34,8 +38,18 @@ impl GenericTransaction { // has an extra field, it's always bigger than the latter. By using `decode_all` we // make sure that these 2 can't be confused with each other either. // I.e. the order in which the decoding attempts are performed here doesn't matter. - if let Ok(tx) = PartiallySignedTransaction::decode_all(&mut &bytes[..]) { - Ok(Self::Partial(tx)) + if let Ok(ptx) = PartiallySignedTransaction::decode_all(&mut &bytes[..]) { + // Decoding bypasses the invariants that `PartiallySignedTransaction::new` + // enforces, so a malformed (but still decodable) transaction could later make + // the wallet panic, e.g. on a witness/input count mismatch. Reject it here. + // + // `Basic` only checks the structural invariants that prevent such panics; the + // stricter additional-info checks are intentionally not used here so that a + // transaction that is still being assembled (and may not carry all of its input + // utxos or additional info yet) is not rejected. + ptx.ensure_consistency(PartiallySignedTransactionConsistencyCheck::Basic) + .map_err(GenericTransactionError::InconsistentPartiallySignedTransaction)?; + Ok(Self::Partial(ptx)) } else if let Ok(stx) = SignedTransaction::decode_all(&mut &bytes[..]) { Ok(Self::Signed(stx)) } else if let Ok(tx) = Transaction::decode_all(&mut &bytes[..]) { @@ -50,6 +64,9 @@ impl GenericTransaction { pub enum GenericTransactionError { #[error("The provided bytes are not an encoded transaction")] CannotDecodeFromUntaggedBytes, + + #[error("Inconsistent partially signed transaction: {0}")] + InconsistentPartiallySignedTransaction(PartiallySignedTransactionError), } #[cfg(test)] @@ -58,10 +75,12 @@ mod tests { use common::{ chain::{ - OutPointSourceId, TxInput, TxOutput, UtxoOutPoint, + Destination, OutPointSourceId, TxInput, TxOutput, UtxoOutPoint, + htlc::HtlcSecret, output_value::OutputValue, partially_signed_transaction::{ - PartiallySignedTransactionConsistencyCheck, TxAdditionalInfo, + PartiallySignedTransactionConsistencyCheck, PartiallySignedTransactionError, + TxAdditionalInfo, }, signature::inputsig::InputWitness, }, @@ -126,4 +145,45 @@ mod tests { GenericTransaction::decode_from_untagged_bytes("invalid bytes".as_bytes()).unwrap_err(); assert_eq!(err, GenericTransactionError::CannotDecodeFromUntaggedBytes); } + + // A PartiallySignedTransaction that is decodable but violates the invariants that + // `new` normally enforces must be rejected, otherwise the wallet could later panic + // on it. Such a transaction can't be built through the public constructor, so its + // bytes are assembled by hand here to mimic malformed external input. + #[rstest] + #[trace] + #[case(Seed::from_entropy())] + fn test_decode_rejects_inconsistent_partially_signed_transaction(#[case] seed: Seed) { + let mut rng = make_seedable_rng(seed); + + let tx = Transaction::new( + rng.random(), + vec![TxInput::Utxo(UtxoOutPoint::new( + OutPointSourceId::Transaction(Id::random_using(&mut rng)), + rng.random(), + ))], + vec![TxOutput::Burn(OutputValue::Coin(Amount::from_atoms(rng.random())))], + ) + .unwrap(); + + // Encode a PartiallySignedTransactionV1 field by field, but give it an empty + // `witnesses` vector while the transaction has one input, so the witness count + // no longer matches the input count. + let mut bytes = Vec::new(); + 64u8.encode_to(&mut bytes); // PartiallySignedTransaction::V1 discriminant (codec index 64) + tx.encode_to(&mut bytes); + Vec::>::new().encode_to(&mut bytes); // witnesses + vec![Option::::None].encode_to(&mut bytes); // input_utxos + vec![Option::::None].encode_to(&mut bytes); // destinations + vec![Option::::None].encode_to(&mut bytes); // htlc_secrets + TxAdditionalInfo::new().encode_to(&mut bytes); + + let err = GenericTransaction::decode_from_untagged_bytes(&bytes).unwrap_err(); + assert_eq!( + err, + GenericTransactionError::InconsistentPartiallySignedTransaction( + PartiallySignedTransactionError::InvalidWitnessCount + ) + ); + } } From fbf262e0b83a051d4b684856f29cfd0ebdc623e3 Mon Sep 17 00:00:00 2001 From: Oliver Anyanwu Date: Fri, 28 Aug 2026 14:34:30 +0100 Subject: [PATCH 2/4] Surface the decoding error and correct the consistency comment Both callers of decode_from_untagged_bytes mapped the error to a unit InvalidRawTransaction variant, so the reason a transaction was rejected never reached the user and an inconsistent transaction looked the same as malformed hex. Give the variant the inner error instead, so the message says which count did not match. Also correct the comment above the Basic check. Basic does verify that the input utxo count matches the input count, the entries are just allowed to be None, so only the additional info part of the original wording was right. Add #[source] to the new error field so Error::source() returns the inner error rather than None. --- wallet/types/src/generic_transaction.rs | 14 +++++++++----- wallet/wallet-rpc-lib/src/rpc/mod.rs | 4 ++-- wallet/wallet-rpc-lib/src/rpc/types.rs | 9 +++++---- 3 files changed, 16 insertions(+), 11 deletions(-) diff --git a/wallet/types/src/generic_transaction.rs b/wallet/types/src/generic_transaction.rs index 524cd47e30..d5d0e7b370 100644 --- a/wallet/types/src/generic_transaction.rs +++ b/wallet/types/src/generic_transaction.rs @@ -43,10 +43,14 @@ impl GenericTransaction { // enforces, so a malformed (but still decodable) transaction could later make // the wallet panic, e.g. on a witness/input count mismatch. Reject it here. // - // `Basic` only checks the structural invariants that prevent such panics; the - // stricter additional-info checks are intentionally not used here so that a - // transaction that is still being assembled (and may not carry all of its input - // utxos or additional info yet) is not rejected. + // `Basic` only checks the structural invariants that prevent such panics, namely + // that the witness, input utxo, destination and htlc secret counts all match the + // input count. The individual entries are still allowed to be `None`, which is what + // a transaction that is only partially filled in looks like. + // + // The stricter additional-info checks are intentionally not used here, so that a + // transaction that is still being assembled and does not carry its additional info + // yet is not rejected. ptx.ensure_consistency(PartiallySignedTransactionConsistencyCheck::Basic) .map_err(GenericTransactionError::InconsistentPartiallySignedTransaction)?; Ok(Self::Partial(ptx)) @@ -66,7 +70,7 @@ pub enum GenericTransactionError { CannotDecodeFromUntaggedBytes, #[error("Inconsistent partially signed transaction: {0}")] - InconsistentPartiallySignedTransaction(PartiallySignedTransactionError), + InconsistentPartiallySignedTransaction(#[source] PartiallySignedTransactionError), } #[cfg(test)] diff --git a/wallet/wallet-rpc-lib/src/rpc/mod.rs b/wallet/wallet-rpc-lib/src/rpc/mod.rs index 3f28c91f20..464e2c77dd 100644 --- a/wallet/wallet-rpc-lib/src/rpc/mod.rs +++ b/wallet/wallet-rpc-lib/src/rpc/mod.rs @@ -911,7 +911,7 @@ where N, > { let tx = GenericTransaction::decode_from_untagged_bytes(raw_tx.as_bytes()) - .map_err(|_| RpcError::InvalidRawTransaction)?; + .map_err(RpcError::InvalidRawTransaction)?; let tx_to_sign = match tx { GenericTransaction::Tx(tx) => TransactionToSign::Tx(tx), GenericTransaction::Partial(tx) => TransactionToSign::Partial(tx), @@ -1116,7 +1116,7 @@ where raw_tx: RpcHexString, ) -> WRpcResult { let tx = GenericTransaction::decode_from_untagged_bytes(raw_tx.as_bytes()) - .map_err(|_| RpcError::InvalidRawTransaction)?; + .map_err(RpcError::InvalidRawTransaction)?; let tx_to_inspect = match tx { GenericTransaction::Tx(tx) => TransactionToInspect::Tx(tx), GenericTransaction::Partial(tx) => TransactionToInspect::Partial(tx), diff --git a/wallet/wallet-rpc-lib/src/rpc/types.rs b/wallet/wallet-rpc-lib/src/rpc/types.rs index 380f0a5cc0..e6f16e88bd 100644 --- a/wallet/wallet-rpc-lib/src/rpc/types.rs +++ b/wallet/wallet-rpc-lib/src/rpc/types.rs @@ -62,8 +62,9 @@ pub use wallet_controller::types::{ pub use wallet_controller::{ControllerConfig, NodeInterface}; use wallet_controller::{UtxoState, UtxoType, types::WalletTypeArgs}; use wallet_types::{ - ImportOrCreate, KeyPurpose, partially_signed_transaction::PartiallySignedTransaction, - seed_phrase::StoreSeedPhrase, signature_status::SignatureStatus, + ImportOrCreate, KeyPurpose, generic_transaction::GenericTransactionError, + partially_signed_transaction::PartiallySignedTransaction, seed_phrase::StoreSeedPhrase, + signature_status::SignatureStatus, }; use crate::service::SubmitError; @@ -124,8 +125,8 @@ pub enum RpcError { #[error("{0}")] SubmitError(#[from] SubmitError), - #[error("Invalid raw transaction")] - InvalidRawTransaction, + #[error("Invalid raw transaction: {0}")] + InvalidRawTransaction(#[from] GenericTransactionError), #[error( "Expecting an unsigned or partially signed transaction, but a fully signed one was passed" From 72133ca255697dbe98f338613b6a7f31b3328787 Mon Sep 17 00:00:00 2001 From: nullPointerEnjoyer Date: Thu, 19 Nov 2026 15:33:39 +0100 Subject: [PATCH 3/4] test(wallet): cover all four PSBT count invariants in decode --- CHANGELOG.md | 6 +++ wallet/types/src/generic_transaction.rs | 60 ++++++++++++++++++++----- 2 files changed, 54 insertions(+), 12 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 4e3a979db9..16991d9dca 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -29,6 +29,12 @@ The format is loosely based on [Keep a Changelog](https://keepachangelog.com/en/ previous `2024-01-12 12:54:52 UTC`. - Wallet: + - decoded partially signed transactions (e.g. passed to the `signrawtransaction` + and `transactioninspect` RPC calls) are now checked for consistency right after + decoding, so a PSBT whose per-input vectors do not match the transaction shape + is rejected with a detailed `Invalid raw transaction` error instead of failing + later or panicking during signing. + - coin selection leaves out redundant UTXOs: - Wallet: - coin selection leaves out redundant UTXOs: the selection algorithms stop as soon as the target is met, and among equally economical solutions the one spending fewer inputs is preferred, so default sends spend fewer UTXOs and produce smaller diff --git a/wallet/types/src/generic_transaction.rs b/wallet/types/src/generic_transaction.rs index d5d0e7b370..51f7ab5639 100644 --- a/wallet/types/src/generic_transaction.rs +++ b/wallet/types/src/generic_transaction.rs @@ -156,8 +156,14 @@ mod tests { // bytes are assembled by hand here to mimic malformed external input. #[rstest] #[trace] - #[case(Seed::from_entropy())] - fn test_decode_rejects_inconsistent_partially_signed_transaction(#[case] seed: Seed) { + #[case(Seed::from_entropy(), SkewedVector::Witnesses)] + #[case(Seed::from_entropy(), SkewedVector::InputUtxos)] + #[case(Seed::from_entropy(), SkewedVector::Destinations)] + #[case(Seed::from_entropy(), SkewedVector::HtlcSecrets)] + fn test_decode_rejects_inconsistent_partially_signed_transaction( + #[case] seed: Seed, + #[case] skewed_vector: SkewedVector, + ) { let mut rng = make_seedable_rng(seed); let tx = Transaction::new( @@ -170,24 +176,54 @@ mod tests { ) .unwrap(); - // Encode a PartiallySignedTransactionV1 field by field, but give it an empty - // `witnesses` vector while the transaction has one input, so the witness count - // no longer matches the input count. + // Encode a PartiallySignedTransactionV1 field by field, giving one of the four + // per-input vectors a length that no longer matches the single input (an empty + // witnesses vector, or a doubled one for the rest), so the corresponding count + // invariant is violated. + let witness_bytes = match skewed_vector { + SkewedVector::Witnesses => Vec::>::new(), + _ => vec![Option::::None], + }; + let input_utxos = match skewed_vector { + SkewedVector::InputUtxos => vec![Option::::None; 2], + _ => vec![Option::::None], + }; + let destinations = match skewed_vector { + SkewedVector::Destinations => vec![Option::::None; 2], + _ => vec![Option::::None], + }; + let htlc_secrets = match skewed_vector { + SkewedVector::HtlcSecrets => vec![Option::::None; 2], + _ => vec![Option::::None], + }; + let mut bytes = Vec::new(); 64u8.encode_to(&mut bytes); // PartiallySignedTransaction::V1 discriminant (codec index 64) tx.encode_to(&mut bytes); - Vec::>::new().encode_to(&mut bytes); // witnesses - vec![Option::::None].encode_to(&mut bytes); // input_utxos - vec![Option::::None].encode_to(&mut bytes); // destinations - vec![Option::::None].encode_to(&mut bytes); // htlc_secrets + witness_bytes.encode_to(&mut bytes); // witnesses + input_utxos.encode_to(&mut bytes); // input_utxos + destinations.encode_to(&mut bytes); // destinations + htlc_secrets.encode_to(&mut bytes); // htlc_secrets TxAdditionalInfo::new().encode_to(&mut bytes); + let expected_error = match skewed_vector { + SkewedVector::Witnesses => PartiallySignedTransactionError::InvalidWitnessCount, + SkewedVector::InputUtxos => PartiallySignedTransactionError::InvalidInputUtxosCount, + SkewedVector::Destinations => PartiallySignedTransactionError::InvalidDestinationsCount, + SkewedVector::HtlcSecrets => PartiallySignedTransactionError::InvalidHtlcSecretsCount, + }; let err = GenericTransaction::decode_from_untagged_bytes(&bytes).unwrap_err(); assert_eq!( err, - GenericTransactionError::InconsistentPartiallySignedTransaction( - PartiallySignedTransactionError::InvalidWitnessCount - ) + GenericTransactionError::InconsistentPartiallySignedTransaction(expected_error) ); } + + #[derive(Clone, Copy, Debug)] + enum SkewedVector { + Witnesses, + InputUtxos, + Destinations, + HtlcSecrets, + } } From 722157cf392b4949225b4be3f4f1a431eae9bad9 Mon Sep 17 00:00:00 2001 From: nullPointerEnjoyer Date: Thu, 19 Nov 2026 15:40:46 +0100 Subject: [PATCH 4/4] fix: address review findings (changelog cleanup) --- CHANGELOG.md | 1 - wallet/types/src/generic_transaction.rs | 4 ++-- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 16991d9dca..b94bb2336e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -34,7 +34,6 @@ The format is loosely based on [Keep a Changelog](https://keepachangelog.com/en/ decoding, so a PSBT whose per-input vectors do not match the transaction shape is rejected with a detailed `Invalid raw transaction` error instead of failing later or panicking during signing. - - coin selection leaves out redundant UTXOs: - Wallet: - coin selection leaves out redundant UTXOs: the selection algorithms stop as soon as the target is met, and among equally economical solutions the one spending fewer inputs is preferred, so default sends spend fewer UTXOs and produce smaller diff --git a/wallet/types/src/generic_transaction.rs b/wallet/types/src/generic_transaction.rs index 51f7ab5639..2b74761819 100644 --- a/wallet/types/src/generic_transaction.rs +++ b/wallet/types/src/generic_transaction.rs @@ -180,7 +180,7 @@ mod tests { // per-input vectors a length that no longer matches the single input (an empty // witnesses vector, or a doubled one for the rest), so the corresponding count // invariant is violated. - let witness_bytes = match skewed_vector { + let witnesses = match skewed_vector { SkewedVector::Witnesses => Vec::>::new(), _ => vec![Option::::None], }; @@ -200,7 +200,7 @@ mod tests { let mut bytes = Vec::new(); 64u8.encode_to(&mut bytes); // PartiallySignedTransaction::V1 discriminant (codec index 64) tx.encode_to(&mut bytes); - witness_bytes.encode_to(&mut bytes); // witnesses + witnesses.encode_to(&mut bytes); // witnesses input_utxos.encode_to(&mut bytes); // input_utxos destinations.encode_to(&mut bytes); // destinations htlc_secrets.encode_to(&mut bytes); // htlc_secrets