Replace sorting with slice pattern matching

Sorting `psbt.output` by `witness_script` is at times pointless
because it might be set to `None`. To be more robust, we pattern
match against the produced transaction.
This commit is contained in:
Thomas Eizinger 2021-07-06 18:28:21 +10:00
parent 625ff4868a
commit 8b59ac26ba
No known key found for this signature in database
GPG Key ID: 651AC83A6C6C8B96

View File

@ -16,7 +16,6 @@ use reqwest::Url;
use rust_decimal::prelude::*; use rust_decimal::prelude::*;
use rust_decimal::Decimal; use rust_decimal::Decimal;
use rust_decimal_macros::dec; use rust_decimal_macros::dec;
use std::cmp::Ordering;
use std::collections::{BTreeMap, HashMap}; use std::collections::{BTreeMap, HashMap};
use std::convert::TryFrom; use std::convert::TryFrom;
use std::fmt; use std::fmt;
@ -326,22 +325,20 @@ where
let (psbt, _details) = tx_builder.finish()?; let (psbt, _details) = tx_builder.finish()?;
let mut psbt: PartiallySignedTransaction = psbt; let mut psbt: PartiallySignedTransaction = psbt;
// When subscribing to transactions we depend on the relevant script being at match psbt.global.unsigned_tx.output.as_mut_slice() {
// output index 0, thus we ensure the relevant output to be at index `0`. // our primary output is the 2nd one? reverse the vectors
psbt.outputs.sort_by(|a, _| { [_, second_txout] if second_txout.script_pubkey == script => {
if a.witness_script.as_ref() == Some(&script) { psbt.outputs.reverse();
Ordering::Less psbt.global.unsigned_tx.output.reverse();
} else {
Ordering::Greater
} }
}); [first_txout, _] if first_txout.script_pubkey == script => {
psbt.global.unsigned_tx.output.sort_by(|a, _| { // no need to do anything
if a.script_pubkey == script { }
Ordering::Less [_] => {
} else { // single output, no need do anything
Ordering::Greater }
_ => bail!("Unexpected transaction layout"),
} }
});
Ok(psbt) Ok(psbt)
} }