cardano_serialization_lib/builders/
tx_inputs_builder.rs

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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
use crate::*;
use hashlink::LinkedHashMap;
use std::collections::{BTreeMap, BTreeSet};

#[derive(Clone, Debug)]
pub(crate) struct TxBuilderInput {
    pub(crate) input: TransactionInput,
    pub(crate) amount: Value, // we need to keep track of the amount in the inputs for input selection
}

// We need to know how many of each type of witness will be in the transaction so we can calculate the tx fee
#[derive(Clone, Debug)]
pub struct InputsRequiredWitness {
    vkeys: Ed25519KeyHashes,
    scripts: LinkedHashMap<ScriptHash, LinkedHashMap<TransactionInput, Option<ScriptWitnessType>>>,
    bootstraps: BTreeSet<Vec<u8>>,
}

#[wasm_bindgen]
#[derive(Clone, Debug)]
pub struct TxInputsBuilder {
    inputs: BTreeMap<TransactionInput, (TxBuilderInput, Option<ScriptHash>)>,
    required_witnesses: InputsRequiredWitness,
}

pub(crate) fn get_bootstraps(inputs: &TxInputsBuilder) -> BTreeSet<Vec<u8>> {
    inputs.required_witnesses.bootstraps.clone()
}

#[wasm_bindgen]
impl TxInputsBuilder {
    pub fn new() -> Self {
        Self {
            inputs: BTreeMap::new(),
            required_witnesses: InputsRequiredWitness {
                vkeys: Ed25519KeyHashes::new(),
                scripts: LinkedHashMap::new(),
                bootstraps: BTreeSet::new(),
            },
        }
    }

    fn push_input(&mut self, e: (TxBuilderInput, Option<ScriptHash>)) {
        self.inputs.insert(e.0.input.clone(), e);
    }

    /// We have to know what kind of inputs these are to know what kind of mock witnesses to create since
    /// 1) mock witnesses have different lengths depending on the type which changes the expecting fee
    /// 2) Witnesses are a set so we need to get rid of duplicates to avoid over-estimating the fee
    pub fn add_key_input(
        &mut self,
        hash: &Ed25519KeyHash,
        input: &TransactionInput,
        amount: &Value,
    ) {
        let inp = TxBuilderInput {
            input: input.clone(),
            amount: amount.clone(),
        };
        self.push_input((inp, None));
        self.required_witnesses.vkeys.add_move(hash.clone());
    }

    fn add_script_input(&mut self, hash: &ScriptHash, input: &TransactionInput, amount: &Value) {
        let inp = TxBuilderInput {
            input: input.clone(),
            amount: amount.clone(),
        };
        self.push_input((inp, Some(hash.clone())));
        self.insert_input_with_empty_witness(hash, input);
    }

    /// This method will add the input to the builder and also register the required native script witness
    pub fn add_native_script_input(
        &mut self,
        script: &NativeScriptSource,
        input: &TransactionInput,
        amount: &Value,
    ) {
        let hash = script.script_hash();
        self.add_script_input(&hash, input, amount);
        let witness = ScriptWitnessType::NativeScriptWitness(script.0.clone());
        self.insert_input_with_witness(&hash, input, &witness);
    }

    /// This method will add the input to the builder and also register the required plutus witness
    pub fn add_plutus_script_input(
        &mut self,
        witness: &PlutusWitness,
        input: &TransactionInput,
        amount: &Value,
    ) {
        let hash = witness.script.script_hash();

        self.add_script_input(&hash, input, amount);
        let witness = ScriptWitnessType::PlutusScriptWitness(witness.clone());
        self.insert_input_with_witness(&hash, input, &witness);
    }

    pub fn add_bootstrap_input(
        &mut self,
        address: &ByronAddress,
        input: &TransactionInput,
        amount: &Value,
    ) {
        let inp = TxBuilderInput {
            input: input.clone(),
            amount: amount.clone(),
        };
        self.push_input((inp, None));
        self.required_witnesses.bootstraps.insert(address.to_bytes());
    }

