Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

stripping excess postage #662

Merged
merged 9 commits into from
Oct 17, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion src/subcommand/wallet/send.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,12 @@ impl Send {

let utxos = list_unspent(&options, &index)?.into_iter().collect();

let change = client
.call("getrawchangeaddress", &[])
.context("Could not get change addresses from wallet")?;

let unsigned_transaction =
TransactionBuilder::build_transaction(utxos, self.ordinal, self.address)?;
TransactionBuilder::build_transaction(utxos, self.ordinal, self.address, change)?;

let signed_tx = client
.sign_raw_transaction_with_wallet(&unsigned_transaction, None, None)?
Expand Down
148 changes: 146 additions & 2 deletions src/subcommand/wallet/transaction_builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ impl std::error::Error for Error {}

#[derive(Debug, PartialEq)]
pub(crate) struct TransactionBuilder {
change: Address,
inputs: Vec<OutPoint>,
ordinal: Ordinal,
outputs: Vec<(Address, Amount)>,
Expand All @@ -36,13 +37,18 @@ pub(crate) struct TransactionBuilder {
type Result<T> = std::result::Result<T, Error>;

impl TransactionBuilder {
const TARGET_POSTAGE: u64 = 10_000;
const MAX_POSTAGE: u64 = 2 * Self::TARGET_POSTAGE;

pub(crate) fn build_transaction(
ranges: BTreeMap<OutPoint, Vec<(u64, u64)>>,
ordinal: Ordinal,
recipient: Address,
change: Address,
) -> Result<Transaction> {
Self::new(ranges, ordinal, recipient)
Self::new(ranges, ordinal, recipient, change)
.select_ordinal()?
.strip_excess_postage()?
.deduct_fee()?
.build()
}
Expand All @@ -51,6 +57,7 @@ impl TransactionBuilder {
ranges: BTreeMap<OutPoint, Vec<(u64, u64)>>,
ordinal: Ordinal,
recipient: Address,
change: Address,
) -> Self {
Self {
utxos: ranges.keys().cloned().collect(),
Expand All @@ -59,6 +66,7 @@ impl TransactionBuilder {
outputs: Vec::new(),
ranges,
recipient,
change,
}
}

Expand All @@ -84,6 +92,32 @@ impl TransactionBuilder {
Ok(self)
}

fn strip_excess_postage(mut self) -> Result<Self> {
let ordinal_offset = self.calculate_ordinal_offset();
let output_total = self
.outputs
.iter()
.map(|(_address, amount)| *amount)
.sum::<Amount>();

assert_eq!(self.outputs.len(), 1, "invariant: only one output");

assert_eq!(
self.outputs[0].0, self.recipient,
"invariant: first output is recipient"
);

if output_total > Amount::from_sat(ordinal_offset + Self::MAX_POSTAGE) {
self.outputs[0].1 = Amount::from_sat(Self::TARGET_POSTAGE);
self.outputs.push((
self.change.clone(),
output_total - Amount::from_sat(ordinal_offset + Self::TARGET_POSTAGE),
));
}

Ok(self)
}

fn deduct_fee(mut self) -> Result<Self> {
let ordinal_offset = self.calculate_ordinal_offset();

Expand Down Expand Up @@ -188,6 +222,15 @@ impl TransactionBuilder {
}
assert!(found, "invariant: ordinal is found in outputs");

for output in &transaction.output {
if output.script_pubkey != self.change.script_pubkey() {
assert!(
output.value < Self::MAX_POSTAGE,
"invariant: excess postage is stripped"
);
}
}

Ok(transaction)
}

Expand Down Expand Up @@ -238,6 +281,9 @@ mod tests {
"tb1q6en7qjxgw4ev8xwx94pzdry6a6ky7wlfeqzunz"
.parse()
.unwrap(),
"tb1qjsv26lap3ffssj6hfy8mzn0lg5vte6a42j75ww"
.parse()
.unwrap(),
)
.select_ordinal()
.unwrap();
Expand Down Expand Up @@ -295,6 +341,9 @@ mod tests {
recipient: "tb1q6en7qjxgw4ev8xwx94pzdry6a6ky7wlfeqzunz"
.parse()
.unwrap(),
change: "tb1qjsv26lap3ffssj6hfy8mzn0lg5vte6a42j75ww"
.parse()
.unwrap(),
inputs: vec![
"1111111111111111111111111111111111111111111111111111111111111111:1"
.parse()
Expand Down Expand Up @@ -402,6 +451,9 @@ mod tests {
"tb1q6en7qjxgw4ev8xwx94pzdry6a6ky7wlfeqzunz"
.parse()
.unwrap(),
"tb1qjsv26lap3ffssj6hfy8mzn0lg5vte6a42j75ww"
.parse()
.unwrap(),
),
Ok(Transaction {
version: 1,
Expand All @@ -415,7 +467,7 @@ mod tests {
witness: Witness::new(),
},],
output: vec![TxOut {
value: 4836,
value: 5000 - 164,
script_pubkey: "tb1q6en7qjxgw4ev8xwx94pzdry6a6ky7wlfeqzunz"
.parse::<Address>()
.unwrap()
Expand All @@ -441,6 +493,9 @@ mod tests {
"tb1q6en7qjxgw4ev8xwx94pzdry6a6ky7wlfeqzunz"
.parse()
.unwrap(),
"tb1qjsv26lap3ffssj6hfy8mzn0lg5vte6a42j75ww"
.parse()
.unwrap(),
),
Err(Error::ConsumedByFee(Ordinal(14900)))
)
Expand All @@ -462,6 +517,9 @@ mod tests {
"tb1q6en7qjxgw4ev8xwx94pzdry6a6ky7wlfeqzunz"
.parse()
.unwrap(),
"tb1qjsv26lap3ffssj6hfy8mzn0lg5vte6a42j75ww"
.parse()
.unwrap(),
)
.build()
.ok();
Expand All @@ -483,6 +541,9 @@ mod tests {
"tb1q6en7qjxgw4ev8xwx94pzdry6a6ky7wlfeqzunz"
.parse()
.unwrap(),
"tb1qjsv26lap3ffssj6hfy8mzn0lg5vte6a42j75ww"
.parse()
.unwrap(),
)
.build()
.ok();
Expand All @@ -504,6 +565,9 @@ mod tests {
"tb1q6en7qjxgw4ev8xwx94pzdry6a6ky7wlfeqzunz"
.parse()
.unwrap(),
"tb1qjsv26lap3ffssj6hfy8mzn0lg5vte6a42j75ww"
.parse()
.unwrap(),
)
.select_ordinal()
.unwrap();
Expand Down Expand Up @@ -531,6 +595,9 @@ mod tests {
"tb1q6en7qjxgw4ev8xwx94pzdry6a6ky7wlfeqzunz"
.parse()
.unwrap(),
"tb1qjsv26lap3ffssj6hfy8mzn0lg5vte6a42j75ww"
.parse()
.unwrap(),
)
.select_ordinal()
.unwrap();
Expand All @@ -539,4 +606,81 @@ mod tests {

builder.build().ok();
}

#[test]
fn excess_postage_is_stripped() {
let utxos = vec![(
"1111111111111111111111111111111111111111111111111111111111111111:1"
.parse()
.unwrap(),
vec![(0, 1_000_000)],
)];

pretty_assert_eq!(
TransactionBuilder::build_transaction(
utxos.into_iter().collect(),
Ordinal(0),
"tb1q6en7qjxgw4ev8xwx94pzdry6a6ky7wlfeqzunz"
.parse()
.unwrap(),
"tb1qjsv26lap3ffssj6hfy8mzn0lg5vte6a42j75ww"
.parse()
.unwrap(),
),
Ok(Transaction {
version: 1,
lock_time: PackedLockTime::ZERO,
input: vec![TxIn {
previous_output: "1111111111111111111111111111111111111111111111111111111111111111:1"
.parse()
.unwrap(),
script_sig: Script::new(),
sequence: Sequence::ENABLE_RBF_NO_LOCKTIME,
witness: Witness::new(),
},],
output: vec![
TxOut {
value: TransactionBuilder::TARGET_POSTAGE,
script_pubkey: "tb1q6en7qjxgw4ev8xwx94pzdry6a6ky7wlfeqzunz"
.parse::<Address>()
.unwrap()
.script_pubkey(),
},
TxOut {
value: 1_000_000 - TransactionBuilder::TARGET_POSTAGE - 226,
script_pubkey: "tb1qjsv26lap3ffssj6hfy8mzn0lg5vte6a42j75ww"
.parse::<Address>()
.unwrap()
.script_pubkey(),
}
],
})
)
}

#[test]
#[should_panic(expected = "invariant: excess postage is stripped")]
fn invariant_excess_postage_is_stripped() {
let utxos = vec![(
"1111111111111111111111111111111111111111111111111111111111111111:1"
.parse()
.unwrap(),
vec![(0, 1_000_000)],
)];

TransactionBuilder::new(
utxos.into_iter().collect(),
Ordinal(0),
"tb1q6en7qjxgw4ev8xwx94pzdry6a6ky7wlfeqzunz"
.parse()
.unwrap(),
"tb1qjsv26lap3ffssj6hfy8mzn0lg5vte6a42j75ww"
.parse()
.unwrap(),
)
.select_ordinal()
.unwrap()
.build()
.unwrap();
}
}
3 changes: 3 additions & 0 deletions test-bitcoincore-rpc/src/api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -66,4 +66,7 @@ pub trait Api {
include_unsafe: Option<bool>,
query_options: Option<String>,
) -> Result<Vec<ListUnspentResultEntry>, jsonrpc_core::Error>;

#[rpc(name = "getrawchangeaddress")]
fn get_raw_change_address(&self) -> Result<bitcoin::Address, jsonrpc_core::Error>;
}
8 changes: 8 additions & 0 deletions test-bitcoincore-rpc/src/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -299,4 +299,12 @@ impl Api for Server {
.collect(),
)
}

fn get_raw_change_address(&self) -> Result<bitcoin::Address, jsonrpc_core::Error> {
Ok(
"tb1qjsv26lap3ffssj6hfy8mzn0lg5vte6a42j75ww"
.parse()
.unwrap(),
)
}
}