dusk-node-data 1.7.0

Types used for interacting with Dusk node.
Documentation
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
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
//
// Copyright (c) DUSK NETWORK. All rights reserved.

use dusk_bytes::Serializable as DuskSerializable;
use dusk_core::signatures::bls::PublicKey as AccountPublicKey;
use dusk_core::transfer::moonlight::Transaction as MoonlightTransaction;
use dusk_core::transfer::phoenix::Transaction as PhoenixTransaction;
use dusk_core::transfer::{
    Transaction as ProtocolTransaction, TransactionFormat,
};
use serde::Serialize;
use sha3::Digest;

use crate::hard_fork;

/// Number of bytes used by the outer ledger transaction header.
///
/// The header contains the transaction version, transaction type, and
/// length-prefix for the encoded protocol transaction.
pub(crate) const LEDGER_TRANSACTION_HEADER_BYTES: usize =
    std::mem::size_of::<u32>() * 3;

/// Canonical protocol transaction representation for a specific
/// [`TransactionFormat`].
#[derive(Debug, Clone)]
pub struct CanonicalTransaction {
    protocol: ProtocolTransaction,
    format: TransactionFormat,
}

impl CanonicalTransaction {
    /// Canonicalizes a native protocol transaction using the ledger format for
    /// `block_height`.
    pub fn canonicalize_for_ledger(
        protocol: ProtocolTransaction,
        block_height: u64,
    ) -> Self {
        Self::canonicalize(
            protocol,
            hard_fork::ledger_tx_format_at(block_height),
        )
    }

    /// Canonicalizes a native protocol transaction using the ingress format for
    /// `block_height`.
    pub fn canonicalize_for_ingress(
        protocol: ProtocolTransaction,
        block_height: u64,
    ) -> Self {
        Self::canonicalize(
            protocol,
            hard_fork::ingress_tx_format_at(block_height),
        )
    }

    /// Decodes transaction bytes for live ingress at `block_height`.
    ///
    /// Live network ingress accepts the currently supported transport
    /// envelopes (`Aegis` and `Boreas`) and normalizes them to the canonical
    /// ingress format for that height. Historical `PreAegis` encodings remain
    /// replay-only and are rejected here.
    pub fn decode_for_ingress(
        bytes: &[u8],
        block_height: u64,
    ) -> Result<Self, dusk_bytes::Error> {
        let decoded = Self::decode_any(bytes)?;

        if decoded.format() == TransactionFormat::PreAegis {
            return Err(dusk_bytes::Error::InvalidData);
        }

        Ok(decoded.reformat_for_ingress(block_height))
    }

    /// Decodes transaction bytes using the ledger format for `block_height`.
    ///
    /// This is the format used by block and ledger replay at that height.
    pub fn decode_for_ledger(
        bytes: &[u8],
        block_height: u64,
    ) -> Result<Self, dusk_bytes::Error> {
        Self::decode_with_selected_format(
            bytes,
            hard_fork::ledger_tx_format_at(block_height),
        )
    }

    /// Decodes transaction bytes using the format encoded by the payload.
    pub fn decode_any(bytes: &[u8]) -> Result<Self, dusk_bytes::Error> {
        let decoded = ProtocolTransaction::decode_any(bytes)?;
        Ok(Self::from_parts(decoded.transaction, decoded.format))
    }

    pub fn canonicalize(
        protocol: ProtocolTransaction,
        format: TransactionFormat,
    ) -> Self {
        Self::from_parts(protocol, format)
    }

    fn decode_with_selected_format(
        bytes: &[u8],
        format: TransactionFormat,
    ) -> Result<Self, dusk_bytes::Error> {
        let decoded = ProtocolTransaction::decode_with_format(format, bytes)?;
        Ok(Self::from_parts(decoded.transaction, decoded.format))
    }

    fn from_parts(
        protocol: ProtocolTransaction,
        format: TransactionFormat,
    ) -> Self {
        Self { protocol, format }
    }

    fn digest_bytes(
        protocol: &ProtocolTransaction,
        format: TransactionFormat,
    ) -> [u8; 32] {
        let tx_bytes = protocol.blob_to_memo().map_or_else(
            || protocol.encode_for_format(format),
            |mut blob_tx| {
                let _ = blob_tx.strip_blobs();
                blob_tx.encode_for_format(format)
            },
        );

        sha3::Sha3_256::digest(tx_bytes).into()
    }

    /// Returns the native protocol transaction.
    pub fn protocol(&self) -> &ProtocolTransaction {
        &self.protocol
    }

    /// Returns the serialization format used for the protocol transaction.
    pub fn format(&self) -> TransactionFormat {
        self.format
    }

