Skip to main content

smplx_sdk_test/transaction/
partial_input.rs

1use std::fmt;
2use std::sync::Arc;
3
4use elements_miniscript::bitcoin::bip32::DerivationPath;
5
6use simplicityhl::elements::confidential::{Asset, Value};
7use simplicityhl::elements::pset::Input;
8use simplicityhl::elements::{AssetId, LockTime, OutPoint, Sequence, TxOut, TxOutSecrets, Txid};
9use simplicityhl::simplicity::hashes::Hash;
10
11use crate::program::ProgramTrait;
12use crate::program::WitnessTrait;
13use crate::utils::tagged_hash;
14
15use super::UTXO;
16
17/// Derives the 32-byte message to sign from the input's `sighash_all`.
18pub type SigMessageFn = Arc<dyn Fn([u8; 32]) -> [u8; 32] + Send + Sync>;
19
20/// Defines the 32-byte message a witness signature actually covers.
21#[derive(Clone)]
22pub enum SigMessage {
23    /// Sign `sighash_all` itself.
24    Sighash,
25    /// Sign the BIP-340 tagged hash `sha256(sha256(tag) || sha256(tag) || sighash_all)`.
26    Tagged(String),
27    /// Sign whatever the closure derives from `sighash_all`.
28    Custom(SigMessageFn),
29}
30
31/// Defines the type of signature required for an input.
32#[derive(Debug, Clone)]
33pub enum RequiredSignature {
34    /// No signature is required.
35    None,
36    /// A standard Native ECDSA (WPKH) signature is required.
37    NativeEcdsa,
38    /// A generic witness payload associated with an external name.
39    Witness(String),
40    /// A witness payload requiring traversal through a specified path hierarchy.
41    WitnessWithPath(String, Vec<String>),
42    /// Like `WitnessWithPath`, but over a message derived from `sighash_all`.
43    WitnessWithMessage(String, Vec<String>, SigMessage),
44}
45
46impl SigMessage {
47    /// Derives the message to sign from the input's `sighash_all`.
48    #[must_use]
49    pub fn digest(&self, sighash: [u8; 32]) -> [u8; 32] {
50        match self {
51            Self::Sighash => sighash,
52            Self::Tagged(tag) => tagged_hash(tag, &sighash).to_byte_array(),
53            Self::Custom(derive) => derive(sighash),
54        }
55    }
56}
57
58impl fmt::Debug for SigMessage {
59    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
60        match self {
61            Self::Sighash => f.write_str("Sighash"),
62            Self::Tagged(tag) => f.debug_tuple("Tagged").field(tag).finish(),
63            Self::Custom(_) => f.write_str("Custom(<closure>)"),
64        }
65    }
66}
67
68impl RequiredSignature {
69    /// Creates a `WitnessWithPath` requirement using an iterator of path segments.
70    pub fn witness_with_path<I>(name: &str, path: I) -> Self
71    where
72        I: IntoIterator,
73        I::Item: AsRef<str>,
74    {
75        RequiredSignature::WitnessWithPath(
76            name.to_string(),
77            path.into_iter().map(|s| s.as_ref().to_string()).collect(),
78        )
79    }
80
81    /// Creates a `WitnessWithMessage` requirement using an iterator of path segments.
82    pub fn witness_with_message<I>(name: &str, path: I, message: SigMessage) -> Self
83    where
84        I: IntoIterator,
85        I::Item: AsRef<str>,
86    {
87        RequiredSignature::WitnessWithMessage(
88            name.to_string(),
89            path.into_iter().map(|s| s.as_ref().to_string()).collect(),
90            message,
91        )
92    }
93
94    /// Creates a requirement for a BIP-340 tagged signature over `tag` and `sighash_all`.
95    pub fn witness_tagged<I>(name: &str, path: I, tag: &str) -> Self
96    where
97        I: IntoIterator,
98        I::Item: AsRef<str>,
99    {
100        Self::witness_with_message(name, path, SigMessage::Tagged(tag.to_string()))
101    }
102}
103
104/// Represents partially prepared input data for Elements transactions.
105#[derive(Debug, Clone)]
106pub struct PartialInput {
107    /// The transaction ID containing the target UTXO being spent.
108    pub witness_txid: Txid,
109    /// The output index of the UTXO within the transaction being spent.
110    pub witness_output_index: u32,
111    /// The native transaction output corresponding to the targeted UTXO.
112    pub witness_utxo: TxOut,
113    /// The sequence number indicating transaction replaceability or relative timelocking.
114    pub sequence: Sequence,
115    /// Absolute timelock criteria enforced against the input.
116    pub locktime: LockTime,
117    /// The explicit amount value in Satoshis for the input, if available.
118    /// Note: if UTXO is explicit, `amount` and `asset` are `Some`.
119    pub amount: Option<u64>,
120    /// The explicit `AssetId` being spent by the input, if available.
121    pub asset: Option<AssetId>,
122    /// Optional blinding secrets mapping values and asset states into confidential outputs.
123    /// Note: if UTXO is confidential, `secrets` are `Some`.
124    pub secrets: Option<TxOutSecrets>,
125    /// Derivation path of the key that can spend this input, relative to the account path.
126    ///
127    /// `None` means the signer's default path. A wallet whose UTXOs sit across many
128    /// derivation indices must set this per input, or the signer will sign with the wrong key.
129    pub derivation_path: Option<DerivationPath>,
130}
131
132/// Represents an input that runs a specific Simplicity program with an associated witness.
133#[derive(Clone)]
134pub struct ProgramInput {
135    /// The compiled program interface associated with the input.
136    pub program: Box<dyn ProgramTrait>,
137    /// The witness values required to satisfy the program.
138    pub witness: Box<dyn WitnessTrait>,
139}
140
141/// Represents an input designated for asset issuance or reissuance.
142#[derive(Clone, Debug)]
143pub enum IssuanceInput {
144    /// Represents a completely new asset issuance.
145    Issuance {
146        /// The initial issuance amount for the asset.
147        issuance_amount: u64,
148        /// The initial issuance amount for the inflation key.
149        inflation_amount: u64,
150        /// The contract hash or entropy used to derive the generated `AssetId`.
151        asset_entropy: [u8; 32],
152    },
153    /// Represents a reissuance of an existing asset.
154    Reissuance {
155        /// The amount of the generated asset to issue.
156        issuance_amount: u64,
157        /// The original asset's entropy used to tie this reissuance back to the parent issuance.
158        asset_entropy: [u8; 32],
159    },
160}
161
162impl PartialInput {
163    /// Creates a new `PartialInput` from an existing `UTXO`.
164    /// Extracts explicit value and asset amounts if available.
165    #[must_use]
166    pub fn new(utxo: UTXO) -> Self {
167        let amount = match utxo.txout.value {
168            Value::Explicit(value) => Some(value),
169            _ => None,
170        };
171        let asset = match utxo.txout.asset {
172            Asset::Explicit(asset) => Some(asset),
173            _ => None,
174        };
175
176        Self {
177            witness_txid: utxo.outpoint.txid,
178            witness_output_index: utxo.outpoint.vout,
179            witness_utxo: utxo.txout,
180            sequence: Sequence::default(),
181            locktime: LockTime::ZERO,
182            amount,
183            asset,
184            secrets: utxo.secrets,
185            derivation_path: None,
186        }
187    }
188
189    /// Sets the derivation path, relative to the account path, of the key that spends this input.
190    ///
191    /// Relative means it is appended to `m/84h/{coin}h/0h`.
192    /// Should be in the form of "m/n".
193    #[must_use]
194    pub fn with_derivation_path(mut self, derivation_path: DerivationPath) -> Self {
195        self.derivation_path = Some(derivation_path);
196
197        self
198    }
199
200    /// Sets a specific `Sequence` for the input.
201    #[must_use]
202    pub fn with_sequence(mut self, sequence: Sequence) -> Self {
203        self.sequence = sequence;
204
205        self
206    }
207
208    /// Sets a specific `LockTime` for the input.
209    #[must_use]
210    pub fn with_locktime(mut self, locktime: LockTime) -> Self {
211        self.locktime = locktime;
212
213        self
214    }
215
216    /// Returns the `OutPoint` corresponding to this input.
217    #[must_use]
218    pub fn outpoint(&self) -> OutPoint {
219        OutPoint {
220            txid: self.witness_txid,
221            vout: self.witness_output_index,
222        }
223    }
224
225    /// Converts this `PartialInput` into a fully formed PSET `Input`.
226    #[must_use]
227    pub fn to_input(&self) -> Input {
228        let time_locktime = match self.locktime {
229            LockTime::Seconds(value) => Some(value),
230            LockTime::Blocks(_) => None,
231        };
232        let height_locktime = match self.locktime {
233            LockTime::Blocks(value) if value.to_consensus_u32() > 0 => Some(value),
234            LockTime::Blocks(_) | LockTime::Seconds(_) => None,
235        };
236
237        Input {
238            previous_txid: self.witness_txid,
239            previous_output_index: self.witness_output_index,
240            witness_utxo: Some(self.witness_utxo.clone()),
241            sequence: Some(self.sequence),
242            required_time_locktime: time_locktime,
243            required_height_locktime: height_locktime,
244            amount: self.amount,
245            asset: self.asset,
246            ..Default::default()
247        }
248    }
249}
250
251impl ProgramInput {
252    /// Creates a new `ProgramInput` from a `ProgramTrait` and its associated `WitnessTrait`.
253    #[must_use]
254    pub fn new(program: Box<dyn ProgramTrait>, witness: Box<dyn WitnessTrait>) -> Self {
255        Self { program, witness }
256    }
257}
258
259impl IssuanceInput {
260    /// Creates a new `IssuanceInput` for creating a new asset issuance.
261    #[must_use]
262    pub fn new_issuance(issuance_amount: u64, inflation_amount: u64, asset_entropy: [u8; 32]) -> Self {
263        Self::Issuance {
264            issuance_amount,
265            inflation_amount,
266            asset_entropy,
267        }
268    }
269
270    /// Creates a new `IssuanceInput` for reissuing an existing asset.
271    #[must_use]
272    pub fn new_reissuance(issuance_amount: u64, asset_entropy: [u8; 32]) -> Self {
273        Self::Reissuance {
274            issuance_amount,
275            asset_entropy,
276        }
277    }
278
279    /// Converts this `IssuanceInput` into a partial PSET `Input` configured for issuance or reissuance.
280    #[must_use]
281    pub fn to_input(&self) -> Input {
282        let (issuance_amount, asset_entropy, inflation_amount) = match self {
283            Self::Issuance {
284                issuance_amount,
285                inflation_amount,
286                asset_entropy,
287            } => {
288                let inflation_amount = (*inflation_amount > 0).then_some(*inflation_amount);
289
290                (*issuance_amount, *asset_entropy, inflation_amount)
291            }
292            Self::Reissuance {
293                issuance_amount,
294                asset_entropy,
295            } => (*issuance_amount, *asset_entropy, None),
296        };
297
298        Input {
299            issuance_value_amount: Some(issuance_amount),
300            issuance_asset_entropy: Some(asset_entropy),
301            issuance_inflation_keys: inflation_amount,
302            blinded_issuance: Some(0x00),
303            ..Default::default()
304        }
305    }
306}
307
308#[cfg(test)]
309mod tests {
310    use super::*;
311
312    const SIGHASH: [u8; 32] = [0x11; 32];
313
314    #[test]
315    fn sighash_message_is_the_sighash() {
316        assert_eq!(SigMessage::Sighash.digest(SIGHASH), SIGHASH);
317    }
318
319    #[test]
320    fn tagged_message_is_the_tagged_hash() {
321        assert_eq!(
322            SigMessage::Tagged("SimplexTag".to_string()).digest(SIGHASH),
323            tagged_hash("SimplexTag", &SIGHASH).to_byte_array()
324        );
325    }
326
327    #[test]
328    fn custom_message_receives_the_sighash() {
329        let message = SigMessage::Custom(Arc::new(|sighash: [u8; 32]| {
330            let mut digest = sighash;
331            digest[0] ^= 0xff;
332
333            digest
334        }));
335
336        let mut expected = SIGHASH;
337        expected[0] ^= 0xff;
338
339        assert_eq!(message.digest(SIGHASH), expected);
340    }
341
342    #[test]
343    fn tagged_constructor_builds_a_tagged_message() {
344        let required = RequiredSignature::witness_tagged("SIGNATURE", ["Left", "1"], "SimplexTag");
345
346        let RequiredSignature::WitnessWithMessage(name, path, message) = required else {
347            panic!("expected a WitnessWithMessage requirement");
348        };
349
350        assert_eq!(name, "SIGNATURE");
351        assert_eq!(path, ["Left", "1"]);
352        assert_eq!(
353            message.digest(SIGHASH),
354            tagged_hash("SimplexTag", &SIGHASH).to_byte_array()
355        );
356    }
357}