//! //! # Transaction //! //! This module implements consensus [`Transaction`] structure and related types. //! #![allow(non_snake_case)] mod script_public_key; mod serde_impl; use crate::HashSet; use crate::mass::{ComputeBudget, NonContextualMasses, ScriptUnits, SigopCount, free_script_units_per_input}; #[cfg(feature = "std")] use crate::mass::{ContextualMasses, Mass, MassCofactors}; pub use crate::utxo::UtxoEntry; use crate::{ errors::tx::PopulateGenesisCovenantsError, hashing, subnets::{self, SubnetworkId}, }; use alloc::sync::Arc; use alloc::vec; use alloc::vec::Vec; use borsh::{BorshDeserialize, BorshSerialize}; use core::{ fmt::Display, ops::Range, str::{self}, }; use kaspa_hashes::Hash; use kaspa_hashes::ZERO_HASH; use kaspa_utils::hex::ToHex; #[cfg(feature = "mem_size")] use kaspa_utils::mem_size::MemSizeEstimator; use kaspa_utils::serde_bytes_fixed_ref; #[cfg(feature = "wasm32-sdk")] pub use script_public_key::ScriptPublicKeyT; pub use script_public_key::{SCRIPT_VECTOR_SIZE, ScriptPublicKey, ScriptPublicKeyVersion, ScriptPublicKeys, ScriptVec, scriptvec}; use serde::{Deserialize, Serialize}; /// COINBASE_TRANSACTION_INDEX is the index of the coinbase transaction in every block pub const COINBASE_TRANSACTION_INDEX: usize = 0; /// A 32-byte Kaspa transaction identifier. pub type TransactionId = kaspa_hashes::Hash; pub type TransactionIndexType = u32; /// Represents a Kaspa transaction outpoint #[derive(Eq, Default, Hash, PartialEq, Debug, Copy, Clone, Serialize, Deserialize, BorshSerialize, BorshDeserialize)] #[serde(rename_all = "camelCase")] pub struct TransactionOutpoint { #[serde(with = "serde_bytes_fixed_ref")] pub transaction_id: TransactionId, pub index: TransactionIndexType, } impl TransactionOutpoint { pub const EMPTY: Self = Self { transaction_id: ZERO_HASH, index: 0 }; pub const MAX: Self = Self { transaction_id: kaspa_hashes::MAX_HASH, index: u32::MAX }; pub fn new(transaction_id: TransactionId, index: u32) -> Self { Self { transaction_id, index } } } impl Display for TransactionOutpoint { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { write!(f, "({}, {})", self.transaction_id, self.index) } } /// Encodes the compute mass commitment for a transaction input. /// Version 0 transactions use `SigopCount`, version >= 1 transactions use `ComputeBudget`. #[derive(Serialize, Deserialize, Clone, PartialEq, Eq, BorshSerialize, BorshDeserialize, Debug, Copy)] pub enum ComputeCommit { SigopCount(SigopCount), ComputeBudget(ComputeBudget), } impl ComputeCommit { pub fn sig_op_count(self) -> Option { match self { Self::SigopCount(n) => Some(n.into()), _ => None, } } pub fn compute_budget(self) -> Option { match self { Self::ComputeBudget(n) => Some(n.into()), _ => None, } } pub fn version_expects_compute_budget_field(version: u16) -> bool { version >= 1 } pub fn version_expects_sig_op_count_field(version: u16) -> bool { !Self::version_expects_compute_budget_field(version) } /// Returns the total script units this input mass allows the engine to consume, including a free per-input budget. pub fn allowed_script_units(self) -> ScriptUnits { let script_units = ScriptUnits::from(self); script_units.saturating_add(free_script_units_per_input()) } } impl From for ComputeCommit { fn from(value: SigopCount) -> Self { Self::SigopCount(value) } } impl From for ComputeCommit { fn from(value: ComputeBudget) -> Self { Self::ComputeBudget(value) } } impl From for ScriptUnits { fn from(value: ComputeCommit) -> Self { match value { ComputeCommit::SigopCount(count) => ScriptUnits::from(count), ComputeCommit::ComputeBudget(budget) => ScriptUnits::from(budget), } } } /// Represents a Kaspa transaction input #[derive(Clone, PartialEq, Eq, BorshSerialize, BorshDeserialize)] pub struct TransactionInput { pub previous_outpoint: TransactionOutpoint, pub signature_script: Vec, // TODO: Consider using SmallVec pub sequence: u64, pub compute_commit: ComputeCommit, } impl TransactionInput { pub fn new_with_mass( previous_outpoint: TransactionOutpoint, signature_script: Vec, sequence: u64, compute_commit: ComputeCommit, ) -> Self { Self { previous_outpoint, signature_script, sequence, compute_commit } } pub fn new(previous_outpoint: TransactionOutpoint, signature_script: Vec, sequence: u64, sig_op_count: u8) -> Self { Self { previous_outpoint, signature_script, sequence, compute_commit: SigopCount(sig_op_count).into() } } pub fn new_with_compute_budget( previous_outpoint: TransactionOutpoint, signature_script: Vec, sequence: u64, compute_budget: u16, ) -> Self { Self { previous_outpoint, signature_script, sequence, compute_commit: ComputeBudget(compute_budget).into() } } } impl core::fmt::Debug for TransactionInput { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { f.debug_struct("TransactionInput") .field("previous_outpoint", &self.previous_outpoint) .field("signature_script", &self.signature_script.to_hex()) .field("sequence", &self.sequence) .field("sig_op_count", &self.compute_commit.sig_op_count().unwrap_or_default()) .field("compute_budget", &self.compute_commit.compute_budget().unwrap_or_default()) .finish() } } /// Represents a Kaspad transaction output #[derive(Debug, Clone, PartialEq, Eq, BorshSerialize, BorshDeserialize)] pub struct TransactionOutput { pub value: u64, pub script_public_key: ScriptPublicKey, pub covenant: Option, } impl TransactionOutput { pub fn new(value: u64, script_public_key: ScriptPublicKey) -> Self { Self { value, script_public_key, covenant: None } } pub fn with_covenant(value: u64, script_public_key: ScriptPublicKey, covenant: Option) -> Self { Self { value, script_public_key, covenant } } } /// Binds a transaction output to the covenant and input authorizing its creation. #[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq, BorshSerialize, BorshDeserialize, Copy)] #[serde(rename_all = "camelCase")] pub struct CovenantBinding { pub authorizing_input: u16, /// Identifier of the covenant this output belongs to. /// /// Genesis covenant ids are computed by /// [`covenant_id()`](fn@crate::hashing::covenant_id::covenant_id). pub covenant_id: Hash, } // #[wasm_bindgen] impl CovenantBinding { pub fn new(authorizing_input: u16, covenant_id: Hash) -> Self { Self { authorizing_input, covenant_id } } } /// A genesis covenant group for bulk covenant binding population. /// /// All listed outputs are bound to the same covenant id, derived from the /// authorizing input outpoint and this exact ordered output list. #[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq, BorshSerialize, BorshDeserialize)] #[serde(rename_all = "camelCase")] pub struct GenesisCovenantGroup { pub authorizing_input: u16, pub outputs: Vec, } impl GenesisCovenantGroup { pub fn new(authorizing_input: u16, outputs: Vec) -> Self { Self { authorizing_input, outputs } } } /// Interior-mutable `u64` cell backing the transaction mass field, abstracting /// over the atomic and non-atomic representations. trait MassCell { fn from_u64(value: u64) -> Self; fn read(&self) -> u64; fn write(&self, value: u64); } #[cfg(feature = "atomic-mass")] use core::sync::atomic::{AtomicU64, Ordering::SeqCst}; #[cfg(feature = "atomic-mass")] impl MassCell for AtomicU64 { fn from_u64(value: u64) -> Self { AtomicU64::new(value) } fn read(&self) -> u64 { self.load(SeqCst) } fn write(&self, value: u64) { self.store(value, SeqCst) } } #[cfg(not(feature = "atomic-mass"))] use core::cell::Cell; #[cfg(not(feature = "atomic-mass"))] impl MassCell for Cell { fn from_u64(value: u64) -> Self { Cell::new(value) } fn read(&self) -> u64 { self.get() } fn write(&self, value: u64) { self.set(value) } } /// Backing storage of the mass field. With the `atomic-mass` feature it is an /// `AtomicU64`, keeping [`Transaction`] `Sync` so the mass can be updated through a /// shared reference (e.g. from the mempool). Without it (single-threaded targets, /// or targets lacking 64-bit atomics) a `Cell` is used instead. #[cfg(feature = "atomic-mass")] type MassInner = AtomicU64; #[cfg(not(feature = "atomic-mass"))] type MassInner = Cell; #[derive(Debug, Default, Serialize, Deserialize)] pub struct TransactionMass(MassInner); // TODO: using interior mutability as a temp solution for mutating this field through the mempool impl Eq for TransactionMass {} impl PartialEq for TransactionMass { fn eq(&self, other: &Self) -> bool { self.0.read() == other.0.read() } } impl Clone for TransactionMass { fn clone(&self) -> Self { Self(MassInner::from_u64(self.0.read())) } } impl BorshDeserialize for TransactionMass { fn deserialize_reader(reader: &mut R) -> borsh::io::Result { let mass: u64 = borsh::BorshDeserialize::deserialize_reader(reader)?; Ok(Self(MassInner::from_u64(mass))) } } impl BorshSerialize for TransactionMass { fn serialize(&self, writer: &mut W) -> borsh::io::Result<()> { borsh::BorshSerialize::serialize(&self.0.read(), writer) } } /// Represents a Kaspa transaction #[derive(Debug, Clone, PartialEq, Eq, Default, BorshSerialize, BorshDeserialize)] pub struct Transaction { pub version: u16, pub inputs: Vec, pub outputs: Vec, pub lock_time: u64, pub subnetwork_id: SubnetworkId, pub gas: u64, pub payload: Vec, /// Holds a commitment to the storage mass (KIP-0009) storage_mass: TransactionMass, // A field that is used to cache the transaction ID. // Always use the corresponding self.id() instead of accessing this field directly id: TransactionId, } impl Transaction { pub fn new( version: u16, inputs: Vec, outputs: Vec, lock_time: u64, subnetwork_id: SubnetworkId, gas: u64, payload: Vec, ) -> Self { let mut tx = Self::new_non_finalized(version, inputs, outputs, lock_time, subnetwork_id, gas, payload); tx.finalize(); tx } pub fn new_with_mass( version: u16, inputs: Vec, outputs: Vec, lock_time: u64, subnetwork_id: SubnetworkId, gas: u64, payload: Vec, mass: u64, ) -> Self { let mut tx = Self::new_non_finalized(version, inputs, outputs, lock_time, subnetwork_id, gas, payload); tx.set_storage_mass(mass); tx.finalize(); tx } pub fn new_non_finalized( version: u16, inputs: Vec, outputs: Vec, lock_time: u64, subnetwork_id: SubnetworkId, gas: u64, payload: Vec, ) -> Self { Self { version, inputs, outputs, lock_time, subnetwork_id, gas, payload, storage_mass: Default::default(), id: Default::default(), } } /// Populates genesis covenant bindings for multiple output groups. /// /// For each group, this computes `covenant_id(authorizing_input.outpoint, group.outputs)` /// and sets that binding on all listed outputs. /// /// Validation is performed for all groups before mutating the transaction: /// - authorizing input index must exist /// - output indices must exist /// - outputs in each group must be strictly increasing /// - outputs across groups must be disjoint /// - targeted outputs must not already contain a covenant binding pub fn populate_genesis_covenants(&mut self, groups: &[GenesisCovenantGroup]) -> Result<(), PopulateGenesisCovenantsError> { let mut seen_outs = vec![false; self.outputs.len()]; // Phase 1: Validate all groups without mutating. for group in groups { let auth_input = group.authorizing_input as usize; if auth_input >= self.inputs.len() { return Err(PopulateGenesisCovenantsError::NoSuchInput(auth_input, self.inputs.len())); } let outs = group.outputs.as_slice(); if outs.is_empty() { return Err(PopulateGenesisCovenantsError::EmptyOutputs); } // Only enforce monotonic order here; duplicate indices are rejected by the `seen_outs` disjointness check below. if !outs.is_sorted() { return Err(PopulateGenesisCovenantsError::OutputsNotOrdered); } // Because indices are sorted ascending, bound-checking the last (max) index is sufficient. let last = *outs.last().expect("checked non-empty above"); if (last as usize) >= self.outputs.len() { return Err(PopulateGenesisCovenantsError::NoSuchOutput(last, self.outputs.len())); } for &out in outs { if seen_outs[out as usize] { return Err(PopulateGenesisCovenantsError::OutputsNotDisjoint(out)); } seen_outs[out as usize] = true; if self.outputs[out as usize].covenant.is_some() { return Err(PopulateGenesisCovenantsError::CovenantAlreadyPopulated(out)); } } } // Phase 2: Compute covenant ids and apply bindings. for group in groups { let auth_input = group.authorizing_input as usize; let input_outpoint = self.inputs[auth_input].previous_outpoint; let covenant_id = hashing::covenant_id::covenant_id(input_outpoint, group.outputs.iter().map(|&out| (out, &self.outputs[out as usize]))); let binding = CovenantBinding::new(group.authorizing_input, covenant_id); for &out in &group.outputs { self.outputs[out as usize].covenant = Some(binding); } } Ok(()) } } impl Transaction { /// Determines whether or not a transaction is a coinbase transaction. A coinbase /// transaction is a special transaction created by miners that distributes fees and block subsidy /// to the previous blocks' miners, and specifies the script_pub_key that will be used to pay the current /// miner in future blocks. pub fn is_coinbase(&self) -> bool { self.subnetwork_id == subnets::SUBNETWORK_ID_COINBASE } /// Recompute and finalize the tx id based on updated tx fields pub fn finalize(&mut self) { self.id = hashing::tx::id(self); } /// Returns the transaction ID pub fn id(&self) -> TransactionId { self.id } /// Set the storage mass commitment field of this transaction. This field has been activated on mainnet as part /// of the Crescendo hardfork. The field has no effect on tx ID so no need to finalize following this call. #[deprecated = "This function is deprecated to avoid ambiguity with compute mass and transient mass. Use `self.set_storage_mass(mass)` instead."] pub fn set_mass(&self, mass: u64) { self.set_storage_mass(mass); } /// Set the storage mass commitment field of this transaction. This field has been activated on mainnet as part /// of the Crescendo hardfork. The field has no effect on tx ID so no need to finalize following this call. pub fn set_storage_mass(&self, mass: u64) { self.storage_mass.0.write(mass) } /// Read the storage mass commitment #[deprecated = "This function is deprecated to avoid ambiguity with compute mass and transient mass. Use `self.storage_mass()` instead."] pub fn mass(&self) -> u64 { self.storage_mass() } /// Read the storage mass commitment pub fn storage_mass(&self) -> u64 { self.storage_mass.0.read() } /// Set the storage mass commitment of the passed transaction pub fn with_storage_mass(self, mass: u64) -> Self { self.set_storage_mass(mass); self } pub fn payload_digest(&self) -> Hash { hashing::tx::payload_digest(&self.payload) } } #[cfg(feature = "mem_size")] impl MemSizeEstimator for Transaction { fn estimate_mem_bytes(&self) -> usize { // Calculates mem bytes of the transaction (for cache tracking purposes) size_of::() + self.payload.len() + self .inputs .iter() .map(|i| i.signature_script.len() + size_of::()) .chain(self.outputs.iter().map(|o| { // size_of::() already counts SCRIPT_VECTOR_SIZE bytes within, so we only add the delta o.script_public_key.script().len().saturating_sub(SCRIPT_VECTOR_SIZE) + size_of::() })) .sum::() } } /// Represents any kind of transaction which has populated UTXO entry data and can be verified/signed etc pub trait VerifiableTransaction { fn tx(&self) -> &Transaction; /// Returns the `i`'th populated input fn populated_input(&self, index: usize) -> (&TransactionInput, &UtxoEntry); /// Returns an iterator over populated `(input, entry)` pairs fn populated_inputs(&self) -> PopulatedInputIterator<'_, Self> where Self: Sized, { PopulatedInputIterator::new(self) } fn inputs(&self) -> &[TransactionInput] { &self.tx().inputs } fn outputs(&self) -> &[TransactionOutput] { &self.tx().outputs } fn is_coinbase(&self) -> bool { self.tx().is_coinbase() } fn id(&self) -> TransactionId { self.tx().id() } fn utxo(&self, index: usize) -> Option<&UtxoEntry>; fn payload_digest(&self) -> Hash { self.tx().payload_digest() } fn version(&self) -> u16 { self.tx().version } } /// A custom iterator written only so that `populated_inputs` has a known return type and can de defined on the trait level pub struct PopulatedInputIterator<'a, T: VerifiableTransaction> { tx: &'a T, r: Range, } impl Clone for PopulatedInputIterator<'_, T> { fn clone(&self) -> Self { Self { tx: self.tx, r: self.r.clone() } } } impl<'a, T: VerifiableTransaction> PopulatedInputIterator<'a, T> { pub fn new(tx: &'a T) -> Self { Self { tx, r: (0..tx.inputs().len()) } } } impl<'a, T: VerifiableTransaction> Iterator for PopulatedInputIterator<'a, T> { type Item = (&'a TransactionInput, &'a UtxoEntry); fn next(&mut self) -> Option { self.r.next().map(|i| self.tx.populated_input(i)) } fn size_hint(&self) -> (usize, Option) { self.r.size_hint() } } impl ExactSizeIterator for PopulatedInputIterator<'_, T> {} /// Represents a read-only referenced transaction along with fully populated UTXO entry data pub struct PopulatedTransaction<'a> { pub tx: &'a Transaction, pub entries: Vec, } impl<'a> PopulatedTransaction<'a> { pub fn new(tx: &'a Transaction, entries: Vec) -> Self { assert_eq!(tx.inputs.len(), entries.len()); Self { tx, entries } } } impl VerifiableTransaction for PopulatedTransaction<'_> { fn tx(&self) -> &Transaction { self.tx } fn populated_input(&self, index: usize) -> (&TransactionInput, &UtxoEntry) { (&self.tx.inputs[index], &self.entries[index]) } fn utxo(&self, index: usize) -> Option<&UtxoEntry> { self.entries.get(index) } } /// Represents a validated transaction with populated UTXO entry data and a calculated fee pub struct ValidatedTransaction<'a> { pub tx: &'a Transaction, pub entries: Vec, pub calculated_fee: u64, } impl<'a> ValidatedTransaction<'a> { pub fn new(populated_tx: PopulatedTransaction<'a>, calculated_fee: u64) -> Self { Self { tx: populated_tx.tx, entries: populated_tx.entries, calculated_fee } } pub fn new_coinbase(tx: &'a Transaction) -> Self { assert!(tx.is_coinbase()); Self { tx, entries: Vec::new(), calculated_fee: 0 } } } impl VerifiableTransaction for ValidatedTransaction<'_> { fn tx(&self) -> &Transaction { self.tx } fn populated_input(&self, index: usize) -> (&TransactionInput, &UtxoEntry) { (&self.tx.inputs[index], &self.entries[index]) } fn utxo(&self, index: usize) -> Option<&UtxoEntry> { self.entries.get(index) } } impl AsRef for Transaction { fn as_ref(&self) -> &Transaction { self } } /// Represents a generic mutable/readonly/pointer transaction type along /// with partially filled UTXO entry data and optional fee and mass #[derive(Clone, Debug, PartialEq, Eq)] pub struct MutableTransaction = alloc::sync::Arc> { /// The inner transaction pub tx: T, /// Partially filled UTXO entry data pub entries: Vec>, /// Populated fee pub calculated_fee: Option, /// Populated non-contextual masses (does not include the storage mass) pub calculated_non_contextual_masses: Option, } impl> MutableTransaction { pub fn new(tx: T) -> Self { let num_inputs = tx.as_ref().inputs.len(); Self { tx, entries: vec![None; num_inputs], calculated_fee: None, calculated_non_contextual_masses: None } } pub fn id(&self) -> TransactionId { self.tx.as_ref().id() } pub fn with_entries(tx: T, entries: Vec) -> Self { assert_eq!(tx.as_ref().inputs.len(), entries.len()); Self { tx, entries: entries.into_iter().map(Some).collect(), calculated_fee: None, calculated_non_contextual_masses: None } } /// Returns the tx wrapped as a [`VerifiableTransaction`]. Note that this function /// must be called only once all UTXO entries are populated, otherwise it panics. pub fn as_verifiable(&self) -> impl VerifiableTransaction + '_ { assert!(self.is_verifiable()); MutableTransactionVerifiableWrapper { inner: self } } pub fn is_verifiable(&self) -> bool { assert_eq!(self.entries.len(), self.tx.as_ref().inputs.len()); self.entries.iter().all(|e| e.is_some()) } pub fn is_fully_populated(&self) -> bool { self.is_verifiable() && self.calculated_fee.is_some() && self.calculated_non_contextual_masses.is_some() } pub fn missing_outpoints(&self) -> impl Iterator + '_ { assert_eq!(self.entries.len(), self.tx.as_ref().inputs.len()); self.entries .iter() .enumerate() .filter_map(|(i, entry)| if entry.is_none() { Some(self.tx.as_ref().inputs[i].previous_outpoint) } else { None }) } pub fn clear_entries(&mut self) { for entry in self.entries.iter_mut() { *entry = None; } } /// Returns the calculated feerate. The feerate is calculated as the amount of fee this /// transactions pays per gram of the aggregated contextual mass (max over compute, transient /// and storage masses). The function returns a value when calculated fee and calculated masses /// exist, otherwise `None` is returned. /// /// Relies on floating-point ceiling math from the standard library. #[cfg(feature = "std")] pub fn calculated_feerate(&self, cofactors: &MassCofactors) -> Option { self.calculated_non_contextual_masses .map(|non_contextual| { Mass::new(non_contextual, ContextualMasses::new(self.tx.as_ref().storage_mass())).normalized_max(cofactors) }) .and_then(|max_mass| self.calculated_fee.map(|fee| fee as f64 / max_mass as f64)) } /// A function for estimating the amount of memory bytes used by this transaction (dedicated to mempool usage). /// We need consistency between estimation calls so only this function should be used for this purpose since /// `estimate_mem_bytes` is sensitive to pointer wrappers such as Arc #[cfg(feature = "mem_size")] pub fn mempool_estimated_bytes(&self) -> usize { self.estimate_mem_bytes() } pub fn has_parent(&self, possible_parent: TransactionId) -> bool { self.tx.as_ref().inputs.iter().any(|x| x.previous_outpoint.transaction_id == possible_parent) } pub fn has_parent_in_set(&self, possible_parents: &HashSet) -> bool { self.tx.as_ref().inputs.iter().any(|x| possible_parents.contains(&x.previous_outpoint.transaction_id)) } } #[cfg(feature = "mem_size")] impl> MemSizeEstimator for MutableTransaction { fn estimate_mem_bytes(&self) -> usize { size_of::() + self .entries .iter() .map(|op| { // size_of::>() already counts SCRIPT_VECTOR_SIZE bytes within, so we only add the delta size_of::>() + op.as_ref().map_or(0, |e| e.script_public_key.script().len().saturating_sub(SCRIPT_VECTOR_SIZE)) }) .sum::() + self.tx.as_ref().estimate_mem_bytes() } } impl> AsRef for MutableTransaction { fn as_ref(&self) -> &Transaction { self.tx.as_ref() } } /// Private struct used to wrap a [`MutableTransaction`] as a [`VerifiableTransaction`] struct MutableTransactionVerifiableWrapper<'a, T: AsRef> { inner: &'a MutableTransaction, } impl> VerifiableTransaction for MutableTransactionVerifiableWrapper<'_, T> { fn tx(&self) -> &Transaction { self.inner.tx.as_ref() } fn populated_input(&self, index: usize) -> (&TransactionInput, &UtxoEntry) { ( &self.inner.tx.as_ref().inputs[index], self.inner.entries[index].as_ref().expect("expected to be called only following full UTXO population"), ) } fn utxo(&self, index: usize) -> Option<&UtxoEntry> { self.inner.entries.get(index).and_then(Option::as_ref) } } /// Specialized impl for `T=Arc` impl MutableTransaction { pub fn from_tx(tx: Transaction) -> Self { Self::new(alloc::sync::Arc::new(tx)) } } /// Alias for a fully mutable and owned transaction which can be populated with external data /// and can also be modified internally and signed etc. pub type SignableTransaction = MutableTransaction; #[derive(Debug, Clone)] pub enum TransactionType { Transaction, SignableTransaction, } #[derive(Debug, Clone)] pub enum TransactionQueryResult { Transaction(Arc>), SignableTransaction(Arc>), } #[cfg(test)] mod tests { use crate::errors::tx::PopulateGenesisCovenantsError; use crate::hashing; use crate::subnets::SUBNETWORK_ID_NATIVE; use super::*; use smallvec::smallvec; fn test_transaction() -> Transaction { let script_public_key = ScriptPublicKey::new( 0, smallvec![ 0x76, 0xa9, 0x21, 0x03, 0x2f, 0x7e, 0x43, 0x0a, 0xa4, 0xc9, 0xd1, 0x59, 0x43, 0x7e, 0x84, 0xb9, 0x75, 0xdc, 0x76, 0xd9, 0x00, 0x3b, 0xf0, 0x92, 0x2c, 0xf3, 0xaa, 0x45, 0x28, 0x46, 0x4b, 0xab, 0x78, 0x0d, 0xba, 0x5e ], ); Transaction::new( 0, vec![ TransactionInput { previous_outpoint: TransactionOutpoint { transaction_id: TransactionId::from_slice(&[ 0x16, 0x5e, 0x38, 0xe8, 0xb3, 0x91, 0x45, 0x95, 0xd9, 0xc6, 0x41, 0xf3, 0xb8, 0xee, 0xc2, 0xf3, 0x46, 0x11, 0x89, 0x6b, 0x82, 0x1a, 0x68, 0x3b, 0x7a, 0x4e, 0xde, 0xfe, 0x2c, 0x00, 0x00, 0x00, ]), index: 0xfffffffa, }, signature_script: vec![ 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, ], sequence: 2, compute_commit: ComputeCommit::SigopCount(3.into()), }, TransactionInput { previous_outpoint: TransactionOutpoint { transaction_id: TransactionId::from_slice(&[ 0x4b, 0xb0, 0x75, 0x35, 0xdf, 0xd5, 0x8e, 0x0b, 0x3c, 0xd6, 0x4f, 0xd7, 0x15, 0x52, 0x80, 0x87, 0x2a, 0x04, 0x71, 0xbc, 0xf8, 0x30, 0x95, 0x52, 0x6a, 0xce, 0x0e, 0x38, 0xc6, 0x00, 0x00, 0x00, ]), index: 0xfffffffb, }, signature_script: vec![ 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, ], sequence: 4, compute_commit: ComputeCommit::SigopCount(5.into()), }, ], vec![ TransactionOutput { value: 6, script_public_key: script_public_key.clone(), covenant: None }, TransactionOutput { value: 7, script_public_key, covenant: None }, ], 8, SUBNETWORK_ID_NATIVE, 9, vec![ 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f, 0x60, 0x61, 0x62, 0x63, ], ) } fn test_transaction_v1() -> Transaction { let mut tx = test_transaction(); tx.version = 1; // A valid v1 transaction must carry a ComputeBudget mass on every input; // the serializer panics otherwise (that's its contract with the type system). tx.inputs[0].compute_commit = ComputeCommit::ComputeBudget(ComputeBudget(17)); tx.inputs[1].compute_commit = ComputeCommit::ComputeBudget(ComputeBudget(23)); tx.outputs[0].covenant = Some(CovenantBinding::new(1, hashing::tx::payload_digest(&[1, 2, 3]))); tx.finalize(); tx } #[test] fn test_transaction_bincode() { let tx = test_transaction(); let bts = bincode::serialize(&tx).unwrap(); // Captured from the version-aware custom serializer in `tx::serde_impl`. // v0 inputs carry a flat `sig_op_count: u8` (no `ComputeCommit` enum tag) // and v0 outputs have no `covenant` field at all. let expected_bts = vec![ 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 22, 94, 56, 232, 179, 145, 69, 149, 217, 198, 65, 243, 184, 238, 194, 243, 70, 17, 137, 107, 130, 26, 104, 59, 122, 78, 222, 254, 44, 0, 0, 0, 250, 255, 255, 255, 32, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 2, 0, 0, 0, 0, 0, 0, 0, 3, 75, 176, 117, 53, 223, 213, 142, 11, 60, 214, 79, 215, 21, 82, 128, 135, 42, 4, 113, 188, 248, 48, 149, 82, 106, 206, 14, 56, 198, 0, 0, 0, 251, 255, 255, 255, 32, 0, 0, 0, 0, 0, 0, 0, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 4, 0, 0, 0, 0, 0, 0, 0, 5, 2, 0, 0, 0, 0, 0, 0, 0, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 36, 0, 0, 0, 0, 0, 0, 0, 118, 169, 33, 3, 47, 126, 67, 10, 164, 201, 209, 89, 67, 126, 132, 185, 117, 220, 118, 217, 0, 59, 240, 146, 44, 243, 170, 69, 40, 70, 75, 171, 120, 13, 186, 94, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 36, 0, 0, 0, 0, 0, 0, 0, 118, 169, 33, 3, 47, 126, 67, 10, 164, 201, 209, 89, 67, 126, 132, 185, 117, 220, 118, 217, 0, 59, 240, 146, 44, 243, 170, 69, 40, 70, 75, 171, 120, 13, 186, 94, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 0, 0, 0, 0, 0, 0, 0, 100, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 0, 0, 0, 0, 0, 0, 0, 0, 50, 200, 4, 55, 147, 193, 14, 39, 3, 248, 207, 196, 68, 249, 136, 99, 48, 134, 161, 29, 52, 181, 205, 113, 128, 141, 219, 202, 72, 208, 223, 66, ]; assert_eq!(expected_bts, bts); assert_eq!(tx, bincode::deserialize(&bts).unwrap()); } #[test] fn test_transaction_json() { let tx = test_transaction(); let str = serde_json::to_string_pretty(&tx).unwrap(); let expected_str = r#"{ "version": 0, "inputs": [ { "previousOutpoint": { "transactionId": "165e38e8b3914595d9c641f3b8eec2f34611896b821a683b7a4edefe2c000000", "index": 4294967290 }, "signatureScript": "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f", "sequence": 2, "sigOpCount": 3 }, { "previousOutpoint": { "transactionId": "4bb07535dfd58e0b3cd64fd7155280872a0471bcf83095526ace0e38c6000000", "index": 4294967291 }, "signatureScript": "202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f", "sequence": 4, "sigOpCount": 5 } ], "outputs": [ { "value": 6, "scriptPublicKey": "000076a921032f7e430aa4c9d159437e84b975dc76d9003bf0922cf3aa4528464bab780dba5e" }, { "value": 7, "scriptPublicKey": "000076a921032f7e430aa4c9d159437e84b975dc76d9003bf0922cf3aa4528464bab780dba5e" } ], "lockTime": 8, "subnetworkId": "0000000000000000000000000000000000000000", "gas": 9, "payload": "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f404142434445464748494a4b4c4d4e4f505152535455565758595a5b5c5d5e5f60616263", "mass": 0, "id": "32c8043793c10e2703f8cfc444f988633086a11d34b5cd71808ddbca48d0df42" }"#; assert_eq!(expected_str, str); assert_eq!(tx, serde_json::from_str(&str).unwrap()); } #[test] fn test_transaction_v1_json() { let tx = test_transaction_v1(); let str = serde_json::to_string_pretty(&tx).unwrap(); assert!(str.contains("\"computeBudget\": 17")); assert!(str.contains("\"covenant\": {")); assert_eq!(tx, serde_json::from_str(&str).unwrap()); } #[test] fn test_transaction_v1_bincode() { let tx = test_transaction_v1(); let bts = bincode::serialize(&tx).unwrap(); assert_eq!(tx, bincode::deserialize(&bts).unwrap()); } #[test] fn test_transaction_yaml_v0() { let tx = test_transaction(); let s = serde_yaml::to_string(&tx).unwrap(); let expected = r#"inputs: - previousOutpoint: transactionId: 165e38e8b3914595d9c641f3b8eec2f34611896b821a683b7a4edefe2c000000 index: 4294967290 signatureScript: 000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f sequence: 2 sigOpCount: 3 - previousOutpoint: transactionId: 4bb07535dfd58e0b3cd64fd7155280872a0471bcf83095526ace0e38c6000000 index: 4294967291 signatureScript: 202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f sequence: 4 sigOpCount: 5 outputs: - value: 6 scriptPublicKey: 000076a921032f7e430aa4c9d159437e84b975dc76d9003bf0922cf3aa4528464bab780dba5e - value: 7 scriptPublicKey: 000076a921032f7e430aa4c9d159437e84b975dc76d9003bf0922cf3aa4528464bab780dba5e lockTime: 8 subnetworkId: '0000000000000000000000000000000000000000' gas: 9 payload: 000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f404142434445464748494a4b4c4d4e4f505152535455565758595a5b5c5d5e5f60616263 mass: 0 id: 32c8043793c10e2703f8cfc444f988633086a11d34b5cd71808ddbca48d0df42 version: 0 "#; let decoded_actual: Transaction = serde_yaml::from_str(&s).unwrap(); let decoded_expected: Transaction = serde_yaml::from_str(expected).unwrap(); assert_eq!(tx, decoded_actual); assert_eq!(decoded_expected, decoded_actual); } #[test] fn test_transaction_yaml_v1() { let tx = test_transaction_v1(); let s = serde_yaml::to_string(&tx).unwrap(); let expected = r#" inputs: - previousOutpoint: transactionId: 165e38e8b3914595d9c641f3b8eec2f34611896b821a683b7a4edefe2c000000 index: 4294967290 signatureScript: 000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f sequence: 2 computeBudget: 17 - previousOutpoint: transactionId: 4bb07535dfd58e0b3cd64fd7155280872a0471bcf83095526ace0e38c6000000 index: 4294967291 signatureScript: 202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f sequence: 4 computeBudget: 23 outputs: - value: 6 scriptPublicKey: 000076a921032f7e430aa4c9d159437e84b975dc76d9003bf0922cf3aa4528464bab780dba5e covenant: authorizingInput: 1 covenantId: 6d190a52d1ad6f508837acf97d05fa45e579df2c2d9a4a2fe5bc259182b4551b - value: 7 scriptPublicKey: 000076a921032f7e430aa4c9d159437e84b975dc76d9003bf0922cf3aa4528464bab780dba5e covenant: null lockTime: 8 subnetworkId: '0000000000000000000000000000000000000000' gas: 9 payload: 000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f404142434445464748494a4b4c4d4e4f505152535455565758595a5b5c5d5e5f60616263 mass: 0 id: 630ca922552ada815f0da92913c2327190f5c9728a0cae12ce38f9a5dfc19b76 version: 1 "#; let decoded_actual: Transaction = serde_yaml::from_str(&s).unwrap(); let decoded_expected: Transaction = serde_yaml::from_str(expected).unwrap(); assert_eq!(tx, decoded_actual); assert_eq!(decoded_expected, decoded_actual); } #[test] fn test_transaction_toml_v0() { let tx = test_transaction(); let s = toml::to_string(&tx).unwrap(); // Hand-authored fixture with `version` at the end. TOML forbids root scalars // after `[[array-of-tables]]` blocks, so inputs/outputs are written as inline // arrays to keep the `version` key at the root table. let expected = r#"inputs = [ { previousOutpoint = { transactionId = "165e38e8b3914595d9c641f3b8eec2f34611896b821a683b7a4edefe2c000000", index = 4294967290 }, signatureScript = "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f", sequence = 2, sigOpCount = 3 }, { previousOutpoint = { transactionId = "4bb07535dfd58e0b3cd64fd7155280872a0471bcf83095526ace0e38c6000000", index = 4294967291 }, signatureScript = "202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f", sequence = 4, sigOpCount = 5 }, ] outputs = [ { value = 6, scriptPublicKey = "000076a921032f7e430aa4c9d159437e84b975dc76d9003bf0922cf3aa4528464bab780dba5e" }, { value = 7, scriptPublicKey = "000076a921032f7e430aa4c9d159437e84b975dc76d9003bf0922cf3aa4528464bab780dba5e" }, ] lockTime = 8 subnetworkId = "0000000000000000000000000000000000000000" gas = 9 payload = "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f404142434445464748494a4b4c4d4e4f505152535455565758595a5b5c5d5e5f60616263" mass = 0 id = "32c8043793c10e2703f8cfc444f988633086a11d34b5cd71808ddbca48d0df42" version = 0 "#; let decoded_actual: Transaction = toml::from_str(&s).unwrap(); let decoded_expected: Transaction = toml::from_str(expected).unwrap(); assert_eq!(tx, decoded_actual); assert_eq!(decoded_expected, decoded_actual); } #[test] fn test_transaction_toml_v1() { let tx = test_transaction_v1(); let s = toml::to_string(&tx).unwrap(); let expected = r#"inputs = [ { previousOutpoint = { transactionId = "165e38e8b3914595d9c641f3b8eec2f34611896b821a683b7a4edefe2c000000", index = 4294967290 }, signatureScript = "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f", sequence = 2, computeBudget = 17 }, { previousOutpoint = { transactionId = "4bb07535dfd58e0b3cd64fd7155280872a0471bcf83095526ace0e38c6000000", index = 4294967291 }, signatureScript = "202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f", sequence = 4, computeBudget = 23 }, ] outputs = [ { value = 6, scriptPublicKey = "000076a921032f7e430aa4c9d159437e84b975dc76d9003bf0922cf3aa4528464bab780dba5e", covenant = { authorizingInput = 1, covenantId = "6d190a52d1ad6f508837acf97d05fa45e579df2c2d9a4a2fe5bc259182b4551b" } }, { value = 7, scriptPublicKey = "000076a921032f7e430aa4c9d159437e84b975dc76d9003bf0922cf3aa4528464bab780dba5e" }, ] lockTime = 8 subnetworkId = "0000000000000000000000000000000000000000" gas = 9 payload = "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f404142434445464748494a4b4c4d4e4f505152535455565758595a5b5c5d5e5f60616263" mass = 0 id = "630ca922552ada815f0da92913c2327190f5c9728a0cae12ce38f9a5dfc19b76" version = 1 "#; let decoded_actual: Transaction = toml::from_str(&s).unwrap(); let decoded_expected: Transaction = toml::from_str(expected).unwrap(); assert_eq!(tx, decoded_actual); assert_eq!(decoded_expected, decoded_actual); } #[test] fn test_spk_serde_json() { let vec = (0..SCRIPT_VECTOR_SIZE as u8).collect::>(); let spk = ScriptPublicKey::from_vec(0xc0de, vec.clone()); let hex: String = serde_json::to_string(&spk).unwrap(); assert_eq!("\"c0de000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f202122\"", hex); let spk = serde_json::from_str::(&hex).unwrap(); assert_eq!(spk.version, 0xc0de); assert_eq!(spk.script.as_slice(), vec.as_slice()); let result = "00".parse::(); assert!(matches!(result, Err(faster_hex::Error::InvalidLength(2)))); let result = "0000".parse::(); let _empty = ScriptPublicKey { version: 0, script: ScriptVec::new() }; assert!(matches!(result, Ok(_empty))); } #[test] fn test_spk_borsh() { // Tests for ScriptPublicKey Borsh ser/deser since we manually implemented them let spk = ScriptPublicKey::from_vec(12, vec![32; 20]); let bin = borsh::to_vec(&spk).unwrap(); let spk2: ScriptPublicKey = BorshDeserialize::try_from_slice(&bin).unwrap(); assert_eq!(spk, spk2); let spk = ScriptPublicKey::from_vec(55455, vec![11; 200]); let bin = borsh::to_vec(&spk).unwrap(); let spk2: ScriptPublicKey = BorshDeserialize::try_from_slice(&bin).unwrap(); assert_eq!(spk, spk2); } fn tx_for_genesis_covenant_population(num_inputs: usize, num_outputs: usize) -> Transaction { let inputs = (0..num_inputs) .map(|i| TransactionInput::new(TransactionOutpoint::new((i as u64).into(), 0), vec![], 0, 0)) .collect::>(); let outputs = (0..num_outputs).map(|_| TransactionOutput::new(100, Default::default())).collect::>(); Transaction::new(1, inputs, outputs, 0, SUBNETWORK_ID_NATIVE, 0, vec![]) } #[test] fn test_populate_genesis_covenants() { // Success case let mut tx = tx_for_genesis_covenant_population(1, 8); let group_a_outputs = [1u32, 3, 7]; let group_b_outputs = [2u32, 4, 5]; let expected_group_a = hashing::covenant_id::covenant_id( tx.inputs[0].previous_outpoint, group_a_outputs.into_iter().map(|i| (i, &tx.outputs[i as usize])), ); let expected_group_b = hashing::covenant_id::covenant_id( tx.inputs[0].previous_outpoint, group_b_outputs.into_iter().map(|i| (i, &tx.outputs[i as usize])), ); tx.populate_genesis_covenants(&[GenesisCovenantGroup::new(0, vec![1, 3, 7]), GenesisCovenantGroup::new(0, vec![2, 4, 5])]) .unwrap(); for &i in &[1u32, 3, 7] { assert_eq!(tx.outputs[i as usize].covenant, Some(CovenantBinding::new(0, expected_group_a))); } for &i in &[2u32, 4, 5] { assert_eq!(tx.outputs[i as usize].covenant, Some(CovenantBinding::new(0, expected_group_b))); } assert!(tx.outputs[0].covenant.is_none()); assert!(tx.outputs[6].covenant.is_none()); // Error cases let mut already_populated_tx = tx_for_genesis_covenant_population(1, 2); already_populated_tx.outputs[1].covenant = Some(CovenantBinding::new(0, Hash::from_u64_word(7))); let cases = vec![ ( tx_for_genesis_covenant_population(1, 1), vec![GenesisCovenantGroup::new(1, vec![0])], PopulateGenesisCovenantsError::NoSuchInput(1, 1), ), ( tx_for_genesis_covenant_population(1, 1), vec![GenesisCovenantGroup::new(0, vec![1])], PopulateGenesisCovenantsError::NoSuchOutput(1, 1), ), ( tx_for_genesis_covenant_population(1, 1), vec![GenesisCovenantGroup::new(0, vec![])], PopulateGenesisCovenantsError::EmptyOutputs, ), ( tx_for_genesis_covenant_population(1, 4), vec![GenesisCovenantGroup::new(0, vec![1, 3, 2])], PopulateGenesisCovenantsError::OutputsNotOrdered, ), ( tx_for_genesis_covenant_population(1, 5), vec![GenesisCovenantGroup::new(0, vec![1, 3]), GenesisCovenantGroup::new(0, vec![2, 3])], PopulateGenesisCovenantsError::OutputsNotDisjoint(3), ), ( already_populated_tx, vec![GenesisCovenantGroup::new(0, vec![1])], PopulateGenesisCovenantsError::CovenantAlreadyPopulated(1), ), ]; for (mut tx, groups, expected_err) in cases { let err = tx.populate_genesis_covenants(&groups).unwrap_err(); assert_eq!(err, expected_err); } } #[test] fn json_transaction_deserialize_accepts_fields_before_version() { let tx = Transaction::new( 1, vec![TransactionInput::new_with_compute_budget( TransactionOutpoint::new(Hash::from_bytes([0x11; 32]), 0), vec![0xaa, 0xbb], 42, 7, )], vec![TransactionOutput::with_covenant( 100, ScriptPublicKey::new(0, vec![0x51].into()), Some(CovenantBinding::new(0, Hash::from_bytes([0x22; 32]))), )], 123, SUBNETWORK_ID_NATIVE, 0, vec![0xcc], ); let value = serde_json::to_value(&tx).unwrap(); let reordered = serde_json::json!({ "inputs": value["inputs"], "outputs": value["outputs"], "version": value["version"], "lockTime": value["lockTime"], "subnetworkId": value["subnetworkId"], "gas": value["gas"], "payload": value["payload"], "mass": value["mass"], "id": value["id"], }); let decoded: Transaction = serde_json::from_value(reordered).expect("field order must not affect transaction JSON"); assert_eq!(decoded, tx); } // use wasm_bindgen_test::wasm_bindgen_test; // #[wasm_bindgen_test] // pub fn test_wasm_serde_spk_constructor() { // let str = "kaspa:qpauqsvk7yf9unexwmxsnmg547mhyga37csh0kj53q6xxgl24ydxjsgzthw5j"; // let a = Address::constructor(str); // let value = to_value(&a).unwrap(); // // assert_eq!(JsValue::from_str("string"), value.js_typeof()); // assert_eq!(value, JsValue::from_str(str)); // assert_eq!(a, from_value(value).unwrap()); // } // // #[wasm_bindgen_test] // pub fn test_wasm_js_serde_spk_object() { // let expected = Address::constructor("kaspa:qpauqsvk7yf9unexwmxsnmg547mhyga37csh0kj53q6xxgl24ydxjsgzthw5j"); // // use web_sys::console; // console::log_4(&"address: ".into(), &expected.version().into(), &expected.prefix().into(), &expected.payload().into()); // // let obj = Object::new(); // obj.set("version", &JsValue::from_str("PubKey")).unwrap(); // obj.set("prefix", &JsValue::from_str("kaspa")).unwrap(); // obj.set("payload", &JsValue::from_str("qpauqsvk7yf9unexwmxsnmg547mhyga37csh0kj53q6xxgl24ydxjsgzthw5j")).unwrap(); // // assert_eq!(JsValue::from_str("object"), obj.js_typeof()); // // let obj_js = obj.into_js_result().unwrap(); // let actual = from_value(obj_js).unwrap(); // assert_eq!(expected, actual); // } // // #[wasm_bindgen_test] // pub fn test_wasm_serde_spk_object() { // use wasm_bindgen::convert::IntoWasmAbi; // // let expected = Address::constructor("kaspa:qpauqsvk7yf9unexwmxsnmg547mhyga37csh0kj53q6xxgl24ydxjsgzthw5j"); // let wasm_js_value: JsValue = expected.clone().into_abi().into(); // // // use web_sys::console; // // console::log_4(&"address: ".into(), &expected.version().into(), &expected.prefix().into(), &expected.payload().into()); // // let actual = from_value(wasm_js_value).unwrap(); // assert_eq!(expected, actual); // } }