    /// Reformats a canonical transaction to the ingress format active at
    /// `block_height`.
    pub fn reformat_for_ingress(&self, block_height: u64) -> Self {
        let expected = hard_fork::ingress_tx_format_at(block_height);

        if self.format() == expected {
            return self.clone();
        }

        Self::canonicalize(self.protocol.clone(), expected)
    }

    /// Encodes the native protocol transaction using its selected format.
    pub fn protocol_bytes(&self) -> Vec<u8> {
        self.protocol.encode_for_format(self.format)
    }

    /// Computes the transaction ID.
    ///
    /// This is the protocol-level transaction hash used to identify the
    /// transaction.
    pub fn id(&self) -> [u8; 32] {
        self.protocol.hash().to_bytes()
    }

    /// Computes the ledger digest of the transaction data.
    ///
    /// This digest hashes the encoded transaction data used by the ledger state
    /// root. For blob transactions, sidecar data is stripped first.
    pub fn digest(&self) -> [u8; 32] {
        Self::digest_bytes(&self.protocol, self.format)
    }

    pub fn gas_price(&self) -> u64 {
        self.protocol.gas_price()
    }

    pub fn to_spend_ids(&self) -> Vec<SpendingId> {
        match &self.protocol {
            ProtocolTransaction::Phoenix(p) => p
                .nullifiers()
                .iter()
                .map(|n| SpendingId::Nullifier(n.to_bytes()))
                .collect(),
            ProtocolTransaction::Moonlight(m) => {
                vec![SpendingId::AccountNonce(*m.sender(), m.nonce())]
            }
        }
    }

    pub fn next_spending_id(&self) -> Option<SpendingId> {
        match &self.protocol {
            ProtocolTransaction::Phoenix(_) => None,
            ProtocolTransaction::Moonlight(m) => {
                Some(SpendingId::AccountNonce(*m.sender(), m.nonce() + 1))
            }
        }
    }
}

/// Ledger transaction wrapper around a [`CanonicalTransaction`].
#[derive(Debug, Clone)]
pub struct LedgerTransaction {
    pub version: u32,
    pub r#type: u32,
    canonical: CanonicalTransaction,
}

impl LedgerTransaction {
    /// Returns the encoded ledger transaction size, including the outer header.
    pub fn size(&self) -> usize {
        LEDGER_TRANSACTION_HEADER_BYTES + self.protocol_bytes().len()
    }
}

impl From<CanonicalTransaction> for LedgerTransaction {
    fn from(value: CanonicalTransaction) -> Self {
        Self {
            r#type: 1,
            version: 1,
            canonical: value,
        }
    }
}

/// A spent transaction is a transaction that has been included in a block and
/// was executed.
#[derive(Debug, Clone, Serialize)]
pub struct SpentTransaction {
    /// The transaction that was executed.
    pub inner: LedgerTransaction,
    /// The height of the block in which the transaction was included.
    pub block_height: u64,
    /// The amount of gas that was spent during the execution of the
    /// transaction.
    pub gas_spent: u64,
    /// An optional error message if the transaction execution yielded an
    /// error.
    pub err: Option<String>,
}

impl SpentTransaction {
    /// Returns the underlying public transaction, if it is one. Otherwise,
    /// returns `None`.
    pub fn public(&self) -> Option<&MoonlightTransaction> {
        match self.inner.protocol() {
            ProtocolTransaction::Moonlight(public_tx) => Some(public_tx),
            _ => None,
        }
    }

    /// Returns the underlying shielded transaction, if it is one. Otherwise,
    /// returns `None`.
    pub fn shielded(&self) -> Option<&PhoenixTransaction> {
        match self.inner.protocol() {
            ProtocolTransaction::Phoenix(shielded_tx) => Some(shielded_tx),
            _ => None,
        }
    }
}

impl LedgerTransaction {
    pub fn decode_for_ingress(
        bytes: &[u8],
        block_height: u64,
    ) -> Result<Self, dusk_bytes::Error> {
        CanonicalTransaction::decode_for_ingress(bytes, block_height)
            .map(Into::into)
    }

    pub fn decode_for_ledger(
        bytes: &[u8],
        block_height: u64,
    ) -> Result<Self, dusk_bytes::Error> {
        CanonicalTransaction::decode_for_ledger(bytes, block_height)
            .map(Into::into)
    }

    pub fn decode_any(bytes: &[u8]) -> Result<Self, dusk_bytes::Error> {
        CanonicalTransaction::decode_any(bytes).map(Into::into)
    }

    /// Builds a ledger transaction from a native protocol transaction and an
    /// explicit format.
    pub fn from_protocol_with_format(
        protocol: ProtocolTransaction,
        format: TransactionFormat,
    ) -> Self {
        CanonicalTransaction::canonicalize(protocol, format).into()
    }