    /// Adds non script input, in case of script or reward address input it will return an error
    pub fn add_regular_input(
        &mut self,
        address: &Address,
        input: &TransactionInput,
        amount: &Value,
    ) -> Result<(), JsError> {
        match &address.0 {
            AddrType::Base(base_addr) => match &base_addr.payment.0 {
                CredType::Key(key) => {
                    self.add_key_input(key, input, amount);
                    Ok(())
                }
                CredType::Script(_) => Err(JsError::from_str(
                    &BuilderError::RegularInputIsScript.as_str(),
                )),
            },
            AddrType::Enterprise(ent_aaddr) => match &ent_aaddr.payment.0 {
                CredType::Key(key) => {
                    self.add_key_input(key, input, amount);
                    Ok(())
                }
                CredType::Script(_) => Err(JsError::from_str(
                    &BuilderError::RegularInputIsScript.as_str(),
                )),
            },
            AddrType::Ptr(ptr_addr) => match &ptr_addr.payment.0 {
                CredType::Key(key) => {
                    self.add_key_input(key, input, amount);
                    Ok(())
                }
                CredType::Script(_) => Err(JsError::from_str(
                    &BuilderError::RegularInputIsScript.as_str(),
                )),
            },
            AddrType::Byron(byron_addr) => {
                self.add_bootstrap_input(byron_addr, input, amount);
                Ok(())
            }
            AddrType::Reward(_) => Err(JsError::from_str(
                &BuilderError::RegularInputIsFromRewardAddress.as_str(),
            )),
            AddrType::Malformed(_) => {
                Err(JsError::from_str(&BuilderError::MalformedAddress.as_str()))
            }
        }
    }

    pub fn get_ref_inputs(&self) -> TransactionInputs {
        let mut inputs = Vec::new();
        for wintess in self
            .required_witnesses
            .scripts
            .iter()
            .flat_map(|(_, tx_wits)| tx_wits.values())
            .filter_map(|wit| wit.as_ref())
        {
            match wintess {
                ScriptWitnessType::NativeScriptWitness(NativeScriptSourceEnum::RefInput(
                    input, _, _, _,
                )) => {
                    inputs.push(input.clone());
                }
                ScriptWitnessType::PlutusScriptWitness(plutus_witness) => {
                    if let Some(DatumSourceEnum::RefInput(input)) = &plutus_witness.datum {
                        inputs.push(input.clone());
                    }
                    if let PlutusScriptSourceEnum::RefInput(script_ref, _) = &plutus_witness.script
                    {
                        inputs.push(script_ref.input_ref.clone());
                    }
                }
                _ => (),
            }
        }
        TransactionInputs::from_vec(inputs)
    }


    /// Returns a copy of the current script input witness scripts in the builder
    pub fn get_native_input_scripts(&self) -> Option<NativeScripts> {
        let mut scripts = NativeScripts::new();
        self.required_witnesses
            .scripts
            .values()
            .flat_map(|v| v)
            .for_each(|tx_in_with_wit| {
                if let Some(ScriptWitnessType::NativeScriptWitness(
                    NativeScriptSourceEnum::NativeScript(s, _),
                )) = tx_in_with_wit.1
                {
                    scripts.add(&s);
                }
            });
        if scripts.len() > 0 {
            Some(scripts)
        } else {
            None
        }
    }

    pub(crate) fn get_used_plutus_lang_versions(&self) -> BTreeSet<Language> {
        let mut used_langs = BTreeSet::new();
        for input_with_wit in self.required_witnesses.scripts.values() {
            for (_, script_wit) in input_with_wit {
                if let Some(ScriptWitnessType::PlutusScriptWitness(plutus_witness)) = script_wit {
                    used_langs.insert(plutus_witness.script.language());
                }
            }
        }
        used_langs
    }

    /// Returns a copy of the current plutus input witness scripts in the builder.
    /// NOTE: each plutus witness will be cloned with a specific corresponding input index
    pub fn get_plutus_input_scripts(&self) -> Option<PlutusWitnesses> {
        /*
         * === EXPLANATION ===
         * The `Redeemer` object contains the `.index` field which is supposed to point
         * exactly to the index of the corresponding input in the inputs array. We want to
         * simplify and automate this as much as possible for the user to not have to care about it.
         *
         * For this we store the script hash along with the input, when it was registered, and
         * now we create a map of script hashes to their input indexes.
         *
         * The registered witnesses are then each cloned with the new correct redeemer input index.
         * To avoid incorrect redeemer tag we also set the `tag` field to `spend`.
         */
        let tag = RedeemerTag::new_spend();
        let script_hash_index_map: BTreeMap<&TransactionInput, BigNum> = self
            .inputs
            .values()
            .enumerate()
            .fold(BTreeMap::new(), |mut m, (i, (tx_in, hash_option))| {
                if hash_option.is_some() {
                    m.insert(&tx_in.input, (i as u64).into());
                }
                m
            });
        let mut scripts = PlutusWitnesses::new();
        self.required_witnesses
            .scripts
            .iter()
            .flat_map(|x| x.1)
            .for_each(|(hash, option)| {
                if let Some(ScriptWitnessType::PlutusScriptWitness(s)) = option {
                    if let Some(idx) = script_hash_index_map.get(&hash) {
                        scripts.add(&s.clone_with_redeemer_index_and_tag(&idx, &tag));
                    }
                }
            });
        if scripts.len() > 0 {
            Some(scripts)
        } else {
            None
        }
    }

