plutus_ledger_api/v1/
transaction.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
//! Types related to Cardano transactions.
use std::{fmt, str::FromStr};

use anyhow::anyhow;
use cardano_serialization_lib as csl;
#[cfg(feature = "lbf")]
use lbr_prelude::json::Json;
use nom::{
    character::complete::char,
    combinator::{all_consuming, map, map_res},
    error::{context, VerboseError},
    sequence::{preceded, tuple},
    Finish, IResult,
};
use num_bigint::BigInt;
#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};

use super::{
    address::{Address, StakingCredential},
    crypto::{ledger_bytes, LedgerBytes, PaymentPubKeyHash},
    datum::{Datum, DatumHash},
    interval::PlutusInterval,
    value::{CurrencySymbol, Value},
};

use crate::{
    self as plutus_ledger_api,
    aux::{big_int, guard_bytes},
};
use crate::{
    csl::pla_to_csl::{TryFromPLAError, TryToCSL},
    plutus_data::IsPlutusData,
};
use crate::{
    csl::{csl_to_pla::FromCSL, pla_to_csl::TryFromPLA},
    error::ConversionError,
};

//////////////////////
// TransactionInput //
//////////////////////

/// An input of a transaction
///
/// Also know as `TxOutRef` from Plutus, this identifies a UTxO by its transacton hash and index
/// inside the transaction
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, IsPlutusData)]
#[is_plutus_data_derive_strategy = "Constr"]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "lbf", derive(Json))]
pub struct TransactionInput {
    pub transaction_id: TransactionHash,
    pub index: BigInt,
}

/// Serializing into a hexadecimal tx hash, followed by an tx id after a # (e.g. aabbcc#1)
impl fmt::Display for TransactionInput {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}#{}", self.transaction_id.0, self.index)
    }
}

impl FromCSL<csl::TransactionInput> for TransactionInput {
    fn from_csl(value: &csl::TransactionInput) -> Self {
        TransactionInput {
            transaction_id: TransactionHash::from_csl(&value.transaction_id()),
            index: BigInt::from_csl(&value.index()),
        }
    }
}

impl TryFromPLA<TransactionInput> for csl::TransactionInput {
    fn try_from_pla(val: &TransactionInput) -> Result<Self, TryFromPLAError> {
        Ok(csl::TransactionInput::new(
            &val.transaction_id.try_to_csl()?,
            val.index.try_to_csl()?,
        ))
    }
}

impl FromCSL<csl::TransactionInputs> for Vec<TransactionInput> {
    fn from_csl(value: &csl::TransactionInputs) -> Self {
        (0..value.len())
            .map(|idx| TransactionInput::from_csl(&value.get(idx)))
            .collect()
    }
}

impl TryFromPLA<Vec<TransactionInput>> for csl::TransactionInputs {
    fn try_from_pla(val: &Vec<TransactionInput>) -> Result<Self, TryFromPLAError> {
        val.iter()
            .try_fold(csl::TransactionInputs::new(), |mut acc, input| {
                acc.add(&input.try_to_csl()?);
                Ok(acc)
            })
    }
}

/// Nom parser for TransactionInput
/// Expects a transaction hash of 32 bytes in hexadecimal followed by a # and an integer index
/// E.g.: 1122334455667788990011223344556677889900112233445566778899001122#1
pub(crate) fn transaction_input(
    input: &str,
) -> IResult<&str, TransactionInput, VerboseError<&str>> {
    map(
        tuple((transaction_hash, preceded(char('#'), big_int))),
        |(transaction_id, index)| TransactionInput {
            transaction_id,
            index,
        },
    )(input)
}

impl FromStr for TransactionInput {
    type Err = ConversionError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        all_consuming(transaction_input)(s)
            .finish()
            .map_err(|err| {
                ConversionError::ParseError(anyhow!(
                    "Error while parsing TransactionInput '{}': {}",
                    s,
                    err
                ))
            })
            .map(|(_, cs)| cs)
    }
}

/////////////////////
// TransactionHash //
/////////////////////

/// 32-bytes blake2b256 hash of a transaction body.
///
/// Also known as Transaction ID or `TxID`.
/// Note: Plutus docs might incorrectly state that it uses SHA256.
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, IsPlutusData)]
#[is_plutus_data_derive_strategy = "Constr"]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "lbf", derive(Json))]
pub struct TransactionHash(pub LedgerBytes);

impl fmt::Display for TransactionHash {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.0)
    }
}

impl TransactionHash {
    pub fn from_bytes(bytes: Vec<u8>) -> Result<Self, ConversionError> {
        Ok(TransactionHash(LedgerBytes(guard_bytes(
            "ScriptHash",
            bytes,
            32,
        )?)))
    }
}

impl FromCSL<csl::TransactionHash> for TransactionHash {
    fn from_csl(value: &csl::TransactionHash) -> Self {
        TransactionHash(LedgerBytes(value.to_bytes()))
    }
}

impl TryFromPLA<TransactionHash> for csl::TransactionHash {
    fn try_from_pla(val: &TransactionHash) -> Result<Self, TryFromPLAError> {
        csl::TransactionHash::from_bytes(val.0 .0.to_owned())
            .map_err(TryFromPLAError::CSLDeserializeError)
    }
}

/// Nom parser for TransactionHash
/// Expects a hexadecimal string representation of 32 bytes
/// E.g.: 1122334455667788990011223344556677889900112233445566778899001122
pub(crate) fn transaction_hash(input: &str) -> IResult<&str, TransactionHash, VerboseError<&str>> {
    context(
        "transaction_hash",
        map_res(ledger_bytes, |LedgerBytes(bytes)| {
            TransactionHash::from_bytes(bytes)
        }),
    )(input)
}

