dusk-core 1.4.1

Types used for interacting with Dusk's transfer and stake contracts.
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
// 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.

//! Types related to the moonlight transaction model of Dusk's transfer
//! contract.

#[cfg(feature = "serde")]
use serde_with::{serde_as, DisplayFromStr};

use alloc::vec::Vec;

use bytecheck::CheckBytes;
use dusk_bytes::{DeserializableSlice, Error as BytesError, Serializable};
use rkyv::{Archive, Deserialize, Serialize};

use crate::signatures::bls::{
    PublicKey as AccountPublicKey, SecretKey as AccountSecretKey,
    Signature as AccountSignature,
};
use crate::transfer::data::{
    BlobData, ContractBytecode, ContractCall, ContractDeploy, TransactionData,
    MAX_MEMO_SIZE,
};
use crate::{BlsScalar, Error};

/// A Moonlight account's information.
#[derive(Debug, Clone, PartialEq, Eq, Archive, Serialize, Deserialize)]
#[archive_attr(derive(CheckBytes))]
#[cfg_attr(feature = "serde", cfg_eval, serde_as)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct AccountData {
    /// Number used for replay protection.
    #[cfg_attr(feature = "serde", serde_as(as = "DisplayFromStr"))]
    pub nonce: u64,
    /// Account balance.
    #[cfg_attr(feature = "serde", serde_as(as = "DisplayFromStr"))]
    pub balance: u64,
}

/// Moonlight transaction.
#[derive(Debug, Clone, PartialEq, Eq, Archive, Serialize, Deserialize)]
#[archive_attr(derive(CheckBytes))]
pub struct Transaction {
    payload: Payload,
    signature: AccountSignature,
}

impl Transaction {
    /// Create a new transaction.
    ///
    /// # Errors
    /// The creation of a transaction is not possible and will error if:
    /// - the memo, if given, is too large
    #[allow(clippy::too_many_arguments)]
    pub fn new(
        sender_sk: &AccountSecretKey,
        receiver: Option<AccountPublicKey>,
        value: u64,
        deposit: u64,
        gas_limit: u64,
        gas_price: u64,
        nonce: u64,
        chain_id: u8,
        data: Option<impl Into<TransactionData>>,
    ) -> Result<Self, Error> {
        let refund_address = AccountPublicKey::from(sender_sk);

        Self::new_with_refund(
            sender_sk,
            &refund_address,
            receiver,
            value,
            deposit,
            gas_limit,
            gas_price,
            nonce,
            chain_id,
            data,
        )
    }

    /// Create a new transaction with a specified refund-address for the gas
    /// refund.
    ///
    /// # Errors
    /// The creation of a transaction is not possible and will error if:
    /// - the memo, if given, is too large
    #[allow(clippy::too_many_arguments)]
    pub fn new_with_refund(
        sender_sk: &AccountSecretKey,
        refund_pk: &AccountPublicKey,
        receiver: Option<AccountPublicKey>,
        value: u64,
        deposit: u64,
        gas_limit: u64,
        gas_price: u64,
        nonce: u64,
        chain_id: u8,
        data: Option<impl Into<TransactionData>>,
    ) -> Result<Self, Error> {
        let data = data.map(Into::into);
        let sender = AccountPublicKey::from(sender_sk);
        let receiver = receiver.unwrap_or(sender);

        let fee = Fee {
            gas_limit,
            gas_price,
            refund_address: *refund_pk,
        };

        let payload = Payload {
            chain_id,
            sender,
            receiver,
            value,
            deposit,
            fee,
            nonce,
            data,
        };

        Self::sign_payload(sender_sk, payload)
    }

    /// Create a transaction by signing a previously generated payload with a
    /// given secret-key.
    ///
    /// Note that this transaction will be invalid if the secret-key used for
    /// signing doesn't form a valid key-pair with the public-key of the
    /// `sender`.
    ///
    /// # Errors
    /// The creation of a transaction is not possible and will error if:
    /// - the payload memo, if given, is too large
    pub fn sign_payload(
        sender_sk: &AccountSecretKey,
        payload: Payload,
    ) -> Result<Self, Error> {
        if let Some(TransactionData::Memo(memo)) = payload.data.as_ref() {
            if memo.len() > MAX_MEMO_SIZE {
                return Err(Error::MemoTooLarge(memo.len()));
            }
        }

        let digest = payload.signature_message();
        let signature = sender_sk.sign(&digest);

        Ok(Self { payload, signature })
    }

