diff --git a/CHANGELOG.md b/CHANGELOG.md index 85f351bffe..a1d63b9548 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -36,6 +36,11 @@ 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: 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 013fb41473..2b74761819 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,22 @@ 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, 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)) } 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 +68,9 @@ impl GenericTransaction { pub enum GenericTransactionError { #[error("The provided bytes are not an encoded transaction")] CannotDecodeFromUntaggedBytes, + + #[error("Inconsistent partially signed transaction: {0}")] + InconsistentPartiallySignedTransaction(#[source] PartiallySignedTransactionError), } #[cfg(test)] @@ -58,10 +79,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 +149,81 @@ 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(), 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( + 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, 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 witnesses = 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); + 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 + 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(expected_error) + ); + } + + #[derive(Clone, Copy, Debug)] + enum SkewedVector { + Witnesses, + InputUtxos, + Destinations, + HtlcSecrets, + } } diff --git a/wallet/wallet-rpc-lib/src/rpc/mod.rs b/wallet/wallet-rpc-lib/src/rpc/mod.rs index 60044761fe..4556de0e42 100644 --- a/wallet/wallet-rpc-lib/src/rpc/mod.rs +++ b/wallet/wallet-rpc-lib/src/rpc/mod.rs @@ -957,7 +957,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), @@ -1162,7 +1162,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 95cba9fc4e..9c9a110320 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"