Skip to main content

smplx_sdk_test/signer/
core.rs

1use std::collections::HashMap;
2#[cfg(feature = "provider")]
3use std::collections::HashSet;
4use std::str::FromStr;
5use std::sync::Arc;
6
7use simplicityhl::Value;
8use simplicityhl::WitnessValues;
9use simplicityhl::elements::pset::PartiallySignedTransaction;
10use simplicityhl::elements::secp256k1_zkp::{All, Keypair, Message, Secp256k1, ecdsa, schnorr};
11use simplicityhl::elements::{Address, LockTime, Script, Sequence, Transaction};
12#[cfg(feature = "provider")]
13use simplicityhl::elements::{AssetId, OutPoint, Txid};
14use simplicityhl::simplicity::bitcoin::XOnlyPublicKey;
15use simplicityhl::simplicity::hashes::Hash;
16use simplicityhl::str::WitnessName;
17use simplicityhl::value::ValueConstructible;
18
19use bip39::Mnemonic;
20use bip39::rand::thread_rng;
21
22use elements_miniscript::{
23    ConfidentialDescriptor, Descriptor, DescriptorPublicKey,
24    bitcoin::{PrivateKey, PublicKey, bip32::DerivationPath},
25    elements::{
26        EcdsaSighashType,
27        bitcoin::bip32::{Fingerprint, Xpriv, Xpub},
28        sighash::SighashCache,
29    },
30    elementssig_to_rawsig,
31    psbt::PsbtExt,
32    slip77::MasterBlindingKey,
33};
34
35use crate::constants::MIN_FEE;
36use crate::program::ProgramTrait;
37use crate::program::logger::ProgramLogger;
38#[cfg(feature = "provider")]
39use crate::provider::ProviderTrait;
40use crate::provider::SimplicityNetwork;
41use crate::signer::wtns_injector::WtnsInjector;
42use crate::transaction::{ChangeOutput, FinalTransaction, PartialOutput, RequiredSignature, SigMessage};
43#[cfg(feature = "provider")]
44use crate::transaction::{PartialInput, TxReceipt, UTXO};
45
46use super::error::SignerError;
47
48/// A placeholder dummy fee amount used during transaction estimation.
49pub const PLACEHOLDER_FEE: u64 = 1;
50
51/// Common signing interface spanning over standard explicit inputs and Simplicity programs.
52pub trait SignerTrait {
53    /// Generates a Schnorr signature to satisfy a target Simplicity program input.
54    ///
55    /// # Errors
56    /// Returns a `SignerError` if the elements environment fails to build or if the message digest fails to construct.
57    fn sign_program(
58        &self,
59        pst: &PartiallySignedTransaction,
60        program: &dyn ProgramTrait,
61        input_index: usize,
62        network: &SimplicityNetwork,
63        derivation_path: Option<&DerivationPath>,
64        message: &SigMessage,
65    ) -> Result<schnorr::Signature, SignerError>;
66
67    /// Generates an ECDSA signature to spend a standard transaction input.
68    ///
69    /// # Errors
70    /// Returns a `SignerError` if the transaction formatting or sighash msg extraction fails.
71    fn sign_input(
72        &self,
73        pst: &PartiallySignedTransaction,
74        input_index: usize,
75        derivation_path: Option<&DerivationPath>,
76    ) -> Result<(PublicKey, ecdsa::Signature), SignerError>;
77}
78
79/// Core interface responsible for managing keys, interfacing with the blockchain provider,
80/// assembling descriptors, estimating fees, and finalizing/signing transactions.
81///
82/// Without the `provider` feature the signer has no blockchain access: it can assemble,
83/// blind, sign and finalize a transaction it is handed, but it cannot discover UTXOs,
84/// look up a fee rate, or broadcast.
85pub struct Signer {
86    mnemonic: Mnemonic,
87    xprv: Xpriv,
88    #[cfg(feature = "provider")]
89    provider: Option<Box<dyn ProviderTrait>>,
90    network: SimplicityNetwork,
91    secp: Secp256k1<All>,
92}
93
94impl SignerTrait for Signer {
95    fn sign_program(
96        &self,
97        pst: &PartiallySignedTransaction,
98        program: &dyn ProgramTrait,
99        input_index: usize,
100        network: &SimplicityNetwork,
101        derivation_path: Option<&DerivationPath>,
102        message: &SigMessage,
103    ) -> Result<schnorr::Signature, SignerError> {
104        let env = program.get_env(pst, input_index, network)?;
105        let sighash = env.c_tx_env().sighash_all().to_byte_array();
106        let msg = Message::from_digest(message.digest(sighash));
107
108        let private_key = self.get_private_key_at(derivation_path);
109        let keypair = Keypair::from_secret_key(&self.secp, &private_key.inner);
110
111        Ok(self.secp.sign_schnorr(&msg, &keypair))
112    }
113
114    fn sign_input(
115        &self,
116        pst: &PartiallySignedTransaction,
117        input_index: usize,
118        derivation_path: Option<&DerivationPath>,
119    ) -> Result<(PublicKey, ecdsa::Signature), SignerError> {
120        let tx = pst.extract_tx()?;
121
122        let mut sighash_cache = SighashCache::new(&tx);
123        let genesis_hash = elements_miniscript::elements::BlockHash::all_zeros();
124
125        let message = pst
126            .sighash_msg(input_index, &mut sighash_cache, None, genesis_hash)?
127            .to_secp_msg();
128
129        let private_key = self.get_private_key_at(derivation_path);
130        let public_key = private_key.public_key(&self.secp);
131
132        let signature = self.secp.sign_ecdsa_low_r(&message, &private_key.inner);
133
134        Ok((public_key, signature))
135    }
136}
137
138enum Estimate {
139    Success(Transaction, u64),
140    Failure(u64),
141}
142
143// TODO: refactor descriptors to be a standalone object to specify custom derivation paths.
144impl Signer {
145    /// Creates a new `Signer` instance seeded from the provided mnemonic and paired with the specified provider.
146    ///
147    /// # Panics
148    /// Panics if the mnemonic fails to parse, or if deriving the master private key fails.
149    #[cfg(feature = "provider")]
150    #[must_use]
151    pub fn new(mnemonic: &str, provider: Box<dyn ProviderTrait>) -> Self {
152        let network = *provider.get_network();
153        let mut signer = Self::from_mnemonic(mnemonic, network);
154
155        signer.provider = Some(provider);
156
157        signer
158    }
159
160    /// Creates a `Signer` from a mnemonic and an explicit network, with no blockchain access.
161    ///
162    /// This is the constructor a host with its own networking and its own key custody should use.
163    ///
164    /// # Panics
165    /// Panics if the mnemonic fails to parse, or if deriving the master private key fails.
166    #[must_use]
167    pub fn from_mnemonic(mnemonic: &str, network: SimplicityNetwork) -> Self {
168        let secp = Secp256k1::new();
169        let mnemonic: Mnemonic = mnemonic
170            .parse()
171            .map_err(|e: bip39::Error| SignerError::Mnemonic(e.to_string()))
172            .unwrap();
173
174        let seed = mnemonic.to_seed("");
175        let xprv = Xpriv::new_master(network, &seed).unwrap();
176
177        Self {
178            mnemonic,
179            xprv,
180            #[cfg(feature = "provider")]
181            provider: None,
182            network,
183            secp,
184        }
185    }
186
187    /// Composes, funds, and broadcasts a standard network transaction sending the specified value of the primary policy asset.
188    ///
189    /// # Errors
190    /// Returns a `SignerError` if compiling the inputs fails, there are insufficient funds/fees, or broadcast is rejected.
191    // TODO: add an ability to send arbitrary assets
192    #[cfg(feature = "provider")]
193    pub fn send(&self, to: Script, amount: u64) -> Result<TxReceipt<'_>, SignerError> {
194        let mut ft = FinalTransaction::new();
195
196        ft.add_output(PartialOutput::new(to, amount, self.network.policy_asset()));
197
198        let (tx, _fee) = self.finalize(&ft)?;
199
200        Ok(self.get_provider()?.broadcast_transaction(&tx)?)
201    }
202
203    /// Evaluates, funds, and broadcasts an already assembled `FinalTransaction`.
204    ///
205    /// # Errors
206    /// Returns a `SignerError` if finalizing the payload fails or if the network rejects the broadcast.
207    #[cfg(feature = "provider")]
208    pub fn broadcast(&self, tx: &FinalTransaction) -> Result<TxReceipt<'_>, SignerError> {
209        let (tx, _fee) = self.finalize(tx)?;
210
211        Ok(self.get_provider()?.broadcast_transaction(&tx)?)
212    }
213
214    /// Evaluates the input components of a `FinalTransaction`, iteratively selecting available wallet UTXOs to cover outputs and estimated fees.
215    ///
216    /// # Errors
217    /// Returns a `SignerError` if the wallet contains insufficient funds to satisfy output values and target fee rates.
218    #[cfg(feature = "provider")]
219    pub fn finalize(&self, tx: &FinalTransaction) -> Result<(Transaction, u64), SignerError> {
220        let mut signer_utxos = self.get_utxos_asset(self.network.policy_asset())?;
221        let mut set = HashSet::new();
222
223        for input in tx.inputs() {
224            set.insert(OutPoint {
225                txid: input.partial_input.witness_txid,
226                vout: input.partial_input.witness_output_index,
227            });
228        }
229
230        signer_utxos.retain(|utxo| !set.contains(&utxo.outpoint));
231
232        // Descending sort of both confidential and explicit utxos
233        signer_utxos.sort_by_key(|utxo| std::cmp::Reverse(utxo.amount()));
234
235        let mut fee_tx = tx.clone();
236        let mut curr_fee = MIN_FEE;
237        let fee_rate = self.get_provider()?.fetch_fee_rate(1)?;
238
239        let try_estimate = |fee_tx: &FinalTransaction, policy_amount_delta: i64, curr_fee: &mut u64| match self
240            .estimate_tx(fee_tx.clone(), fee_rate, policy_amount_delta.cast_unsigned())
241        {
242            Ok(Estimate::Success(tx, fee)) => {
243                ProgramLogger::flush_logs();
244                Ok(Some((tx, fee)))
245            }
246            Ok(Estimate::Failure(required_fee)) => {
247                *curr_fee = required_fee;
248                Ok(None)
249            }
250            Err(err) => {
251                ProgramLogger::flush_logs();
252                Err(err)
253            }
254        };
255
256        for utxo in signer_utxos {
257            let policy_amount_delta = fee_tx.calculate_fee_delta(&self.network);
258
259            if policy_amount_delta >= curr_fee.cast_signed()
260                && let Some(result) = try_estimate(&fee_tx, policy_amount_delta, &mut curr_fee)?
261            {
262                return Ok(result);
263            }
264
265            // IMPORTANT: must be added to the end of the transaction.
266            // Otherwise, the logging of execution traces will be broken
267            fee_tx.add_input(PartialInput::new(utxo), RequiredSignature::NativeEcdsa);
268        }
269
270        // need to try one more time after the loop
271        let policy_amount_delta = fee_tx.calculate_fee_delta(&self.network);
272
273        if policy_amount_delta >= curr_fee.cast_signed()
274            && let Some(result) = try_estimate(&fee_tx, policy_amount_delta, &mut curr_fee)?
275        {
276            return Ok(result);
277        }
278
279        Err(SignerError::NotEnoughFunds(curr_fee))
280    }
281
282    /// Verifies and finalizes a transaction against a strict target confirmation window (in blocks).
283    /// This function also assumes that the transaction already includes the coin selection.
284    ///
285    /// # Errors
286    /// Returns a `SignerError` if the assembled inputs do not meet dust limits or fail to cover the
287    /// dynamically estimated required fee.
288    pub fn finalize_strict(&self, tx: &FinalTransaction, fee_rate: f32) -> Result<(Transaction, u64), SignerError> {
289        let policy_amount_delta = tx.calculate_fee_delta(&self.network);
290
291        if policy_amount_delta < MIN_FEE.cast_signed() {
292            return Err(SignerError::DustAmount(policy_amount_delta));
293        }
294
295        // policy_amount_delta will be > 0
296        match self.estimate_tx(tx.clone(), fee_rate, policy_amount_delta.cast_unsigned())? {
297            Estimate::Success(tx, fee) => {
298                ProgramLogger::flush_logs();
299                Ok((tx, fee))
300            }
301            Estimate::Failure(required_fee) => Err(SignerError::NotEnoughFeeAmount(policy_amount_delta, required_fee)),
302        }
303    }
304
305    /// Reports what an assembled transaction would cost in fees at the given rate.
306    ///
307    /// # Errors
308    /// Returns a `SignerError` if the transaction cannot be signed.
309    pub fn estimate_fee(&self, tx: &FinalTransaction, fee_rate: f32) -> Result<u64, SignerError> {
310        let available_delta = tx.calculate_fee_delta(&self.network).max(0).cast_unsigned();
311        let estimate = self.estimate_tx(tx.clone(), fee_rate, available_delta);
312
313        ProgramLogger::flush_logs();
314
315        Ok(match estimate? {
316            Estimate::Success(_, fee) | Estimate::Failure(fee) => fee,
317        })
318    }
319
320    /// Returns a reference to the active configured network provider.
321    ///
322    /// # Errors
323    /// Returns `ProviderUnavailable` when the signer was built without one.
324    #[cfg(feature = "provider")]
325    pub fn get_provider(&self) -> Result<&dyn ProviderTrait, SignerError> {
326        self.provider.as_deref().ok_or(SignerError::ProviderUnavailable)
327    }
328
329    /// Returns the confidential elements address matching the local wallet logic.
330    ///
331    /// # Panics
332    /// Panics if the SLIP77 descriptor cannot be generated or parsed, or if address derivation fails.
333    #[must_use]
334    pub fn get_confidential_address(&self) -> Address {
335        let mut descriptor =
336            ConfidentialDescriptor::<DescriptorPublicKey>::from_str(&self.get_slip77_descriptor().unwrap())
337                .map_err(|e| SignerError::Slip77Descriptor(e.to_string()))
338                .unwrap();
339
340        // Confidential descriptor doesn't support multipath
341        descriptor.descriptor = descriptor.descriptor.into_single_descriptors().unwrap()[0].clone();
342
343        descriptor
344            .at_derivation_index(0)
345            .unwrap()
346            .address(&self.secp, self.network.address_params())
347            .unwrap()
348    }
349
350    /// Returns the standard unblinded address matching the local wallet logic.
351    ///
352    /// # Panics
353    /// Panics if the WPKH descriptor cannot be generated or parsed, or if address derivation fails.
354    #[must_use]
355    pub fn get_address(&self) -> Address {
356        let descriptor = Descriptor::<DescriptorPublicKey>::from_str(&self.get_wpkh_descriptor().unwrap())
357            .map_err(|e| SignerError::WpkhDescriptor(e.to_string()))
358            .unwrap();
359
360        descriptor.into_single_descriptors().unwrap()[0]
361            .at_derivation_index(0)
362            .unwrap()
363            .address(self.network.address_params())
364            .unwrap()
365    }
366
367    /// Iterates against the network provider to select and unblind all known UTXOs.
368    ///
369    /// # Errors
370    /// Returns a `SignerError` if querying the network or unblinding operations fail.
371    #[cfg(feature = "provider")]
372    pub fn get_utxos(&self) -> Result<Vec<UTXO>, SignerError> {
373        self.get_utxos_filter(&|_| true, &|_| true)
374    }
375
376    /// Finds all known UTXOs belonging to the specific `AssetId`.
377    ///
378    /// # Errors
379    /// Returns a `SignerError` if network interaction or confidential output decryption fails.
380    #[cfg(feature = "provider")]
381    pub fn get_utxos_asset(&self, asset: AssetId) -> Result<Vec<UTXO>, SignerError> {
382        self.get_utxos_filter(&|utxo| utxo.asset() == asset, &|utxo| utxo.asset() == asset)
383    }
384
385    /// Finds all known UTXOs deriving from a targeted `Txid`.
386    ///
387    /// # Errors
388    /// Returns a `SignerError` if querying the network fails.
389    // TODO: can this be optimized to not populate TxOuts that are filtered out?
390    #[cfg(feature = "provider")]
391    pub fn get_utxos_txid(&self, txid: Txid) -> Result<Vec<UTXO>, SignerError> {
392        self.get_utxos_filter(&|utxo| utxo.outpoint.txid == txid, &|utxo| utxo.outpoint.txid == txid)
393    }
394
395    /// Maps UTXOs retrieved from the provider through arbitrary functional filters.
396    /// Separate filtering criteria apply explicitly vs confidentially.
397    ///
398    /// # Errors
399    /// Returns a `SignerError` if retrieving remote outputs or executing confidential node unblinding throws an error.
400    #[cfg(feature = "provider")]
401    pub fn get_utxos_filter(
402        &self,
403        explicit_filter: &dyn Fn(&UTXO) -> bool,
404        confidential_filter: &dyn Fn(&UTXO) -> bool,
405    ) -> Result<Vec<UTXO>, SignerError> {
406        // Fetch explicit and confidential utxos
407        let mut all_utxos = self
408            .get_provider()?
409            .fetch_address_utxos(&self.get_confidential_address())?;
410
411        // Filter out only confidential utxos and unblind them
412        let mut confidential_utxos = self.unblind(
413            all_utxos
414                .iter()
415                .filter(|utxo| utxo.txout.value.is_confidential())
416                .cloned()
417                .collect(),
418        )?;
419        // Leave only explicit utxos
420        all_utxos.retain(|utxo| !utxo.txout.value.is_confidential());
421
422        all_utxos.retain(explicit_filter);
423        confidential_utxos.retain(confidential_filter);
424
425        // Push unblinded utxos to explicit ones
426        all_utxos.extend(confidential_utxos);
427
428        Ok(all_utxos)
429    }
430
431    /// Derives the X-Only public key specifically used for Schnorr and Taproot structures.
432    #[must_use]
433    pub fn get_schnorr_public_key(&self) -> XOnlyPublicKey {
434        let private_key = self.get_private_key();
435        let keypair = Keypair::from_secret_key(&self.secp, &private_key.inner);
436
437        keypair.x_only_public_key().0
438    }
439
440    /// Resolves the standard format ECDSA public key.
441    #[must_use]
442    pub fn get_ecdsa_public_key(&self) -> PublicKey {
443        self.get_private_key().public_key(&self.secp)
444    }
445
446    /// Resolves the corresponding blinding public key.
447    #[must_use]
448    pub fn get_blinding_public_key(&self) -> PublicKey {
449        self.get_blinding_private_key().public_key(&self.secp)
450    }
451
452    /// Internally derives and exposes the wallet's signing active private key.
453    ///
454    /// # Panics
455    /// Panics if the master private key or derivation path cannot be derived.
456    #[must_use]
457    pub fn get_private_key(&self) -> PrivateKey {
458        self.get_private_key_at(None)
459    }
460
461    /// Derives the signing key at a path relative to the account path. `None` defaults to `0/0`.
462    ///
463    /// # Panics
464    /// Panics if the master private key or derivation path cannot be derived.
465    #[must_use]
466    pub fn get_private_key_at(&self, relative: Option<&DerivationPath>) -> PrivateKey {
467        let master_xprv = self.master_xpriv().unwrap();
468        let full_path = self.get_derivation_path().unwrap();
469
470        let default_path;
471        let relative = if let Some(path) = relative {
472            path
473        } else {
474            default_path = DerivationPath::from_str("0/0")
475                .map_err(|e| SignerError::DerivationPath(e.to_string()))
476                .unwrap();
477
478            &default_path
479        };
480
481        let derived = full_path.extend(relative);
482        let ext_derived = master_xprv.derive_priv(&self.secp, &derived).unwrap();
483
484        PrivateKey::new(ext_derived.private_key, self.network)
485    }
486
487    /// Generates the private key linked to confidential payload blinding.
488    ///
489    /// The generated `PrivateKey` is associated with the `Test` (non-Bitcoin/Liquid-mainnet) network kind.
490    /// Retrieves the blinding private key derived from the master SLIP77 key and the script public key of the address.
491    ///
492    /// # Panics
493    /// Panics if the master SLIP77 key cannot be derived.
494    #[must_use]
495    pub fn get_blinding_private_key(&self) -> PrivateKey {
496        let blinding_key = self
497            .master_slip77()
498            .unwrap()
499            .blinding_private_key(&self.get_address().script_pubkey());
500
501        PrivateKey::new(blinding_key, self.network)
502    }
503
504    #[cfg(feature = "provider")]
505    fn unblind(&self, utxos: Vec<UTXO>) -> Result<Vec<UTXO>, SignerError> {
506        let mut unblinded: Vec<UTXO> = Vec::new();
507
508        for mut utxo in utxos {
509            let blinding_key = self.get_blinding_private_key();
510            let secrets = utxo.txout.unblind(&self.secp, blinding_key.inner)?;
511
512            utxo.secrets = Some(secrets);
513
514            unblinded.push(utxo);
515        }
516
517        Ok(unblinded)
518    }
519
520    fn estimate_tx(
521        &self,
522        mut fee_tx: FinalTransaction,
523        fee_rate: f32,
524        available_delta: u64,
525    ) -> Result<Estimate, SignerError> {
526        // Estimate the tx fee with the change. The caller supplies the change target
527        let change = match fee_tx.change() {
528            Some(target) => target.clone(),
529            None => {
530                ChangeOutput::new(self.get_address().script_pubkey()).with_blinding_key(self.get_blinding_public_key())
531            }
532        };
533
534        // A confidential input with an explicit change target and no blinded
535        // output cannot be balanced, which the node rejects with `bad-txns-in-ne-out`.
536        if fee_tx.has_confidential_input() && !fee_tx.needs_blinding() && change.blinding_key.is_none() {
537            return Err(SignerError::ConfidentialInputWithoutBlindedOutput);
538        }
539
540        let mut change_output = PartialOutput::new(change.script_pubkey, PLACEHOLDER_FEE, self.network.policy_asset());
541
542        if let Some(blinding_key) = change.blinding_key {
543            change_output = change_output.with_blinding_key(blinding_key);
544        }
545
546        fee_tx.add_output(change_output);
547
548        fee_tx.add_output(PartialOutput::new(
549            Script::new(),
550            PLACEHOLDER_FEE,
551            self.network.policy_asset(),
552        ));
553
554        let final_tx = self.sign_tx(&fee_tx)?;
555        let fee = fee_tx.calculate_fee(final_tx.discount_weight(), fee_rate);
556
557        if available_delta > fee && available_delta - fee >= MIN_FEE {
558            // We have enough funds to cover the change UTXO
559            let outputs = fee_tx.outputs_mut();
560
561            outputs[outputs.len() - 2].amount = available_delta - fee;
562            outputs[outputs.len() - 1].amount = fee;
563
564            if !fee_tx.is_balanced() {
565                return Err(SignerError::Unbalanced());
566            }
567
568            let final_tx = self.sign_tx(&fee_tx)?;
569
570            return Ok(Estimate::Success(final_tx, fee));
571        }
572
573        // Not enough funds for the change, so estimate without it.
574        // Dropping the change is only safe while something else stays blinded.
575        // When it is the transaction's only blinded output and an input is confidential,
576        // removing it makes the transaction unblindable.
577        let change_index = fee_tx.n_outputs() - 2;
578        let blinded_without_change = fee_tx
579            .outputs()
580            .iter()
581            .enumerate()
582            .any(|(index, output)| index != change_index && output.blinding_key.is_some());
583
584        if fee_tx.has_confidential_input() && !blinded_without_change {
585            return Ok(Estimate::Failure(fee + MIN_FEE));
586        }
587
588        fee_tx.remove_output(change_index);
589
590        let final_tx = self.sign_tx(&fee_tx)?;
591        let fee = fee_tx.calculate_fee(final_tx.discount_weight(), fee_rate);
592
593        if available_delta < fee {
594            return Ok(Estimate::Failure(fee));
595        }
596
597        let outputs = fee_tx.outputs_mut();
598
599        // Change the fee output amount
600        outputs[outputs.len() - 1].amount = available_delta;
601
602        if !fee_tx.is_balanced() {
603            return Err(SignerError::Unbalanced());
604        }
605
606        // Finalize the tx with fee and without the change
607        let final_tx = self.sign_tx(&fee_tx)?;
608
609        Ok(Estimate::Success(final_tx, fee))
610    }
611
612    fn sign_tx(&self, tx: &FinalTransaction) -> Result<Transaction, SignerError> {
613        let (mut pst, secrets) = tx.extract_pst();
614        let inputs = tx.inputs();
615
616        if tx.needs_blinding() {
617            pst.blind_last(&mut thread_rng(), &self.secp, &secrets)?;
618        }
619
620        for (index, input_i) in inputs.iter().enumerate() {
621            // We need to prune the program
622            if let Some(program_input) = &input_i.program_input {
623                let signing_info: Option<(&String, &[String], &SigMessage)> = match &input_i.required_sig {
624                    RequiredSignature::Witness(wtns_name) => Some((wtns_name, &[], &SigMessage::Sighash)),
625                    RequiredSignature::WitnessWithPath(wtns_name, sig_path) => {
626                        Some((wtns_name, sig_path, &SigMessage::Sighash))
627                    }
628                    RequiredSignature::WitnessWithMessage(wtns_name, sig_path, message) => {
629                        Some((wtns_name, sig_path, message))
630                    }
631                    _ => None,
632                };
633
634                let signed_witness: Result<WitnessValues, SignerError> = match signing_info {
635                    // Sign the program and inject the signature into the witness
636                    Some((witness_name, sig_path, message)) => Ok(self.get_signed_program_witness(
637                        &pst,
638                        program_input.program.as_ref(),
639                        &program_input.witness.build_witness(),
640                        witness_name,
641                        sig_path,
642                        index,
643                        input_i.partial_input.derivation_path.as_ref(),
644                        message,
645                    )?),
646                    // Just build the witness
647                    None => Ok(program_input.witness.build_witness()),
648                };
649
650                let pruned_witness = program_input
651                    .program
652                    .finalize(&pst, &signed_witness.unwrap(), index, &self.network)
653                    .map_err(|source| SignerError::CovenantExecution {
654                        index,
655                        locktime: pst.locktime().map_or(0, LockTime::to_consensus_u32),
656                        sequence: pst.inputs()[index]
657                            .sequence
658                            .map_or(u32::MAX, Sequence::to_consensus_u32),
659                        source,
660                    })?;
661
662                pst.inputs_mut()[index].final_script_witness = Some(pruned_witness);
663            } else {
664                // We need to sign the UTXO as is
665                // TODO: do we always sign?
666                let signed_witness = self.sign_input(&pst, index, input_i.partial_input.derivation_path.as_ref())?;
667                let raw_sig = elementssig_to_rawsig(&(signed_witness.1, EcdsaSighashType::All));
668
669                pst.inputs_mut()[index].final_script_witness = Some(vec![raw_sig, signed_witness.0.to_bytes()]);
670            }
671        }
672
673        Ok(pst.extract_tx()?)
674    }
675
676    #[allow(clippy::too_many_arguments)]
677    fn get_signed_program_witness(
678        &self,
679        pst: &PartiallySignedTransaction,
680        program: &dyn ProgramTrait,
681        witness: &WitnessValues,
682        witness_name: &str,
683        sig_path: &[String],
684        index: usize,
685        derivation_path: Option<&DerivationPath>,
686        message: &SigMessage,
687    ) -> Result<WitnessValues, SignerError> {
688        let signature = self.sign_program(pst, program, index, &self.network, derivation_path, message)?;
689
690        // Inject the signature into the wtns name directly if the path is not provided
691        let sig_val = if sig_path.is_empty() {
692            Value::byte_array(signature.serialize())
693        } else {
694            let witness_types = program.get_witness_types()?;
695            let witness_type = witness_types
696                .get(&WitnessName::from_str_unchecked(witness_name))
697                .ok_or(SignerError::WtnsFieldNotFound(witness_name.to_string()))?;
698
699            let local_wtns = Arc::new(
700                witness
701                    .get(&WitnessName::from_str_unchecked(witness_name))
702                    .expect("checked above")
703                    .clone(),
704            );
705
706            WtnsInjector::inject_value(
707                &local_wtns,
708                witness_type,
709                sig_path,
710                Value::byte_array(signature.serialize()),
711            )?
712        };
713
714        let mut hm = HashMap::new();
715
716        witness.iter().for_each(|el| {
717            hm.insert(el.0.clone(), el.1.clone());
718        });
719
720        hm.insert(WitnessName::from_str_unchecked(witness_name), sig_val);
721
722        Ok(WitnessValues::from(hm))
723    }
724
725    #[allow(clippy::unnecessary_wraps)]
726    fn master_slip77(&self) -> Result<MasterBlindingKey, SignerError> {
727        let seed = self.mnemonic.to_seed("");
728
729        Ok(MasterBlindingKey::from_seed(&seed[..]))
730    }
731
732    fn derive_xpriv(&self, path: &DerivationPath) -> Result<Xpriv, SignerError> {
733        Ok(self.xprv.derive_priv(&self.secp, &path)?)
734    }
735
736    fn master_xpriv(&self) -> Result<Xpriv, SignerError> {
737        self.derive_xpriv(&DerivationPath::master())
738    }
739
740    fn derive_xpub(&self, path: &DerivationPath) -> Result<Xpub, SignerError> {
741        let derived = self.derive_xpriv(path)?;
742
743        Ok(Xpub::from_priv(&self.secp, &derived))
744    }
745
746    fn master_xpub(&self) -> Result<Xpub, SignerError> {
747        self.derive_xpub(&DerivationPath::master())
748    }
749
750    fn fingerprint(&self) -> Result<Fingerprint, SignerError> {
751        Ok(self.master_xpub()?.fingerprint())
752    }
753
754    fn get_slip77_descriptor(&self) -> Result<String, SignerError> {
755        let wpkh_descriptor = self.get_wpkh_descriptor()?;
756        let blinding_key = self.master_slip77()?;
757
758        Ok(format!("ct(slip77({blinding_key}),{wpkh_descriptor})"))
759    }
760
761    fn get_wpkh_descriptor(&self) -> Result<String, SignerError> {
762        let fingerprint = self.fingerprint()?;
763        let path = self.get_derivation_path()?;
764        let mut xpub = self.derive_xpub(&path)?;
765
766        // TODO: Blockstream app does this. Is this a bug?
767        xpub.parent_fingerprint = Fingerprint::default();
768
769        Ok(format!("elwpkh([{fingerprint}/{path}]{xpub}/<0;1>/*)"))
770    }
771
772    fn get_derivation_path(&self) -> Result<DerivationPath, SignerError> {
773        let coin_type = if self.network.is_mainnet() { 1776 } else { 1 };
774        let path = format!("84h/{coin_type}h/0h");
775
776        DerivationPath::from_str(&format!("m/{path}")).map_err(|e| SignerError::DerivationPath(e.to_string()))
777    }
778}
779
780#[cfg(test)]
781mod tests {
782    use crate::provider::EsploraProvider;
783    use crate::utils::random_mnemonic;
784
785    use super::*;
786
787    fn create_signer() -> Signer {
788        let url = "https://blockstream.info/liquidtestnet/api".to_string();
789        let network = SimplicityNetwork::Liquid;
790
791        Signer::new(random_mnemonic().as_str(), Box::new(EsploraProvider::new(url, network)))
792    }
793
794    fn confidential_input(signer: &Signer, value: u64) -> PartialInput {
795        use simplicityhl::elements::confidential::{AssetBlindingFactor, ValueBlindingFactor};
796        use simplicityhl::elements::hashes::Hash;
797        use simplicityhl::elements::{TxOut, TxOutSecrets};
798
799        PartialInput::new(UTXO {
800            outpoint: OutPoint::new(Txid::from_slice(&[0x01; 32]).unwrap(), 0),
801            txout: TxOut::default(),
802            secrets: Some(TxOutSecrets::new(
803                signer.network.policy_asset(),
804                AssetBlindingFactor::zero(),
805                value,
806                ValueBlindingFactor::zero(),
807            )),
808        })
809    }
810
811    #[test]
812    fn explicit_change_target_cannot_balance_a_confidential_input() {
813        let signer = create_signer();
814        let mut ft = FinalTransaction::new();
815
816        ft.add_input(confidential_input(&signer, 100_000), RequiredSignature::NativeEcdsa);
817        ft.add_output(PartialOutput::new(
818            signer.get_address().script_pubkey(),
819            50_000,
820            signer.network.policy_asset(),
821        ));
822        ft.add_change(ChangeOutput::new(signer.get_address().script_pubkey()));
823
824        assert!(matches!(
825            signer.estimate_fee(&ft, 1.0),
826            Err(SignerError::ConfidentialInputWithoutBlindedOutput)
827        ));
828    }
829
830    #[test]
831    fn blinded_output_lets_the_explicit_change_target_stand() {
832        let signer = create_signer();
833        let mut ft = FinalTransaction::new();
834
835        ft.add_input(confidential_input(&signer, 100_000), RequiredSignature::NativeEcdsa);
836        ft.add_output(
837            PartialOutput::new(
838                signer.get_address().script_pubkey(),
839                50_000,
840                signer.network.policy_asset(),
841            )
842            .with_blinding_key(signer.get_blinding_public_key()),
843        );
844        ft.add_change(ChangeOutput::new(signer.get_address().script_pubkey()));
845
846        assert!(!matches!(
847            signer.estimate_fee(&ft, 1.0),
848            Err(SignerError::ConfidentialInputWithoutBlindedOutput)
849        ));
850    }
851
852    #[test]
853    fn default_change_target_balances_it_by_itself() {
854        let signer = create_signer();
855        let mut ft = FinalTransaction::new();
856
857        ft.add_input(confidential_input(&signer, 100_000), RequiredSignature::NativeEcdsa);
858        ft.add_output(PartialOutput::new(
859            signer.get_address().script_pubkey(),
860            50_000,
861            signer.network.policy_asset(),
862        ));
863
864        assert!(!matches!(
865            signer.estimate_fee(&ft, 1.0),
866            Err(SignerError::ConfidentialInputWithoutBlindedOutput)
867        ));
868    }
869
870    #[test]
871    fn keys_correspond_to_address() {
872        let signer = create_signer();
873
874        let address = signer.get_address();
875        let pubkey = signer.get_ecdsa_public_key();
876
877        let derived_addr = Address::p2wpkh(
878            &pubkey,
879            None,
880            signer.get_provider().unwrap().get_network().address_params(),
881        );
882
883        assert_eq!(derived_addr.to_string(), address.to_string());
884    }
885
886    #[test]
887    fn descriptors() {
888        let signer = create_signer();
889
890        println!("{}", signer.get_address());
891        println!("{}", signer.get_confidential_address());
892    }
893}