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
use std::collections::BTreeSet;

use crate::{
    address::Address,
    plutus::Language,
    transaction::{DatumOption, ScriptRef, TransactionOutput},
    Value,
};
use cml_crypto::{DatumHash, Ed25519KeyHash, TransactionHash};

use super::{
    AlonzoFormatTxOut, ConwayFormatTxOut, NativeScript, TransactionBody, TransactionWitnessSet,
};

impl TransactionBody {
    pub fn hash(&self) -> TransactionHash {
        crate::crypto::hash::hash_transaction(self)
    }
}

impl TransactionOutput {
    pub fn new(
        address: Address,
        amount: Value,
        datum_option: Option<DatumOption>,
        script_reference: Option<ScriptRef>,
    ) -> Self {
        match (datum_option, script_reference) {
            (None, None) => Self::AlonzoFormatTxOut(AlonzoFormatTxOut::new(address, amount)),
            (Some(DatumOption::Hash { datum_hash, .. }), None) => {
                let mut tx_out = AlonzoFormatTxOut::new(address, amount);
                tx_out.datum_hash = Some(datum_hash);
                Self::AlonzoFormatTxOut(tx_out)
            }
            (datum, script_ref) => {
                let mut tx_out = ConwayFormatTxOut::new(address, amount);
                tx_out.datum_option = datum;
                tx_out.script_reference = script_ref;
                Self::ConwayFormatTxOut(tx_out)
            }
        }
    }

    pub fn address(&self) -> &Address {
        match self {
            Self::AlonzoFormatTxOut(tx_out) => &tx_out.address,
            Self::ConwayFormatTxOut(tx_out) => &tx_out.address,
        }
    }

    pub fn amount(&self) -> &Value {
        match self {
            Self::AlonzoFormatTxOut(tx_out) => &tx_out.amount,
            Self::ConwayFormatTxOut(tx_out) => &tx_out.amount,
        }
    }

    pub fn set_amount(&mut self, amount: Value) {
        match self {
            Self::AlonzoFormatTxOut(tx_out) => tx_out.amount = amount,
            Self::ConwayFormatTxOut(tx_out) => tx_out.amount = amount,
        }
    }

    pub fn datum(&self) -> Option<DatumOption> {
        match self {
            Self::AlonzoFormatTxOut(tx_out) => tx_out
                .datum_hash
                .as_ref()
                .map(|hash| DatumOption::new_hash(*hash)),
            Self::ConwayFormatTxOut(tx_out) => tx_out.datum_option.clone(),
        }
    }

    /// Get the datum hash from a tx output if present as a hash.
    /// Returns None if there is no datum, or the datum is inlined.
    /// Use TransactionOutput::datum() for inlined datums.
    pub fn datum_hash(&self) -> Option<&DatumHash> {
        match self {
            Self::AlonzoFormatTxOut(tx_out) => tx_out.datum_hash.as_ref(),
            Self::ConwayFormatTxOut(tx_out) => match &tx_out.datum_option {
                Some(DatumOption::Hash { datum_hash, .. }) => Some(datum_hash),
                _ => None,
            },
        }
    }

    pub fn script_ref(&self) -> Option<&ScriptRef> {
        match self {
            Self::AlonzoFormatTxOut(_) => None,
            Self::ConwayFormatTxOut(tx_out) => tx_out.script_reference.as_ref(),
        }
    }
}

impl From<AlonzoFormatTxOut> for TransactionOutput {
    fn from(tx_out: AlonzoFormatTxOut) -> Self {
        Self::AlonzoFormatTxOut(tx_out)
    }
}

impl From<ConwayFormatTxOut> for TransactionOutput {
    fn from(tx_out: ConwayFormatTxOut) -> Self {
        Self::ConwayFormatTxOut(tx_out)
    }
}

pub type RequiredSignersSet = BTreeSet<Ed25519KeyHash>;