    /// The proof of the transaction.
    #[must_use]
    pub fn signature(&self) -> &AccountSignature {
        &self.signature
    }

    /// Return the sender of the transaction.
    #[must_use]
    pub fn sender(&self) -> &AccountPublicKey {
        &self.payload.sender
    }

    /// Return the address to send the transaction refund to.
    #[must_use]
    pub fn refund_address(&self) -> &AccountPublicKey {
        &self.payload.fee.refund_address
    }

    /// Return the receiver of the transaction if it's different from the
    /// sender. Otherwise, return None.
    #[must_use]
    pub fn receiver(&self) -> Option<&AccountPublicKey> {
        if self.payload.sender == self.payload.receiver {
            None
        } else {
            Some(&self.payload.receiver)
        }
    }

    /// Return the value transferred in the transaction.
    #[must_use]
    pub fn value(&self) -> u64 {
        self.payload.value
    }

    /// Returns the deposit of the transaction.
    #[must_use]
    pub fn deposit(&self) -> u64 {
        self.payload.deposit
    }

    /// Returns the gas limit of the transaction.
    #[must_use]
    pub fn gas_limit(&self) -> u64 {
        self.payload.fee.gas_limit
    }

    /// Returns the gas price of the transaction.
    #[must_use]
    pub fn gas_price(&self) -> u64 {
        self.payload.fee.gas_price
    }

    /// Returns the nonce of the transaction.
    #[must_use]
    pub fn nonce(&self) -> u64 {
        self.payload.nonce
    }

    /// Returns the chain ID of the transaction.
    #[must_use]
    pub fn chain_id(&self) -> u8 {
        self.payload.chain_id
    }

    /// Return the contract call data, if there is any.
    #[must_use]
    pub fn call(&self) -> Option<&ContractCall> {
        #[allow(clippy::match_wildcard_for_single_variants)]
        match self.data()? {
            TransactionData::Call(ref c) => Some(c),
            _ => None,
        }
    }

    /// Return the contract deploy data, if there is any.
    #[must_use]
    pub fn deploy(&self) -> Option<&ContractDeploy> {
        #[allow(clippy::match_wildcard_for_single_variants)]
        match self.data()? {
            TransactionData::Deploy(ref d) => Some(d),
            _ => None,
        }
    }

    /// Returns the memo used with the transaction, if any.
    #[must_use]
    pub fn memo(&self) -> Option<&[u8]> {
        match self.data()? {
            TransactionData::Memo(memo) => Some(memo),
            _ => None,
        }
    }

    /// Return the blob data, if there is any.
    #[must_use]
    pub fn blob(&self) -> Option<&Vec<BlobData>> {
        #[allow(clippy::match_wildcard_for_single_variants)]
        match self.data()? {
            TransactionData::Blob(ref d) => Some(d),
            _ => None,
        }
    }

    /// Return the mutable blob data, if there is any.
    #[must_use]
    pub fn blob_mut(&mut self) -> Option<&mut Vec<BlobData>> {
        #[allow(clippy::match_wildcard_for_single_variants)]
        match self.data_mut()? {
            TransactionData::Blob(d) => Some(d),
            _ => None,
        }
    }

    /// Returns the transaction data, if it exists.
    #[must_use]
    pub fn data(&self) -> Option<&TransactionData> {
        self.payload.data.as_ref()
    }

    /// Returns the transaction data, if it exists.
    #[must_use]
    pub(crate) fn data_mut(&mut self) -> Option<&mut TransactionData> {
        self.payload.data.as_mut()
    }

