torvyon-core 0.1.2

Keys, addresses, post-quantum signing and transaction building for the Torvyon blockchain
Documentation
use super::{Input, OutPoint, Output, ScriptPubKey, UnsignedTransaction, MAX_DATA_SIZE, SEQUENCE_FINAL};
use crate::{Address, Amount, Error, Network, Result};

/// Most inputs one payment may spend, keeping transactions small enough for
/// proxies and relays. Larger balances must be consolidated first.
pub const MAX_INPUTS: usize = 500;

/// A spendable output, as returned by the node's UTXO API. Pass only
/// outputs the node reports as spendable.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Utxo {
    /// Where it is.
    pub outpoint: OutPoint,
    /// Value in nibbles.
    pub value: u64,
    /// Its locking script.
    pub script_pub_key: ScriptPubKey,
}

/// A payment to build.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Payment {
    /// Recipient.
    pub to: Address,
    /// Amount sent to the recipient.
    pub amount: Amount,
    /// Fee paid to the miner (inputs − outputs).
    pub fee: Amount,
    /// Optional data payload (max 512 bytes).
    pub data: Vec<u8>,
}

/// Builds an unsigned p2pkh payment from `from`'s UTXOs.
///
/// Coin selection is largest-first; any remainder above amount + fee goes
/// back to `from` as a change output.
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)
}

/// Builds an unsigned p2pkh payment for a specific network.
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(),
    })
}