Skip to content
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
110 changes: 105 additions & 5 deletions wallet/types/src/generic_transaction.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 _;

Expand All @@ -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[..]) {
Expand All @@ -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)]
Expand All @@ -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,
},
Expand Down Expand Up @@ -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::<Option<InputWitness>>::new(),
_ => vec![Option::<InputWitness>::None],
};
let input_utxos = match skewed_vector {
SkewedVector::InputUtxos => vec![Option::<TxOutput>::None; 2],
_ => vec![Option::<TxOutput>::None],
};
let destinations = match skewed_vector {
SkewedVector::Destinations => vec![Option::<Destination>::None; 2],
_ => vec![Option::<Destination>::None],
};
let htlc_secrets = match skewed_vector {
SkewedVector::HtlcSecrets => vec![Option::<HtlcSecret>::None; 2],
_ => vec![Option::<HtlcSecret>::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,
}
}
4 changes: 2 additions & 2 deletions wallet/wallet-rpc-lib/src/rpc/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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),
Expand Down Expand Up @@ -1162,7 +1162,7 @@ where
raw_tx: RpcHexString,
) -> WRpcResult<InspectTransaction, N> {
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),
Expand Down
9 changes: 5 additions & 4 deletions wallet/wallet-rpc-lib/src/rpc/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -124,8 +125,8 @@ pub enum RpcError<N: NodeInterface> {
#[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"
Expand Down
Loading