Skip to main content

smplx_sdk_test/transaction/
final_transaction.rs

1use std::collections::HashMap;
2
3use bitcoin_hashes::sha256;
4
5use simplicityhl::elements::pset::{Input, PartiallySignedTransaction};
6use simplicityhl::elements::{
7    AssetId, LockTime, Sequence, TxOutSecrets,
8    confidential::{AssetBlindingFactor, ValueBlindingFactor},
9};
10
11use crate::provider::SimplicityNetwork;
12use crate::utils;
13
14use super::change_output::ChangeOutput;
15use super::partial_input::{IssuanceInput, PartialInput, ProgramInput, RequiredSignature};
16use super::partial_output::PartialOutput;
17
18/// Constant is defined for fee calculation on transaction sending.
19pub const WITNESS_SCALE_FACTOR: usize = 4;
20
21/// A structure representing the details of token issuance and related metadata.
22#[derive(Debug, Clone)]
23pub struct IssuanceDetails {
24    /// The unique `AssetId` generated from the provided entropy, representing the issued tokens struct.
25    pub asset_id: AssetId,
26    /// The `AssetId` corresponding to the reissuance (inflation) token, used for minting new tokens.
27    pub inflation_asset_id: AssetId,
28    /// The entropy value (`sha256::Midstate`) that was used to derive both the `asset_id` and `inflation_asset_id`.
29    pub asset_entropy: sha256::Midstate,
30}
31
32/// Represents the final input structure put into a `FinalTransaction` for processing.
33#[derive(Clone)]
34pub struct FinalInput {
35    /// Holds the base input data required for the operation.
36    pub partial_input: PartialInput,
37    /// Holds program inputs, which are used for program witness finalization.
38    pub program_input: Option<ProgramInput>,
39    /// Contains optional issuance-related information.
40    pub issuance_input: Option<IssuanceInput>,
41    /// Required signature for finalizing the transaction.
42    pub required_sig: RequiredSignature,
43}
44
45impl FinalInput {
46    /// Creates a new instance of the type with the specified `partial_input` and `required_sig`.
47    #[must_use]
48    pub fn new(partial_input: PartialInput, required_sig: RequiredSignature) -> Self {
49        Self {
50            partial_input,
51            required_sig,
52            program_input: None,
53            issuance_input: None,
54        }
55    }
56
57    /// Sets the `program_input` field with the given `ProgramInput` and returns the modified `FinalInput`.
58    #[must_use]
59    pub fn with_program(mut self, program_input: ProgramInput) -> Self {
60        self.program_input = Some(program_input);
61
62        self
63    }
64
65    /// Sets the `issuance_input` field of the current instance and returns the updated `FinalInput`.
66    #[must_use]
67    pub fn with_issuance(mut self, issuance_input: IssuanceInput) -> Self {
68        self.issuance_input = Some(issuance_input);
69
70        self
71    }
72
73    /// Retrieves the issuance details associated with the current instance.
74    ///
75    /// # Errors
76    ///
77    /// This method does not explicitly return errors but returns `None` if no issuance
78    /// input is available.
79    #[must_use]
80    pub fn get_issuance_details(&self) -> Option<IssuanceDetails> {
81        match &self.issuance_input {
82            Some(issuance_input) => {
83                let asset_entropy = match issuance_input {
84                    IssuanceInput::Issuance { asset_entropy, .. } => {
85                        utils::asset_entropy(&self.partial_input.outpoint(), *asset_entropy)
86                    }
87                    IssuanceInput::Reissuance { asset_entropy, .. } => {
88                        sha256::Midstate::from_byte_array(*asset_entropy)
89                    }
90                };
91
92                let asset_id = AssetId::from_entropy(asset_entropy);
93                let inflation_asset_id = AssetId::reissuance_token_from_entropy(asset_entropy, false);
94
95                Some(IssuanceDetails {
96                    asset_id,
97                    inflation_asset_id,
98                    asset_entropy,
99                })
100            }
101            None => None,
102        }
103    }
104
105    /// Converts the current object into an `Input` representation, including any
106    /// issuance input and partial input details.
107    ///
108    /// # Panics
109    ///
110    /// This function will panic if the `issuance_input` is of type `Reissuance`
111    /// and the `partial_input.secrets` field is `None` or does not contain the necessary
112    /// confidential information. Specifically, a panic occurs when attempting to unwrap the `asset_bf` value.
113    #[must_use]
114    pub fn to_input(&self) -> Input {
115        let mut pst_input = self.partial_input.to_input();
116
117        // populate the input manually since `input.merge` is private
118        if let Some(issuance_input) = &self.issuance_input {
119            let issue = issuance_input.to_input();
120
121            pst_input.issuance_value_amount = issue.issuance_value_amount;
122            pst_input.issuance_asset_entropy = issue.issuance_asset_entropy;
123            pst_input.issuance_inflation_keys = issue.issuance_inflation_keys;
124            pst_input.blinded_issuance = issue.blinded_issuance;
125
126            if matches!(issuance_input, IssuanceInput::Reissuance { .. }) {
127                let issuance_blinding_nonce = self
128                    .partial_input
129                    .secrets
130                    .expect("Reissuance input must be confidential")
131                    .asset_bf
132                    .into_inner();
133
134                pst_input.issuance_blinding_nonce = Some(issuance_blinding_nonce);
135            }
136        }
137
138        pst_input
139    }
140}
141
142/// A struct representing a final (but not yet signed) transaction.
143#[derive(Clone)]
144pub struct FinalTransaction {
145    inputs: Vec<FinalInput>,
146    outputs: Vec<PartialOutput>,
147    change: Option<ChangeOutput>,
148    sequence: Sequence,
149    locktime: LockTime,
150}
151
152impl FinalTransaction {
153    /// Creates a new instance of the final transaction with default values.
154    #[must_use]
155    #[allow(clippy::new_without_default)]
156    pub fn new() -> Self {
157        Self {
158            inputs: Vec::new(),
159            outputs: Vec::new(),
160            change: None,
161            sequence: Sequence::default(),
162            locktime: LockTime::ZERO,
163        }
164    }
165    /// Sets a specific `Sequence` for the transaction.
166    ///
167    /// Injects this value into the inputs that don't declare their own sequence.
168    pub fn set_sequence(&mut self, sequence: Sequence) {
169        self.sequence = sequence;
170    }
171
172    /// Sets a specific `LockTime` for the transaction.
173    ///
174    /// Injects this value into the inputs that don't declare their own locktime.
175    pub fn set_locktime(&mut self, locktime: LockTime) {
176        self.locktime = locktime;
177    }
178
179    /// Sets where this transaction's change should go.
180    ///
181    /// Left unset, the signer sends change to the single address it derives internally.
182    pub fn add_change(&mut self, change: ChangeOutput) {
183        self.change = Some(change);
184    }
185
186    /// Drops the change target, returning to the signer's own address.
187    pub fn remove_change(&mut self) {
188        self.change = None;
189    }
190
191    /// Adds a new input to the transaction.
192    ///
193    /// # Panics
194    /// Panics if the requested signature is not `NativeEcdsa` or `None`.
195    /// (i.e. if `required_sig` is `RequiredSignature::Witness` or `RequiredSignature::WitnessWithPath`)
196    pub fn add_input(&mut self, partial_input: PartialInput, required_sig: RequiredSignature) {
197        match required_sig {
198            RequiredSignature::Witness(_)
199            | RequiredSignature::WitnessWithPath(_, _)
200            | RequiredSignature::WitnessWithMessage(_, _, _) => {
201                panic!("Requested signature is not NativeEcdsa or None")
202            }
203            _ => {}
204        }
205
206        self.push_new_input(FinalInput::new(partial_input, required_sig));
207    }
208
209    /// Adds a new program input to the transaction.
210    ///
211    /// # Panics
212    /// The function will panic if the `required_sig` parameter is of type `RequiredSignature::NativeEcdsa`,
213    /// as this type of signature is not applicable for program inputs.
214    pub fn add_program_input(
215        &mut self,
216        partial_input: PartialInput,
217        program_input: ProgramInput,
218        required_sig: RequiredSignature,
219    ) {
220        if let RequiredSignature::NativeEcdsa = required_sig {
221            panic!("Requested signature is not Witness or None");
222        }
223
224        self.push_new_input(FinalInput::new(partial_input, required_sig).with_program(program_input));
225    }
226
227    /// Adds an issuance (or reissuance) input to the transaction.
228    ///
229    /// # Panics
230    /// This function panics if the `required_sig` is of type `Witness` or
231    /// `WitnessWithPath`, as these signature types are not allowed in the current context.
232    pub fn add_issuance_input(
233        &mut self,
234        partial_input: PartialInput,
235        issuance_input: IssuanceInput,
236        required_sig: RequiredSignature,
237    ) -> IssuanceDetails {
238        match required_sig {
239            RequiredSignature::Witness(_)
240            | RequiredSignature::WitnessWithPath(_, _)
241            | RequiredSignature::WitnessWithMessage(_, _, _) => {
242                panic!("Requested signature is not NativeEcdsa or None")
243            }
244            _ => {}
245        }
246
247        self.push_new_input(FinalInput::new(partial_input, required_sig).with_issuance(issuance_input))
248            .unwrap()
249    }
250
251    /// Adds an issuance program input to the transaction with the specified parameters.
252    ///
253    /// # Panics
254    /// Panics if the `required_sig` parameter is of type `RequiredSignature::NativeEcdsa`.
255    /// Also panics if the populated input fails to return valid issuance details.
256    pub fn add_program_issuance_input(
257        &mut self,
258        partial_input: PartialInput,
259        program_input: ProgramInput,
260        issuance_input: IssuanceInput,
261        required_sig: RequiredSignature,
262    ) -> IssuanceDetails {
263        if let RequiredSignature::NativeEcdsa = required_sig {
264            panic!("Requested signature is not Witness or None");
265        }
266
267        self.push_new_input(
268            FinalInput::new(partial_input, required_sig)
269                .with_program(program_input)
270                .with_issuance(issuance_input),
271        )
272        .unwrap()
273    }
274
275    /// Removes an input from the list of inputs at the specified index.
276    pub fn remove_input(&mut self, index: usize) -> Option<FinalInput> {
277        if self.inputs.get(index).is_some() {
278            return Some(self.inputs.remove(index));
279        }
280
281        None
282    }
283
284    /// Adds a partial output to the list of outputs.
285    pub fn add_output(&mut self, partial_output: PartialOutput) {
286        self.outputs.push(partial_output);
287    }
288
289    /// Removes an output from the `outputs` list at the specified index.
290    ///
291    /// # Panics
292    /// This function does not panic. If the `index` is invalid, it will return `None` instead of causing a panic.
293    pub fn remove_output(&mut self, index: usize) -> Option<PartialOutput> {
294        if self.outputs.get(index).is_some() {
295            return Some(self.outputs.remove(index));
296        }
297
298        None
299    }
300
301    /// Where this transaction's change should go, when the caller said.
302    #[must_use]
303    pub fn change(&self) -> Option<&ChangeOutput> {
304        self.change.as_ref()
305    }
306
307    /// Where this transaction's change should go, for a caller that needs to amend it.
308    #[must_use]
309    pub fn change_mut(&mut self) -> Option<&mut ChangeOutput> {
310        self.change.as_mut()
311    }
312
313    /// Provides a slice reference to the collection of `FinalInput` elements.
314    #[must_use]
315    pub fn inputs(&self) -> &[FinalInput] {
316        &self.inputs
317    }
318
319    /// Provides mutable access to the `inputs` field.
320    ///
321    /// This method returns a mutable slice of `FinalInput` elements,
322    /// allowing the caller to modify the elements in the `inputs` field.
323    pub fn inputs_mut(&mut self) -> &mut [FinalInput] {
324        &mut self.inputs
325    }
326
327    /// Returns a reference to the slice of `PartialOutput` elements contained within the struct.
328    #[must_use]
329    pub fn outputs(&self) -> &[PartialOutput] {
330        &self.outputs
331    }
332
333    /// Provides mutable access to the `outputs` field of the current struct.
334    pub fn outputs_mut(&mut self) -> &mut [PartialOutput] {
335        &mut self.outputs
336    }
337
338    /// Returns the number of inputs associated with the current instance.
339    #[must_use]
340    pub fn n_inputs(&self) -> usize {
341        self.inputs.len()
342    }
343
344    /// Returns the number of outputs associated with the object.
345    #[must_use]
346    pub fn n_outputs(&self) -> usize {
347        self.outputs.len()
348    }
349
350    /// Checks if any of the outputs require blinding, determines if at least one of them has a `blinding_key` specified.
351    #[must_use]
352    pub fn needs_blinding(&self) -> bool {
353        self.outputs.iter().any(|el| el.blinding_key.is_some())
354    }
355
356    /// Checks whether any input being spent is confidential.
357    ///
358    /// Blinding balances the inputs against the outputs, so a transaction spending a confidential input needs
359    /// at least one blinded output to balance against. Left without one it is rejected by the node as `bad-txns-in-ne-out`.
360    #[must_use]
361    pub fn has_confidential_input(&self) -> bool {
362        self.inputs.iter().any(|el| {
363            el.partial_input.witness_utxo.value.is_confidential()
364                || el.partial_input.witness_utxo.asset.is_confidential()
365                || el.partial_input.secrets.is_some()
366        })
367    }
368
369    /// Calculates the fee delta for a transaction based on the inputs and outputs.
370    ///
371    /// The fee delta represents the net difference between the available asset amount
372    /// from the transaction's inputs and the consumed asset amount by its outputs.
373    /// The function considers the network's policy asset to determine which inputs
374    /// and outputs contribute to the calculation.
375    ///
376    /// # Panics
377    /// Function will panic if the asset isn't unblinded correctly, and if PST input asset and amount is confidential.
378    #[must_use]
379    pub fn calculate_fee_delta(&self, network: &SimplicityNetwork) -> i64 {
380        let mut available_amount = 0;
381
382        for input in &self.inputs {
383            match input.partial_input.secrets {
384                // This is an unblinded confidential input
385                Some(secrets) => {
386                    if secrets.asset == network.policy_asset() {
387                        available_amount += secrets.value;
388                    }
389                }
390                // This is an explicit input
391                None => {
392                    if input.partial_input.asset.unwrap() == network.policy_asset() {
393                        available_amount += input.partial_input.amount.unwrap();
394                    }
395                }
396            }
397        }
398
399        let consumed_amount = self
400            .outputs
401            .iter()
402            .filter(|output| output.asset == network.policy_asset())
403            .fold(0_u64, |acc, output| acc + output.amount);
404
405        available_amount.cast_signed() - consumed_amount.cast_signed()
406    }
407
408    /// Checks if the transaction is balanced, meaning all inputs - all outputs = 0 for every asset.
409    ///
410    /// Issued and reissued amounts are credited to the input that declares them, so a newly created
411    /// asset is balanced against its declared `issuance_amount`/`inflation_amount`.
412    ///
413    /// # Panics
414    /// Function will panic if the assets aren't unblinded correctly, and if PST input assets and amounts are confidential.
415    #[must_use]
416    pub fn is_balanced(&self) -> bool {
417        let mut transfers: HashMap<AssetId, i64> = HashMap::new();
418
419        // Collecting all inputs
420        for input in &self.inputs {
421            let (asset, amount) = match input.partial_input.secrets {
422                Some(secrets) => (secrets.asset, secrets.value),
423                None => (input.partial_input.asset.unwrap(), input.partial_input.amount.unwrap()),
424            };
425
426            let transfer_entry = transfers.entry(asset).or_insert(0);
427            *transfer_entry += amount.cast_signed();
428
429            // Issuance brings new assets into the transaction, so the declared amounts count as inputs.
430            // A reissuance mints no new inflation tokens
431            if let Some(issuance_details) = input.get_issuance_details()
432                && let Some(issuance_input) = &input.issuance_input
433            {
434                let (issuance_amount, inflation_amount) = match issuance_input {
435                    IssuanceInput::Issuance {
436                        issuance_amount,
437                        inflation_amount,
438                        ..
439                    } => (*issuance_amount, *inflation_amount),
440                    IssuanceInput::Reissuance { issuance_amount, .. } => (*issuance_amount, 0),
441                };
442
443                *transfers.entry(issuance_details.asset_id).or_insert(0) += issuance_amount.cast_signed();
444                *transfers.entry(issuance_details.inflation_asset_id).or_insert(0) += inflation_amount.cast_signed();
445            }
446        }
447
448        for output in &self.outputs {
449            if output.script_pubkey.is_op_return() && output.amount == 0 {
450                continue;
451            }
452
453            match transfers.get_mut(&output.asset) {
454                Some(value) => {
455                    *value -= output.amount.cast_signed();
456                }
457                None => return false,
458            }
459        }
460
461        // All transfers including fee should sum up to 0
462        transfers.values().all(|&value| value == 0)
463    }
464
465    /// Computes the transaction fee based on the provided weight and fee rate.
466    ///
467    /// Overall, the function calculates the virtual size (vsize) of the transaction as:
468    /// `weight / WITNESS_SCALE_FACTOR`, rounded up to the nearest whole number.
469    /// Then, the fee is computed as `(vsize * fee_rate / 1000.0)`, also rounded up.
470    ///
471    /// # Returns
472    /// The transaction fee in satoshis, rounded up to the nearest whole number.
473    #[allow(
474        clippy::cast_possible_truncation,
475        clippy::cast_precision_loss,
476        clippy::cast_sign_loss
477    )]
478    #[must_use]
479    pub fn calculate_fee(&self, weight: usize, fee_rate: f32) -> u64 {
480        let vsize = weight.div_ceil(WITNESS_SCALE_FACTOR);
481
482        (vsize as f32 * fee_rate / 1000.0).ceil() as u64
483    }
484
485    /// Extracts a partially signed transaction (PST) and a mapping of input secrets from the current state.
486    ///
487    /// # Panics
488    /// Function will panic if the pst input is a confidential issuance.
489    #[must_use]
490    pub fn extract_pst(&self) -> (PartiallySignedTransaction, HashMap<usize, TxOutSecrets>) {
491        let mut input_secrets = HashMap::new();
492        let mut pst = PartiallySignedTransaction::new_v2();
493
494        for i in 0..self.inputs.len() {
495            let mut final_input = self.inputs[i].clone();
496
497            // Inject sequence if the input has none
498            if final_input.partial_input.sequence == Sequence::default() {
499                final_input.partial_input = final_input.partial_input.with_sequence(self.sequence);
500            }
501
502            // Inject locktime if the input has none
503            if final_input.partial_input.locktime == LockTime::ZERO {
504                final_input.partial_input = final_input.partial_input.with_locktime(self.locktime);
505            }
506
507            let pst_input = final_input.to_input();
508
509            match final_input.partial_input.secrets {
510                // Insert input secrets if present
511                Some(secrets) => input_secrets.insert(i, secrets),
512                // Else populate input secrets with "explicit" amounts
513                None => input_secrets.insert(
514                    i,
515                    TxOutSecrets {
516                        asset: pst_input.asset.unwrap(),
517                        asset_bf: AssetBlindingFactor::zero(),
518                        value: pst_input.amount.unwrap(),
519                        value_bf: ValueBlindingFactor::zero(),
520                    },
521                ),
522            };
523
524            pst.add_input(pst_input);
525        }
526
527        self.outputs.iter().for_each(|el| {
528            pst.add_output(el.to_output());
529        });
530
531        (pst, input_secrets)
532    }
533
534    fn push_new_input(&mut self, new_input: FinalInput) -> Option<IssuanceDetails> {
535        let issuance_details = new_input.get_issuance_details();
536
537        self.inputs.push(new_input);
538
539        issuance_details
540    }
541}
542
543#[cfg(test)]
544mod tests {
545    use bitcoin_hashes::Hash;
546
547    use simplicityhl::elements::{LockTime, OutPoint, Script, TxOut, Txid};
548
549    use crate::transaction::UTXO;
550
551    use super::*;
552
553    fn dummy_asset_id(byte: u8) -> AssetId {
554        AssetId::from_slice(&[byte; 32]).unwrap()
555    }
556
557    fn dummy_txid(byte: u8) -> Txid {
558        Txid::from_slice(&[byte; 32]).unwrap()
559    }
560
561    fn dummy_blinding_key() -> elements_miniscript::bitcoin::PublicKey {
562        let secp = simplicityhl::elements::secp256k1_zkp::Secp256k1::new();
563        let secret = simplicityhl::elements::secp256k1_zkp::SecretKey::from_slice(&[0x11; 32]).unwrap();
564
565        elements_miniscript::bitcoin::PublicKey::new(secret.public_key(&secp))
566    }
567
568    fn explicit_utxo(txid_byte: u8, vout: u32, amount: u64, asset: AssetId) -> UTXO {
569        UTXO {
570            outpoint: OutPoint::new(dummy_txid(txid_byte), vout),
571            txout: TxOut::new_fee(amount, asset),
572            secrets: None,
573        }
574    }
575
576    fn confidential_utxo(txid_byte: u8, vout: u32, asset: AssetId, value: u64) -> UTXO {
577        UTXO {
578            outpoint: OutPoint::new(dummy_txid(txid_byte), vout),
579            txout: TxOut::default(),
580            secrets: Some(TxOutSecrets::new(
581                asset,
582                AssetBlindingFactor::zero(),
583                value,
584                ValueBlindingFactor::zero(),
585            )),
586        }
587    }
588
589    #[test]
590    fn explicit_input_is_not_a_confidential_one() {
591        let policy = dummy_asset_id(0xAA);
592        let mut ft = FinalTransaction::new();
593
594        ft.add_input(
595            PartialInput::new(explicit_utxo(0x01, 0, 5000, policy)),
596            RequiredSignature::None,
597        );
598
599        assert!(!ft.has_confidential_input());
600    }
601
602    #[test]
603    fn input_carrying_secrets_is_a_confidential_one() {
604        let policy = dummy_asset_id(0xAA);
605        let mut ft = FinalTransaction::new();
606
607        ft.add_input(
608            PartialInput::new(confidential_utxo(0x01, 0, policy, 5000)),
609            RequiredSignature::None,
610        );
611
612        assert!(ft.has_confidential_input());
613    }
614
615    #[test]
616    fn confidential_input_paying_an_explicit_output_leaves_nothing_blinded() {
617        let policy = dummy_asset_id(0xAA);
618        let mut ft = FinalTransaction::new();
619
620        ft.add_input(
621            PartialInput::new(confidential_utxo(0x01, 0, policy, 5000)),
622            RequiredSignature::None,
623        );
624        ft.add_output(PartialOutput::new(Script::new(), 4000, policy));
625
626        assert!(ft.has_confidential_input());
627        assert!(!ft.needs_blinding());
628    }
629
630    #[test]
631    fn blinded_output_is_what_balances_the_transaction() {
632        let policy = dummy_asset_id(0xAA);
633        let mut ft = FinalTransaction::new();
634
635        ft.add_input(
636            PartialInput::new(confidential_utxo(0x01, 0, policy, 5000)),
637            RequiredSignature::None,
638        );
639        ft.add_output(PartialOutput::new(Script::new(), 4000, policy).with_blinding_key(dummy_blinding_key()));
640
641        assert!(ft.has_confidential_input());
642        assert!(ft.needs_blinding());
643    }
644
645    // Manually construct PST and check extract_pst correctness based on it
646    #[test]
647    fn extract_pst_single_explicit_input_single_output() {
648        let policy = dummy_asset_id(0xAA);
649
650        let utxo = explicit_utxo(0x01, 0, 5000, policy);
651        let partial_input = PartialInput::new(utxo);
652        let partial_output = PartialOutput::new(Script::new(), 4000, policy);
653
654        let mut ft = FinalTransaction::new();
655        ft.add_input(partial_input.clone(), RequiredSignature::None);
656        ft.add_output(partial_output.clone());
657
658        let mut expected_pst = PartiallySignedTransaction::new_v2();
659        expected_pst.add_input(partial_input.to_input());
660        expected_pst.add_output(partial_output.to_output());
661
662        let expected_secrets: HashMap<usize, TxOutSecrets> = HashMap::from([(
663            0,
664            TxOutSecrets::new(policy, AssetBlindingFactor::zero(), 5000, ValueBlindingFactor::zero()),
665        )]);
666
667        let (pst, secrets) = ft.extract_pst();
668
669        assert_eq!(pst, expected_pst);
670        assert_eq!(secrets, expected_secrets);
671    }
672
673    #[test]
674    fn declared_height_becomes_the_transactions_locktime() {
675        let policy = dummy_asset_id(0xAA);
676        let mut ft = FinalTransaction::new();
677
678        ft.add_input(
679            PartialInput::new(explicit_utxo(0x01, 0, 5000, policy)),
680            RequiredSignature::None,
681        );
682        ft.add_input(
683            PartialInput::new(explicit_utxo(0x02, 0, 5000, policy)),
684            RequiredSignature::None,
685        );
686        ft.add_output(PartialOutput::new(Script::new(), 9000, policy));
687        ft.set_locktime(LockTime::from_height(2_580_990).unwrap());
688
689        let (pst, _) = ft.extract_pst();
690
691        assert_eq!(
692            pst.locktime().expect("one height, so no conflict"),
693            LockTime::from_height(2_580_990).unwrap()
694        );
695        assert!(
696            pst.inputs()
697                .iter()
698                .all(|input| input.required_height_locktime.is_some())
699        );
700    }
701
702    #[test]
703    fn transaction_that_declares_no_height_still_has_none() {
704        let policy = dummy_asset_id(0xAA);
705        let mut ft = FinalTransaction::new();
706
707        ft.add_input(
708            PartialInput::new(explicit_utxo(0x01, 0, 5000, policy)),
709            RequiredSignature::None,
710        );
711        ft.add_output(PartialOutput::new(Script::new(), 4000, policy));
712
713        let (pst, _) = ft.extract_pst();
714
715        assert_eq!(pst.locktime().unwrap(), LockTime::ZERO);
716    }
717
718    #[test]
719    fn extract_pst_single_confidential_input() {
720        let policy = dummy_asset_id(0xAA);
721
722        let utxo = confidential_utxo(0x01, 0, policy, 3000);
723        let partial_input = PartialInput::new(utxo);
724        let partial_output = PartialOutput::new(Script::new(), 2000, policy);
725
726        let mut ft = FinalTransaction::new();
727        ft.add_input(partial_input.clone(), RequiredSignature::None);
728        ft.add_output(partial_output.clone());
729
730        let mut expected_pst = PartiallySignedTransaction::new_v2();
731        expected_pst.add_input(partial_input.to_input());
732        expected_pst.add_output(partial_output.to_output());
733
734        let expected_secrets = HashMap::from([(
735            0,
736            TxOutSecrets::new(policy, AssetBlindingFactor::zero(), 3000, ValueBlindingFactor::zero()),
737        )]);
738
739        let (pst, secrets) = ft.extract_pst();
740
741        assert_eq!(pst, expected_pst);
742        assert_eq!(secrets, expected_secrets);
743    }
744
745    #[test]
746    fn extract_pst_mixed_inputs_multiple_outputs() {
747        let policy = dummy_asset_id(0xAA);
748        let other = dummy_asset_id(0xBB);
749
750        let explicit_utxo = explicit_utxo(0x01, 0, 5000, policy);
751        let conf_utxo = confidential_utxo(0x02, 1, other, 1000);
752
753        let explicit_partial = PartialInput::new(explicit_utxo);
754        let conf_partial = PartialInput::new(conf_utxo);
755
756        let output_a = PartialOutput::new(Script::new(), 3000, policy);
757        let output_b = PartialOutput::new(Script::new(), 800, other);
758
759        let mut ft = FinalTransaction::new();
760        ft.add_input(explicit_partial.clone(), RequiredSignature::None);
761        ft.add_input(conf_partial.clone(), RequiredSignature::None);
762        ft.add_output(output_a.clone());
763        ft.add_output(output_b.clone());
764
765        let mut expected_pst = PartiallySignedTransaction::new_v2();
766        expected_pst.add_input(explicit_partial.to_input());
767        expected_pst.add_input(conf_partial.to_input());
768        expected_pst.add_output(output_a.to_output());
769        expected_pst.add_output(output_b.to_output());
770
771        let expected_secrets = HashMap::from([
772            (
773                0,
774                TxOutSecrets::new(policy, AssetBlindingFactor::zero(), 5000, ValueBlindingFactor::zero()),
775            ),
776            (
777                1,
778                TxOutSecrets::new(other, AssetBlindingFactor::zero(), 1000, ValueBlindingFactor::zero()),
779            ),
780        ]);
781
782        let (pst, secrets) = ft.extract_pst();
783
784        assert_eq!(pst, expected_pst);
785        assert_eq!(secrets, expected_secrets);
786    }
787
788    #[test]
789    fn extract_pst_with_issuance_input() {
790        let policy = dummy_asset_id(0xAA);
791        let entropy = [0x42u8; 32];
792        let issuance_amount = 1_000_000u64;
793
794        let utxo = explicit_utxo(0x01, 0, 5000, policy);
795        let partial_input = PartialInput::new(utxo);
796        let issuance = IssuanceInput::new_issuance(issuance_amount, 0, entropy);
797        let partial_output = PartialOutput::new(Script::new(), 4000, policy);
798
799        let mut ft = FinalTransaction::new();
800        ft.add_issuance_input(partial_input.clone(), issuance.clone(), RequiredSignature::None);
801        ft.add_output(partial_output.clone());
802
803        // build expected pst, merge partial_input and issuance manually
804        let mut expected_pst = PartiallySignedTransaction::new_v2();
805        let mut expected_input = partial_input.to_input();
806        let issuance_input = issuance.to_input();
807        expected_input.issuance_value_amount = issuance_input.issuance_value_amount;
808        expected_input.issuance_asset_entropy = issuance_input.issuance_asset_entropy;
809        expected_input.issuance_inflation_keys = issuance_input.issuance_inflation_keys;
810        expected_input.issuance_blinding_nonce = None;
811        expected_input.blinded_issuance = issuance_input.blinded_issuance;
812        expected_pst.add_input(expected_input);
813        expected_pst.add_output(partial_output.to_output());
814
815        let expected_secrets = HashMap::from([(
816            0,
817            TxOutSecrets::new(policy, AssetBlindingFactor::zero(), 5000, ValueBlindingFactor::zero()),
818        )]);
819
820        let (pst, secrets) = ft.extract_pst();
821
822        assert_eq!(pst, expected_pst);
823        assert_eq!(secrets, expected_secrets);
824    }
825
826    #[test]
827    fn extract_pst_with_reissuance_input() {
828        let policy = dummy_asset_id(0xAA);
829        let entropy = [0x42u8; 32];
830        let issuance_amount = 1_000_000u64;
831
832        let conf_utxo = confidential_utxo(0x02, 0, policy, 1000);
833        let partial_input = PartialInput::new(conf_utxo);
834        let reissuance_input = IssuanceInput::new_reissuance(issuance_amount, entropy);
835        let partial_output = PartialOutput::new(Script::new(), 1000, policy);
836
837        let mut ft = FinalTransaction::new();
838        ft.add_issuance_input(partial_input.clone(), reissuance_input.clone(), RequiredSignature::None);
839        ft.add_output(partial_output.clone());
840
841        // build expected pst, merge partial_input and issuance manually
842        let mut expected_pst = PartiallySignedTransaction::new_v2();
843        let mut expected_input = partial_input.to_input();
844        let issuance_input = reissuance_input.to_input();
845        expected_input.issuance_value_amount = issuance_input.issuance_value_amount;
846        expected_input.issuance_asset_entropy = issuance_input.issuance_asset_entropy;
847        expected_input.issuance_inflation_keys = None;
848        expected_input.issuance_blinding_nonce = Some(partial_input.secrets.unwrap().asset_bf.into_inner());
849        expected_input.blinded_issuance = issuance_input.blinded_issuance;
850        expected_pst.add_input(expected_input);
851        expected_pst.add_output(partial_output.to_output());
852
853        let expected_secrets = HashMap::from([(
854            0,
855            TxOutSecrets::new(policy, AssetBlindingFactor::zero(), 1000, ValueBlindingFactor::zero()),
856        )]);
857
858        let (pst, secrets) = ft.extract_pst();
859
860        assert_eq!(pst, expected_pst);
861        assert_eq!(secrets, expected_secrets);
862    }
863
864    #[test]
865    fn balanced_transfer_single_asset() {
866        let policy = dummy_asset_id(0xAA);
867
868        let mut ft = FinalTransaction::new();
869        ft.add_input(
870            PartialInput::new(explicit_utxo(0x01, 0, 5000, policy)),
871            RequiredSignature::None,
872        );
873        ft.add_output(PartialOutput::new(Script::new(), 4000, policy));
874        ft.add_output(PartialOutput::new(Script::new(), 1000, policy));
875
876        assert!(ft.is_balanced());
877    }
878
879    #[test]
880    fn output_without_input_is_unbalanced() {
881        let policy = dummy_asset_id(0xAA);
882
883        let mut ft = FinalTransaction::new();
884        ft.add_input(
885            PartialInput::new(explicit_utxo(0x01, 0, 5000, policy)),
886            RequiredSignature::None,
887        );
888        ft.add_output(PartialOutput::new(Script::new(), 5000, policy));
889        ft.add_output(PartialOutput::new(Script::new(), 1, dummy_asset_id(0xBB)));
890
891        assert!(!ft.is_balanced());
892    }
893
894    #[test]
895    fn leftover_input_amount_is_unbalanced() {
896        let policy = dummy_asset_id(0xAA);
897
898        let mut ft = FinalTransaction::new();
899        ft.add_input(
900            PartialInput::new(explicit_utxo(0x01, 0, 5000, policy)),
901            RequiredSignature::None,
902        );
903        ft.add_output(PartialOutput::new(Script::new(), 4000, policy));
904
905        assert!(!ft.is_balanced());
906    }
907
908    #[test]
909    fn issuance_is_balanced_against_its_declared_amounts() {
910        let policy = dummy_asset_id(0xAA);
911
912        let mut ft = FinalTransaction::new();
913        let details = ft.add_issuance_input(
914            PartialInput::new(explicit_utxo(0x01, 0, 1000, policy)),
915            IssuanceInput::new_issuance(100, 1, [0x07; 32]),
916            RequiredSignature::None,
917        );
918        ft.add_output(PartialOutput::new(Script::new(), 100, details.asset_id));
919        ft.add_output(PartialOutput::new(Script::new(), 1, details.inflation_asset_id));
920        ft.add_output(PartialOutput::new(Script::new(), 1000, policy));
921
922        assert!(ft.is_balanced());
923    }
924
925    #[test]
926    fn issuing_more_than_declared_is_unbalanced() {
927        let policy = dummy_asset_id(0xAA);
928
929        let mut ft = FinalTransaction::new();
930        let details = ft.add_issuance_input(
931            PartialInput::new(explicit_utxo(0x01, 0, 1000, policy)),
932            IssuanceInput::new_issuance(100, 0, [0x07; 32]),
933            RequiredSignature::None,
934        );
935        ft.add_output(PartialOutput::new(Script::new(), 1_000_000_000, details.asset_id));
936        ft.add_output(PartialOutput::new(Script::new(), 1000, policy));
937
938        assert!(!ft.is_balanced());
939    }
940
941    #[test]
942    fn minting_inflation_keys_that_were_never_declared_is_unbalanced() {
943        let policy = dummy_asset_id(0xAA);
944
945        let mut ft = FinalTransaction::new();
946        let details = ft.add_issuance_input(
947            PartialInput::new(explicit_utxo(0x01, 0, 1000, policy)),
948            IssuanceInput::new_issuance(100, 0, [0x07; 32]),
949            RequiredSignature::None,
950        );
951        ft.add_output(PartialOutput::new(Script::new(), 100, details.asset_id));
952        ft.add_output(PartialOutput::new(Script::new(), 42, details.inflation_asset_id));
953        ft.add_output(PartialOutput::new(Script::new(), 1000, policy));
954
955        assert!(!ft.is_balanced());
956    }
957
958    #[test]
959    fn reissuance_alongside_a_transfer_of_the_same_asset_is_balanced() {
960        let policy = dummy_asset_id(0xAA);
961        let entropy = [0x07; 32];
962
963        let mut probe = FinalTransaction::new();
964        let details = probe.add_issuance_input(
965            PartialInput::new(explicit_utxo(0x01, 0, 1, dummy_asset_id(0xBB))),
966            IssuanceInput::new_reissuance(100, entropy),
967            RequiredSignature::None,
968        );
969
970        let mut ft = FinalTransaction::new();
971        ft.add_input(
972            PartialInput::new(explicit_utxo(0x02, 0, 1, details.inflation_asset_id)),
973            RequiredSignature::None,
974        );
975        ft.add_issuance_input(
976            PartialInput::new(explicit_utxo(0x03, 0, 50, details.asset_id)),
977            IssuanceInput::new_reissuance(100, entropy),
978            RequiredSignature::None,
979        );
980        ft.add_input(
981            PartialInput::new(explicit_utxo(0x04, 0, 1000, policy)),
982            RequiredSignature::None,
983        );
984
985        ft.add_output(PartialOutput::new(Script::new(), 150, details.asset_id));
986        ft.add_output(PartialOutput::new(Script::new(), 1, details.inflation_asset_id));
987        ft.add_output(PartialOutput::new(Script::new(), 1000, policy));
988
989        assert!(ft.is_balanced());
990    }
991
992    #[test]
993    fn confidential_input_amounts_are_counted() {
994        let policy = dummy_asset_id(0xAA);
995
996        let mut ft = FinalTransaction::new();
997        ft.add_input(
998            PartialInput::new(confidential_utxo(0x01, 0, policy, 5000)),
999            RequiredSignature::None,
1000        );
1001        ft.add_output(PartialOutput::new(Script::new(), 5000, policy));
1002
1003        assert!(ft.is_balanced());
1004    }
1005
1006    #[test]
1007    fn balanced_transfer_single_asset_with_metadata_output() {
1008        let policy = dummy_asset_id(0xAA);
1009
1010        let mut ft = FinalTransaction::new();
1011        ft.add_input(
1012            PartialInput::new(explicit_utxo(0x01, 0, 5000, policy)),
1013            RequiredSignature::None,
1014        );
1015        ft.add_output(PartialOutput::new(Script::new(), 4000, policy));
1016        ft.add_output(PartialOutput::new(Script::new(), 1000, policy));
1017        ft.add_output(PartialOutput::new_metadata("burn".as_bytes()));
1018
1019        assert!(ft.is_balanced());
1020    }
1021}