impl FromStr for TransactionHash {
    type Err = ConversionError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        all_consuming(transaction_hash)(s)
            .finish()
            .map_err(|err| {
                ConversionError::ParseError(anyhow!(
                    "Error while parsing TransactionHash '{}': {}",
                    s,
                    err
                ))
            })
            .map(|(_, cs)| cs)
    }
}

///////////////////////
// TransactionOutput //
///////////////////////

/// An output of a transaction
///
/// This must include the target address, the hash of the datum attached, and the amount of output
/// tokens
#[derive(Clone, Debug, PartialEq, Eq, IsPlutusData)]
#[is_plutus_data_derive_strategy = "Constr"]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "lbf", derive(Json))]
pub struct TransactionOutput {
    pub address: Address,
    pub value: Value,
    pub datum_hash: Option<DatumHash>,
}

///////////////
// POSIXTime //
///////////////

/// POSIX time is measured as the number of milliseconds since 1970-01-01T00:00:00Z
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, IsPlutusData)]
#[is_plutus_data_derive_strategy = "Newtype"]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "lbf", derive(Json))]
pub struct POSIXTime(pub BigInt);

#[cfg(feature = "chrono")]
#[derive(thiserror::Error, Debug)]
pub enum POSIXTimeConversionError {
    #[error(transparent)]
    TryFromBigIntError(#[from] num_bigint::TryFromBigIntError<BigInt>),
    #[error("POSIXTime is out of bounds.")]
    OutOfBoundsError,
}

#[cfg(feature = "chrono")]
impl<Tz: chrono::TimeZone> From<chrono::DateTime<Tz>> for POSIXTime {
    fn from(datetime: chrono::DateTime<Tz>) -> POSIXTime {
        POSIXTime(BigInt::from(datetime.timestamp_millis()))
    }
}

#[cfg(feature = "chrono")]
impl TryFrom<POSIXTime> for chrono::DateTime<chrono::Utc> {
    type Error = POSIXTimeConversionError;

    fn try_from(posix_time: POSIXTime) -> Result<chrono::DateTime<chrono::Utc>, Self::Error> {
        let POSIXTime(millis) = posix_time;
        chrono::DateTime::from_timestamp_millis(
            <i64>::try_from(millis).map_err(POSIXTimeConversionError::TryFromBigIntError)?,
        )
        .ok_or(POSIXTimeConversionError::OutOfBoundsError)
    }
}

////////////////////
// POSIXTimeRange //
////////////////////

pub type POSIXTimeRange = PlutusInterval<POSIXTime>;

//////////////
// TxInInfo //
//////////////

/// An input of a pending transaction.
#[derive(Clone, Debug, PartialEq, Eq, IsPlutusData)]
#[is_plutus_data_derive_strategy = "Constr"]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "lbf", derive(Json))]
pub struct TxInInfo {
    pub reference: TransactionInput,
    pub output: TransactionOutput,
}

impl From<(TransactionInput, TransactionOutput)> for TxInInfo {
    fn from((reference, output): (TransactionInput, TransactionOutput)) -> TxInInfo {
        TxInInfo { reference, output }
    }
}

///////////
// DCert //
///////////

/// Partial representation of digests of certificates on the ledger.
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone, Hash, IsPlutusData)]
#[is_plutus_data_derive_strategy = "Constr"]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "lbf", derive(Json))]
pub enum DCert {
    DelegRegKey(StakingCredential),
    DelegDeRegKey(StakingCredential),
    DelegDelegate(
        /// Delegator
        StakingCredential,
        /// Delegatee
        PaymentPubKeyHash,
    ),
    /// A digest of the PoolParam
    PoolRegister(
        /// Pool id
        PaymentPubKeyHash,
        /// Pool VFR
        PaymentPubKeyHash,
    ),
    PoolRetire(
        PaymentPubKeyHash,
        /// Epoch
        BigInt,
    ),
    Genesis,
    Mir,
}

///////////////////
// ScriptPurpose //
///////////////////

/// The purpose of the script that's currently running.
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone, Hash, IsPlutusData)]
#[is_plutus_data_derive_strategy = "Constr"]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "lbf", derive(Json))]
pub enum ScriptPurpose {
    Minting(CurrencySymbol),
    Spending(TransactionInput),
    Rewarding(StakingCredential),
    Certifying(DCert),
}

/////////////////////
// TransactionInfo //
/////////////////////

/// A pending transaction as seen by validator scripts, also known as TxInfo in Plutus
#[derive(Debug, PartialEq, Eq, Clone, IsPlutusData)]
#[is_plutus_data_derive_strategy = "Constr"]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "lbf", derive(Json))]
pub struct TransactionInfo {
    pub inputs: Vec<TxInInfo>,
    pub outputs: Vec<TransactionOutput>,
    pub fee: Value,
    pub mint: Value,
    pub d_cert: Vec<DCert>,
    pub wdrl: Vec<(StakingCredential, BigInt)>,
    pub valid_range: POSIXTimeRange,
    pub signatories: Vec<PaymentPubKeyHash>,
    pub datums: Vec<(DatumHash, Datum)>,
    pub id: TransactionHash,
}

///////////////////
// ScriptContext //
///////////////////

/// The context that is presented to the currently-executing script.
#[derive(Debug, PartialEq, Eq, Clone, IsPlutusData)]
#[is_plutus_data_derive_strategy = "Constr"]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "lbf", derive(Json))]
pub struct ScriptContext {
    pub tx_info: TransactionInfo,
    pub purpose: ScriptPurpose,
}