    pub fn from_protocol_for_ledger(
        protocol: ProtocolTransaction,
        block_height: u64,
    ) -> Self {
        CanonicalTransaction::canonicalize_for_ledger(protocol, block_height)
            .into()
    }

    pub fn from_protocol_for_ingress(
        protocol: ProtocolTransaction,
        block_height: u64,
    ) -> Self {
        CanonicalTransaction::canonicalize_for_ingress(protocol, block_height)
            .into()
    }

    /// Reformats a ledger transaction to the ledger format active at
    /// `block_height`.
    pub fn reformat_for_ledger(&self, block_height: u64) -> Self {
        let expected = hard_fork::ledger_tx_format_at(block_height);

        if self.format() == expected {
            return self.clone();
        }

        Self::from_protocol_with_format(self.protocol().clone(), expected)
    }

    /// Reformats a ledger transaction to the ingress format active at
    /// `block_height`.
    pub fn reformat_for_ingress(&self, block_height: u64) -> Self {
        let expected = hard_fork::ingress_tx_format_at(block_height);

        if self.format() == expected {
            return self.clone();
        }

        Self::from_protocol_with_format(self.protocol().clone(), expected)
    }

    pub fn format(&self) -> TransactionFormat {
        self.canonical.format()
    }

    pub fn canonical(&self) -> &CanonicalTransaction {
        &self.canonical
    }

    pub fn protocol(&self) -> &ProtocolTransaction {
        self.canonical.protocol()
    }

    pub fn protocol_bytes(&self) -> Vec<u8> {
        self.canonical.protocol_bytes()
    }

    /// Computes the hash digest of the entire transaction data.
    ///
    /// This method returns the Sha3 256 digest of the entire
    /// transaction in its serialized form. If the transaction is a blob
    /// transaction, the sidecar is stripped
    ///
    /// The digest hash is currently only being used in the merkle tree.
    ///
    /// ### Returns
    /// An array of 32 bytes representing the hash of the transaction.
    pub fn digest(&self) -> [u8; 32] {
        self.canonical.digest()
    }

    /// Computes the transaction ID.
    ///
    /// The transaction ID is a unique identifier for the transaction.
    /// Unlike the [`digest()`](#method.digest) method, which is computed over
    /// the entire transaction, the transaction ID is derived from specific
    /// fields of the transaction and serves as a unique identifier of the
    /// transaction itself.
    ///
    /// ### Returns
    /// An array of 32 bytes representing the transaction ID.
    pub fn id(&self) -> [u8; 32] {
        self.canonical.id()
    }

    pub fn gas_price(&self) -> u64 {
        self.protocol().gas_price()
    }

    pub fn to_spend_ids(&self) -> Vec<SpendingId> {
        self.canonical.to_spend_ids()
    }

    pub fn next_spending_id(&self) -> Option<SpendingId> {
        self.canonical.next_spending_id()
    }

    pub fn blob_mut(
        &mut self,
    ) -> Option<&mut Vec<dusk_core::transfer::data::BlobData>> {
        self.canonical.protocol.blob_mut()
    }

    pub fn strip_blobs(
        &mut self,
    ) -> Option<Vec<([u8; 32], dusk_core::transfer::data::BlobSidecar)>> {
        self.canonical.protocol.strip_blobs()
    }
}

impl PartialEq<Self> for LedgerTransaction {
    fn eq(&self, other: &Self) -> bool {
        self.r#type == other.r#type
            && self.version == other.version
            && self.format() == other.format()
            && self.id() == other.id()
    }
}

impl Eq for LedgerTransaction {}

impl PartialEq<Self> for SpentTransaction {
    fn eq(&self, other: &Self) -> bool {
        self.inner == other.inner && self.gas_spent == other.gas_spent
    }
}

impl Eq for SpentTransaction {}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SpendingId {
    Nullifier([u8; 32]),
    AccountNonce(AccountPublicKey, u64),
}

impl SpendingId {
    pub fn to_bytes(&self) -> Vec<u8> {
        match self {
            SpendingId::Nullifier(n) => n.to_vec(),
            SpendingId::AccountNonce(account, nonce) => {
                let mut id = account.to_bytes().to_vec();
                id.extend_from_slice(&nonce.to_le_bytes());
                id
            }
        }
    }

    pub fn next(&self) -> Option<SpendingId> {
        match self {
            SpendingId::Nullifier(_) => None,
            SpendingId::AccountNonce(account, nonce) => {
                Some(SpendingId::AccountNonce(*account, nonce + 1))
            }
        }
    }
}