    /// Creates a modified clone of this transaction if it contains data for
    /// deployment, clones all fields except for the bytecode 'bytes' part.
    /// Returns none if the transaction is not a deployment transaction.
    #[must_use]
    pub fn strip_off_bytecode(&self) -> Option<Self> {
        let deploy = self.deploy()?;

        let stripped_deploy = TransactionData::Deploy(ContractDeploy {
            owner: deploy.owner.clone(),
            init_args: deploy.init_args.clone(),
            bytecode: ContractBytecode {
                hash: deploy.bytecode.hash,
                bytes: Vec::new(),
            },
            nonce: deploy.nonce,
        });

        let mut stripped_transaction = self.clone();
        stripped_transaction.payload.data = Some(stripped_deploy);

        Some(stripped_transaction)
    }

    /// Creates a modified clone of this transaction if it contains a Blob,
    /// clones all fields except for the Blob, whose versioned hashes are set as
    /// Memo.
    ///
    /// Returns none if the transaction is not a Blob transaction.
    #[must_use]
    pub fn blob_to_memo(&self) -> Option<Self> {
        let data = self.data()?;

        if let TransactionData::Blob(_) = data {
            let hash = data.signature_message();
            let memo = TransactionData::Memo(hash);
            let mut converted_tx = self.clone();
            converted_tx.payload.data = Some(memo);
            Some(converted_tx)
        } else {
            None
        }
    }

    /// Serialize a transaction into a byte buffer.
    #[must_use]
    pub fn to_var_bytes(&self) -> Vec<u8> {
        let mut bytes = Vec::new();

        let payload_bytes = self.payload.to_var_bytes();
        bytes.extend((payload_bytes.len() as u64).to_bytes());
        bytes.extend(payload_bytes);

        bytes.extend(self.signature.to_bytes());

        bytes
    }

    /// Deserialize the Transaction from a bytes buffer.
    ///
    /// # Errors
    /// Errors when the bytes are not canonical.
    pub fn from_slice(buf: &[u8]) -> Result<Self, BytesError> {
        let mut buf = buf;

        let payload_len = usize::try_from(u64::from_reader(&mut buf)?)
            .map_err(|_| BytesError::InvalidData)?;

        if buf.len() < payload_len {
            return Err(BytesError::InvalidData);
        }
        let (payload_buf, new_buf) = buf.split_at(payload_len);

        let payload = Payload::from_slice(payload_buf)?;
        buf = new_buf;

        let signature = AccountSignature::from_bytes(
            buf.try_into().map_err(|_| BytesError::InvalidData)?,
        )
        .map_err(|_| BytesError::InvalidData)?;

        Ok(Self { payload, signature })
    }

    /// Return input bytes to hash the payload.
    ///
    /// Note: The result of this function is *only* meant to be used as an input
    /// for hashing and *cannot* be used to deserialize the transaction again.
    #[must_use]
    pub fn to_hash_input_bytes(&self) -> Vec<u8> {
        let mut bytes = self.payload.signature_message();
        bytes.extend(self.signature.to_bytes());
        bytes
    }

    /// Return the message that is meant to be signed over to make the
    /// transaction a valid one.
    #[must_use]
    pub fn signature_message(&self) -> Vec<u8> {
        self.payload.signature_message()
    }

    /// Create the transaction hash.
    #[must_use]
    pub fn hash(&self) -> BlsScalar {
        BlsScalar::hash_to_scalar(&self.to_hash_input_bytes())
    }
}

/// The payload for a moonlight transaction.
#[derive(Debug, Clone, PartialEq, Eq, Archive, Serialize, Deserialize)]
#[archive_attr(derive(CheckBytes))]
pub struct Payload {
    /// ID of the chain for this transaction to execute on.
    pub chain_id: u8,
    /// Key of the sender of this transaction.
    pub sender: AccountPublicKey,
    /// Key of the receiver of the funds.
    pub receiver: AccountPublicKey,
    /// Value to be transferred.
    pub value: u64,
    /// Deposit for a contract.
    pub deposit: u64,
    /// Data used to calculate the transaction fee and refund unspent gas.
    pub fee: Fee,
    /// Nonce used for replay protection. Moonlight nonces are strictly
    /// increasing and incremental, meaning that for a transaction to be
    /// valid, only the current nonce + 1 can be used.
    ///
    /// The current nonce is queryable via the transfer contract.
    pub nonce: u64,
    /// Data to do a contract call, deployment, or insert a memo.
    pub data: Option<TransactionData>,
}