impl From<&NativeScript> for RequiredSignersSet {
    fn from(script: &NativeScript) -> Self {
        fn from_scripts(scripts: &[NativeScript]) -> RequiredSignersSet {
            scripts.iter().fold(BTreeSet::new(), |mut set, s| {
                RequiredSignersSet::from(s).iter().for_each(|pk| {
                    set.insert(*pk);
                });
                set
            })
        }
        match script {
            NativeScript::ScriptPubkey(spk) => {
                let mut set = BTreeSet::new();
                set.insert(spk.ed25519_key_hash);
                set
            }
            NativeScript::ScriptAll(all) => from_scripts(&all.native_scripts),
            NativeScript::ScriptAny(any) => from_scripts(&any.native_scripts),
            NativeScript::ScriptNOfK(ofk) => from_scripts(&ofk.native_scripts),
            _ => BTreeSet::new(),
        }
    }
}

impl NativeScript {
    /// Returns an array of unique Ed25519KeyHashes
    /// contained within this script recursively on any depth level.
    /// The order of the keys in the result is not determined in any way.
    pub fn get_required_signers(&self) -> Vec<Ed25519KeyHash> {
        RequiredSignersSet::from(self).iter().cloned().collect()
    }
}

impl TransactionWitnessSet {
    pub fn add_all_witnesses(&mut self, other: Self) {
        // TODO: should we do duplicate checking here?
        if let Some(other_vkeys) = other.vkeywitnesses {
            if let Some(vkeys) = &mut self.vkeywitnesses {
                vkeys.extend(other_vkeys);
            } else {
                self.vkeywitnesses = Some(other_vkeys);
            }
        }
        if let Some(other_native_scripts) = other.native_scripts {
            if let Some(scripts) = &mut self.native_scripts {
                scripts.extend(other_native_scripts);
            } else {
                self.native_scripts = Some(other_native_scripts);
            }
        }
        if let Some(other_bootstraps) = other.bootstrap_witnesses {
            if let Some(bootstraps) = &mut self.bootstrap_witnesses {
                bootstraps.extend(other_bootstraps);
            } else {
                self.bootstrap_witnesses = Some(other_bootstraps);
            }
        }
        if let Some(other_plutus_v1_scripts) = other.plutus_v1_scripts {
            if let Some(scripts) = &mut self.plutus_v1_scripts {
                scripts.extend(other_plutus_v1_scripts);
            } else {
                self.plutus_v1_scripts = Some(other_plutus_v1_scripts);
            }
        }
        if let Some(other_plutus_v2_scripts) = other.plutus_v2_scripts {
            if let Some(scripts) = &mut self.plutus_v2_scripts {
                scripts.extend(other_plutus_v2_scripts);
            } else {
                self.plutus_v2_scripts = Some(other_plutus_v2_scripts);
            }
        }
        if let Some(other_plutus_v3_scripts) = other.plutus_v3_scripts {
            if let Some(scripts) = &mut self.plutus_v3_scripts {
                scripts.extend(other_plutus_v3_scripts);
            } else {
                self.plutus_v3_scripts = Some(other_plutus_v3_scripts);
            }
        }
        if let Some(other_plutus_datums) = other.plutus_datums {
            if let Some(datums) = &mut self.plutus_datums {
                datums.extend(other_plutus_datums);
            } else {
                self.plutus_datums = Some(other_plutus_datums);
            }
        }
        if let Some(other_redeemers) = other.redeemers {
            if let Some(redeemers) = &mut self.redeemers {
                redeemers.extend(other_redeemers);
            } else {
                self.redeemers = Some(other_redeemers);
            }
        }
    }

    pub fn languages(&self) -> Vec<Language> {
        let mut used_langs = vec![];
        if self.plutus_v1_scripts.is_some() {
            used_langs.push(Language::PlutusV1);
        }
        if self.plutus_v2_scripts.is_some() {
            used_langs.push(Language::PlutusV2);
        }
        if self.plutus_v3_scripts.is_some() {
            used_langs.push(Language::PlutusV3);
        }
        used_langs
    }
}