#[cfg(any(feature = "faker", test))]
pub mod faker {
    use dusk_core::transfer::data::{ContractCall, TransactionData};
    use dusk_core::transfer::phoenix::{
        Fee, Note, Payload as PhoenixPayload, PublicKey as PhoenixPublicKey,
        SecretKey as PhoenixSecretKey, Transaction as PhoenixTransaction,
        TxSkeleton,
    };
    use dusk_core::{BlsScalar, JubJubScalar};
    use rand::Rng;

    use super::*;
    use crate::ledger::Dummy;

    impl<T> Dummy<T> for LedgerTransaction {
        fn dummy_with_rng<R: Rng + ?Sized>(_config: &T, _rng: &mut R) -> Self {
            gen_dummy_tx(1_000_000)
        }
    }

    impl<T> Dummy<T> for SpentTransaction {
        fn dummy_with_rng<R: Rng + ?Sized>(_config: &T, _rng: &mut R) -> Self {
            let tx = LedgerTransaction::from_protocol_with_format(
                gen_dummy_tx(1_000_000).protocol().clone(),
                TransactionFormat::PreAegis,
            );
            SpentTransaction {
                inner: tx,
                block_height: 0,
                gas_spent: 3,
                err: Some("error".to_string()),
            }
        }
    }

    /// Generates a decodable transaction from a fixed blob with a specified
    /// gas price.
    pub fn gen_dummy_tx(gas_price: u64) -> LedgerTransaction {
        let pk = PhoenixPublicKey::from(&PhoenixSecretKey::new(
            JubJubScalar::from(42u64),
            JubJubScalar::from(42u64),
        ));
        let gas_limit = 1;

        let fee = Fee::deterministic(
            &JubJubScalar::from(5u64),
            &pk,
            gas_limit,
            gas_price,
            &[JubJubScalar::from(9u64), JubJubScalar::from(10u64)],
        );

        let tx_skeleton = TxSkeleton {
            root: BlsScalar::from(12345u64),
            nullifiers: vec![
                BlsScalar::from(1u64),
                BlsScalar::from(2u64),
                BlsScalar::from(3u64),
            ],
            outputs: [Note::empty(), Note::empty()],
            max_fee: gas_price * gas_limit,
            deposit: 0,
        };

        let contract_call = ContractCall::new([21; 32], "some_method");

        let payload = PhoenixPayload {
            chain_id: 0xFA,
            tx_skeleton,
            fee,
            data: Some(TransactionData::Call(contract_call)),
        };
        let proof = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];

        let tx: ProtocolTransaction =
            PhoenixTransaction::from_payload_and_proof(payload, proof).into();

        LedgerTransaction::from_protocol_with_format(
            tx,
            TransactionFormat::Aegis,
        )
    }
}

#[cfg(test)]
mod tests {
    use dusk_core::transfer::TransactionFormat;

    use super::faker::gen_dummy_tx;
    use super::*;

    #[test]
    fn decode_for_ingress_accepts_aegis_and_normalizes_to_boreas() {
        let tx = gen_dummy_tx(10);
        let bytes = tx.protocol_bytes();

        let decoded =
            CanonicalTransaction::decode_for_ingress(&bytes, u64::MAX)
                .expect("aegis bytes should decode for boreas ingress");

        assert_eq!(decoded.format(), TransactionFormat::Boreas);
        assert_eq!(decoded.id(), tx.id());
    }

    #[test]
    fn decode_for_ingress_accepts_boreas_and_normalizes_to_aegis() {
        let tx = gen_dummy_tx(10);
        let bytes = tx.protocol().encode_for_format(TransactionFormat::Boreas);

        let decoded = CanonicalTransaction::decode_for_ingress(&bytes, 1)
            .expect("boreas bytes should decode for aegis ingress");

        assert_eq!(decoded.format(), TransactionFormat::Aegis);
        assert_eq!(decoded.id(), tx.id());
    }

    #[test]
    fn reformat_for_ingress_preserves_tx_identity() {
        let tx = gen_dummy_tx(10);
        let reformatted = tx.reformat_for_ingress(u64::MAX);

        assert_eq!(reformatted.format(), TransactionFormat::Boreas);
        assert_eq!(reformatted.id(), tx.id());
    }

    #[test]
    fn reformat_for_ingress_preserves_tx_identity_before_boreas() {
        let tx = LedgerTransaction::from_protocol_with_format(
            gen_dummy_tx(10).protocol().clone(),
            TransactionFormat::Boreas,
        );
        let reformatted = tx.reformat_for_ingress(1);

        assert_eq!(reformatted.format(), TransactionFormat::Aegis);
        assert_eq!(reformatted.id(), tx.id());
    }
}