impl Payload {
    /// Serialize the payload into a byte buffer.
    #[must_use]
    pub fn to_var_bytes(&self) -> Vec<u8> {
        let mut bytes = Vec::from([self.chain_id]);

        bytes.extend(self.sender.to_bytes());
        // to save space we only serialize the receiver if it's different from
        // the sender
        if self.sender == self.receiver {
            bytes.push(0);
        } else {
            bytes.push(1);
            bytes.extend(self.receiver.to_bytes());
        }

        bytes.extend(self.value.to_bytes());
        bytes.extend(self.deposit.to_bytes());

        // serialize the fee
        bytes.extend(self.fee.gas_limit.to_bytes());
        bytes.extend(self.fee.gas_price.to_bytes());
        // to save space we only serialize the refund-address if it's different
        // from the sender
        if self.sender == self.fee.refund_address {
            bytes.push(0);
        } else {
            bytes.push(1);
            bytes.extend(self.fee.refund_address.to_bytes());
        }

        bytes.extend(self.nonce.to_bytes());

        // serialize the transaction data, if present.
        bytes.extend(TransactionData::option_to_var_bytes(self.data.as_ref()));

        bytes
    }

    /// Deserialize the payload from bytes slice.
    ///
    /// # Errors
    /// Errors when the bytes are not canonical.
    pub fn from_slice(buf: &[u8]) -> Result<Self, BytesError> {
        let mut buf = buf;

        let chain_id = u8::from_reader(&mut buf)?;
        let sender = AccountPublicKey::from_reader(&mut buf)?;
        let receiver = match u8::from_reader(&mut buf)? {
            0 => sender,
            1 => AccountPublicKey::from_reader(&mut buf)?,
            _ => {
                return Err(BytesError::InvalidData);
            }
        };
        let value = u64::from_reader(&mut buf)?;
        let deposit = u64::from_reader(&mut buf)?;

        // deserialize the fee
        let gas_limit = u64::from_reader(&mut buf)?;
        let gas_price = u64::from_reader(&mut buf)?;
        let refund_address = match u8::from_reader(&mut buf)? {
            0 => sender,
            1 => AccountPublicKey::from_reader(&mut buf)?,
            _ => {
                return Err(BytesError::InvalidData);
            }
        };
        let fee = Fee {
            gas_limit,
            gas_price,
            refund_address,
        };

        let nonce = u64::from_reader(&mut buf)?;

        // deserialize optional transaction data
        let data = TransactionData::from_slice(buf)?;

        Ok(Self {
            chain_id,
            sender,
            receiver,
            value,
            deposit,
            fee,
            nonce,
            data,
        })
    }

    /// Return input bytes to hash the payload.
    ///
    /// Note: The result of this function is *only* meant to be used as an input
    /// for hashing and *cannot* be used to deserialize the payload again.
    #[must_use]
    pub fn signature_message(&self) -> Vec<u8> {
        let mut bytes = Vec::from([self.chain_id]);

        bytes.extend(self.sender.to_bytes());
        if self.receiver != self.sender {
            bytes.extend(self.receiver.to_bytes());
        }
        bytes.extend(self.value.to_bytes());
        bytes.extend(self.deposit.to_bytes());
        bytes.extend(self.fee.gas_limit.to_bytes());
        bytes.extend(self.fee.gas_price.to_bytes());
        if self.fee.refund_address != self.sender {
            bytes.extend(self.fee.refund_address.to_bytes());
        }
        bytes.extend(self.nonce.to_bytes());

        if let Some(data) = &self.data {
            bytes.extend(data.signature_message());
        }

        bytes
    }
}

/// The Fee structure
#[derive(Debug, Clone, PartialEq, Eq, Archive, Serialize, Deserialize)]
#[archive_attr(derive(CheckBytes))]
pub struct Fee {
    /// Limit on the gas to be spent.
    pub gas_limit: u64,
    /// Price for each unit of gas.
    pub gas_price: u64,
    /// Address to which to refund the unspent gas.
    pub refund_address: AccountPublicKey,
}