    pub(crate) fn has_plutus_scripts(&self) -> bool {
        self.required_witnesses.scripts.values().any(|x| {
            x.iter()
                .any(|(_, w)| matches!(w, Some(ScriptWitnessType::PlutusScriptWitness(_))))
        })
    }

    pub(crate) fn iter(&self) -> impl std::iter::Iterator<Item = &TxBuilderInput> + '_ {
        self.inputs.values().map(|(i, _)| i)
    }

    pub fn len(&self) -> usize {
        self.inputs.len()
    }

    pub fn add_required_signer(&mut self, key: &Ed25519KeyHash) {
        self.required_witnesses.vkeys.add_move(key.clone());
    }

    pub fn add_required_signers(&mut self, keys: &RequiredSigners) {
        self.required_witnesses.vkeys.extend(keys);
    }

    pub fn total_value(&self) -> Result<Value, JsError> {
        let mut res = Value::zero();
        for (inp, _) in self.inputs.values() {
            res = res.checked_add(&inp.amount)?;
        }
        Ok(res)
    }

    pub fn inputs(&self) -> TransactionInputs {
        TransactionInputs::from_vec(
            self.inputs
                .values()
                .map(|(ref tx_builder_input, _)| tx_builder_input.input.clone())
                .collect(),
        )
    }

    pub fn inputs_option(&self) -> Option<TransactionInputs> {
        if self.len() > 0 {
            Some(self.inputs())
        } else {
            None
        }
    }

    pub(crate) fn get_script_ref_inputs_with_size(
        &self,
    ) -> impl Iterator<Item = (&TransactionInput, usize)> {
        self.required_witnesses
            .scripts
            .iter()
            .flat_map(|(_, tx_wits)| tx_wits.iter())
            .filter_map(|(_, wit)| wit.as_ref())
            .filter_map(|wit| wit.get_script_ref_input_with_size())
    }

    #[allow(dead_code)]
    pub(crate) fn get_required_signers(&self) -> Ed25519KeyHashes {
        self.into()
    }

    pub(crate) fn has_inputs(&self) -> bool {
        !self.inputs.is_empty()
    }

    pub(crate) fn has_input(&self, input: &TransactionInput) -> bool {
        self.inputs.contains_key(input)
    }

    fn insert_input_with_witness(
        &mut self,
        script_hash: &ScriptHash,
        input: &TransactionInput,
        witness: &ScriptWitnessType,
    ) {
        let script_inputs = self
            .required_witnesses
            .scripts
            .entry(script_hash.clone())
            .or_insert(LinkedHashMap::new());
        script_inputs.insert(input.clone(), Some(witness.clone()));
    }

    fn insert_input_with_empty_witness(
        &mut self,
        script_hash: &ScriptHash,
        input: &TransactionInput,
    ) {
        let script_inputs = self
            .required_witnesses
            .scripts
            .entry(script_hash.clone())
            .or_insert(LinkedHashMap::new());
        script_inputs.insert(input.clone(), None);
    }
}

impl From<&TxInputsBuilder> for Ed25519KeyHashes {
    fn from(inputs: &TxInputsBuilder) -> Self {
        let mut set = inputs.required_witnesses.vkeys.clone();
        inputs
            .required_witnesses
            .scripts
            .values()
            .flat_map(|tx_wits| tx_wits.values())
            .for_each(|swt: &Option<ScriptWitnessType>| {
                match swt {
                    Some(ScriptWitnessType::NativeScriptWitness(script_source)) => {
                        if let Some(signers) = script_source.required_signers() {
                            set.extend_move(signers);
                        }
                    }
                    Some(ScriptWitnessType::PlutusScriptWitness(script_source)) => {
                        if let Some(signers) = script_source.get_required_signers() {
                            set.extend_move(signers);
                        }
                    }
                    None => (),
                }
            });
        set
    }
}