use super::{Input, OutPoint, Output, ScriptPubKey, UnsignedTransaction, MAX_DATA_SIZE, SEQUENCE_FINAL};
use crate::{Address, Amount, Error, Network, Result};
pub const MAX_INPUTS: usize = 500;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Utxo {
pub outpoint: OutPoint,
pub value: u64,
pub script_pub_key: ScriptPubKey,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Payment {
pub to: Address,
pub amount: Amount,
pub fee: Amount,
pub data: Vec<u8>,
}
pub fn build_payment(
chain_id: &str,
from: &Address,
utxos: &[Utxo],
payment: &Payment,
) -> Result<UnsignedTransaction> {
build_payment_for_network(Network::Mainnet, chain_id, from, utxos, payment)
}
pub fn build_payment_for_network(
network: Network,
chain_id: &str,
from: &Address,
utxos: &[Utxo],
payment: &Payment,
) -> Result<UnsignedTransaction> {
if payment.amount == Amount::ZERO {
return Err(Error::ZeroValue(0));
}
if payment.data.len() > MAX_DATA_SIZE {
return Err(Error::DataTooLarge(payment.data.len()));
}
let target = payment.amount.checked_add(payment.fee)?.nibbles();
let mut candidates: Vec<&Utxo> = utxos
.iter()
.filter(|u| u.script_pub_key.is_p2pkh_to(from))
.collect();
candidates.sort_by_key(|u| std::cmp::Reverse(u.value));
let mut selected = Vec::new();
let mut total: u64 = 0;
for utxo in candidates {
selected.push(utxo);
total = total.checked_add(utxo.value).ok_or(Error::AmountOverflow)?;
if total >= target || selected.len() >= MAX_INPUTS {
break;
}
}
if total < target {
return Err(if selected.len() >= MAX_INPUTS {
Error::TooManyInputs(MAX_INPUTS)
} else {
Error::InsufficientFunds {
need: target,
have: total,
}
});
}
let inputs = selected
.iter()
.map(|u| Input {
previous_outpoint: u.outpoint.clone(),
sequence: SEQUENCE_FINAL,
witness: None,
})
.collect();
let mut outputs = vec![Output {
value: payment.amount.nibbles(),
script_pub_key: Some(ScriptPubKey::p2pkh(&payment.to)),
condition: Vec::new(),
}];
let change = total - target;
if change > 0 {
outputs.push(Output {
value: change,
script_pub_key: Some(ScriptPubKey::p2pkh(from)),
condition: Vec::new(),
});
}
Ok(UnsignedTransaction {
network,
chain_id: chain_id.to_owned(),
inputs,
outputs,
fee: payment.fee.nibbles(),
lock_time: 0,
data: payment.data.clone(),
})
}