xrpl-rust 1.3.0

A 100% Rust library to interact with the XRPL
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
use alloc::borrow::Cow;
use alloc::vec::Vec;
use serde::{Deserialize, Serialize};
use serde_with::skip_serializing_none;

use crate::models::amount::XRPAmount;
use crate::models::{
    transactions::{Memo, Signer, Transaction, TransactionType},
    Model, ValidateCurrencies, XRPLModelException,
};
use crate::models::{FlagCollection, NoFlags};

use super::confidential_mpt_constants::{
    address_is_issuer, validate_hex_length, validate_mpt_amount, BLINDING_FACTOR_LENGTH,
    CIPHERTEXT_LENGTH, ENCRYPTION_KEY_LENGTH, SCHNORR_PROOF_LENGTH,
};
use super::mptoken_issuance_set::validate_mptoken_issuance_id;
use super::{CommonFields, CommonTransactionBuilder};

/// A `ConfidentialMPTConvert` transaction converts a holder's public MPT
/// balance into confidential form (XLS-0096 §7).
///
/// On first use it also serves as the **opt-in** for confidential MPTs: the
/// holder registers their `HolderEncryptionKey` and provides a 64-byte
/// Schnorr Proof of Knowledge of the corresponding secret key.
///
/// On subsequent calls (key already registered) `holder_encryption_key`
/// and `zk_proof` MUST both be absent — those fields are gated by §7.3.1
/// rules 2 and 3.
#[skip_serializing_none]
#[derive(
    Debug,
    Default,
    Serialize,
    Deserialize,
    PartialEq,
    Eq,
    Clone,
    xrpl_rust_macros::ValidateCurrencies,
)]
#[serde(rename_all = "PascalCase")]
pub struct ConfidentialMPTConvert<'a> {
    #[serde(flatten)]
    pub common_fields: CommonFields<'a, NoFlags>,

    /// 24-byte `MPTokenIssuanceID` of the target MPT.
    #[serde(rename = "MPTokenIssuanceID")]
    pub mptoken_issuance_id: Cow<'a, str>,

    /// Plaintext amount being converted from public to confidential.
    /// Encoded as a u64 string per XRPL's large-integer convention.
    #[serde(rename = "MPTAmount")]
    pub mpt_amount: Cow<'a, str>,

    /// 66-byte ElGamal ciphertext credited to the holder's `CB_IN`.
    pub holder_encrypted_amount: Cow<'a, str>,

    /// 66-byte ElGamal ciphertext credited to the issuer's mirror balance.
    pub issuer_encrypted_amount: Cow<'a, str>,

    /// 32-byte ElGamal randomness `r`. Revealed plaintext so validators
    /// can deterministically verify the ciphertexts encrypt `mpt_amount`.
    pub blinding_factor: Cow<'a, str>,

    /// 33-byte compressed holder ElGamal public key. **Required** on first
    /// Convert (key registration); **forbidden** thereafter.
    pub holder_encryption_key: Option<Cow<'a, str>>,

    /// 66-byte ElGamal ciphertext for the auditor mirror. Required iff the
    /// issuance has an `AuditorEncryptionKey` registered.
    pub auditor_encrypted_amount: Option<Cow<'a, str>>,

    /// 64-byte Schnorr Proof of Knowledge of the holder's secret key.
    /// **Required** if `holder_encryption_key` is present; **forbidden**
    /// otherwise.
    #[serde(rename = "ZKProof")]
    pub zk_proof: Option<Cow<'a, str>>,
}

impl<'a> Model for ConfidentialMPTConvert<'a> {
    fn get_errors(&self) -> crate::models::XRPLModelResult<()> {
        self._get_registration_error()?;
        self._get_field_length_errors()?;
        self._get_issuer_role_error()?;
        self.validate_currencies()
    }
}

impl<'a> ConfidentialMPTConvert<'a> {
    /// `HolderEncryptionKey` and the Schnorr `ZKProof` are all-or-nothing:
    /// both present on the registering (first) Convert, both absent after
    /// (XLS-0096 §7.3.1 rules 2 and 3).
    fn _get_registration_error(&self) -> crate::models::XRPLModelResult<()> {
        match (
            self.holder_encryption_key.is_some(),
            self.zk_proof.is_some(),
        ) {
            (true, false) => Err(XRPLModelException::FieldRequiresField {
                field1: "holder_encryption_key".into(),
                field2: "zk_proof".into(),
            }),
            (false, true) => Err(XRPLModelException::FieldRequiresField {
                field1: "zk_proof".into(),
                field2: "holder_encryption_key".into(),
            }),
            _ => Ok(()),
        }
    }

    /// The issuer converts value through its mirror balances, not a personal
    /// confidential balance, so it cannot be the `Account` of a Convert
    /// (`temMALFORMED`, `ConfidentialMPTConvert.cpp` preflight).
    fn _get_issuer_role_error(&self) -> crate::models::XRPLModelResult<()> {
        if address_is_issuer(
            self.mptoken_issuance_id.as_ref(),
            self.common_fields.account.as_ref(),
        ) {
            return Err(XRPLModelException::ValueEqualsValue {
                field1: "account".into(),
                field2: "issuer".into(),
            });
        }
        Ok(())
    }

    fn _get_field_length_errors(&self) -> crate::models::XRPLModelResult<()> {
        validate_mptoken_issuance_id(self.mptoken_issuance_id.as_ref())?;
        // Unlike ConvertBack/Clawback, a zero amount is permitted here on
        // purpose: rippled allows a zero-amount Convert as the way to register
        // the holder's ElGamal key and initialize the confidential balance
        // fields (it does explicit freeze/auth checks precisely for that case).
        validate_mpt_amount("mpt_amount", self.mpt_amount.as_ref(), false)?;
        validate_hex_length(
            "holder_encrypted_amount",
            self.holder_encrypted_amount.as_ref(),
            CIPHERTEXT_LENGTH,
        )?;
        validate_hex_length(
            "issuer_encrypted_amount",
            self.issuer_encrypted_amount.as_ref(),
            CIPHERTEXT_LENGTH,
        )?;
        if let Some(auditor) = self.auditor_encrypted_amount.as_deref() {
            validate_hex_length("auditor_encrypted_amount", auditor, CIPHERTEXT_LENGTH)?;
        }
        validate_hex_length(
            "blinding_factor",
            self.blinding_factor.as_ref(),
            BLINDING_FACTOR_LENGTH,
        )?;
        if let Some(key) = self.holder_encryption_key.as_deref() {
            validate_hex_length("holder_encryption_key", key, ENCRYPTION_KEY_LENGTH)?;
        }
        if let Some(proof) = self.zk_proof.as_deref() {
            validate_hex_length("zk_proof", proof, SCHNORR_PROOF_LENGTH)?;
        }
        Ok(())
    }
}

impl<'a> Transaction<'a, NoFlags> for ConfidentialMPTConvert<'a> {
    fn get_transaction_type(&self) -> &TransactionType {
        self.common_fields.get_transaction_type()
    }

    fn get_common_fields(&self) -> &CommonFields<'_, NoFlags> {
        self.common_fields.get_common_fields()
    }

    fn get_mut_common_fields(&mut self) -> &mut CommonFields<'a, NoFlags> {
        self.common_fields.get_mut_common_fields()
    }
}

impl<'a> CommonTransactionBuilder<'a, NoFlags> for ConfidentialMPTConvert<'a> {
    fn get_mut_common_fields(&mut self) -> &mut CommonFields<'a, NoFlags> {
        &mut self.common_fields
    }

    fn into_self(self) -> Self {
        self
    }
}

impl<'a> ConfidentialMPTConvert<'a> {
    #[allow(clippy::too_many_arguments)]
    pub fn new(
        account: Cow<'a, str>,
        account_txn_id: Option<Cow<'a, str>>,
        fee: Option<XRPAmount<'a>>,
        last_ledger_sequence: Option<u32>,
        memos: Option<Vec<Memo>>,
        sequence: Option<u32>,
        signers: Option<Vec<Signer>>,
        source_tag: Option<u32>,
        ticket_sequence: Option<u32>,
        mptoken_issuance_id: Cow<'a, str>,
        mpt_amount: Cow<'a, str>,
        holder_encrypted_amount: Cow<'a, str>,
        issuer_encrypted_amount: Cow<'a, str>,
        blinding_factor: Cow<'a, str>,
        holder_encryption_key: Option<Cow<'a, str>>,
        auditor_encrypted_amount: Option<Cow<'a, str>>,
        zk_proof: Option<Cow<'a, str>>,
    ) -> Self {
        Self {
            common_fields: CommonFields::new(
                account,
                TransactionType::ConfidentialMPTConvert,
                account_txn_id,
                fee,
                Some(FlagCollection::default()),
                last_ledger_sequence,
                memos,
                None,
                sequence,
                signers,
                None,
                source_tag,
                ticket_sequence,
                None,
            ),
            mptoken_issuance_id,
            mpt_amount,
            holder_encrypted_amount,
            issuer_encrypted_amount,
            blinding_factor,
            holder_encryption_key,
            auditor_encrypted_amount,
            zk_proof,
        }
    }
}

#[cfg(test)]
mod tests {
    use alloc::string::ToString;

    use super::*;

    #[test]
    fn test_serialize_first_convert_with_registration() {
        let tx = ConfidentialMPTConvert {
            common_fields: CommonFields {
                account: "rUserAccount11111111111111111111".into(),
                transaction_type: TransactionType::ConfidentialMPTConvert,
                ..Default::default()
            },
            mptoken_issuance_id: "610F33B8EBF7EC795F822A454FB852156AEFE50BE0CB8326338A81CD74801864"
                .into(),
            mpt_amount: "1000".into(),
            holder_encrypted_amount: "AD3F".repeat(33).into(),
            issuer_encrypted_amount: "BC2E".repeat(33).into(),
            blinding_factor: "EE".repeat(32).into(),
            holder_encryption_key: Some("03".to_string() + &"8d".repeat(32)).map(Into::into),
            auditor_encrypted_amount: None,
            zk_proof: Some("AB".repeat(64).into()),
        };

        let json = serde_json::to_string(&tx).unwrap();
        assert!(json.contains("\"TransactionType\":\"ConfidentialMPTConvert\""));
        assert!(json.contains("\"HolderEncryptionKey\""));
        assert!(json.contains("\"ZKProof\""));

        let round_tripped: ConfidentialMPTConvert = serde_json::from_str(&json).unwrap();
        assert_eq!(round_tripped, tx);
    }

    #[test]
    fn test_serialize_subsequent_convert_no_key() {
        let tx = ConfidentialMPTConvert {
            common_fields: CommonFields {
                account: "rUserAccount11111111111111111111".into(),
                transaction_type: TransactionType::ConfidentialMPTConvert,
                ..Default::default()
            },
            mptoken_issuance_id: "610F33".repeat(4).into(),
            mpt_amount: "500".into(),
            holder_encrypted_amount: "AD3F".repeat(33).into(),
            issuer_encrypted_amount: "BC2E".repeat(33).into(),
            blinding_factor: "EE".repeat(32).into(),
            holder_encryption_key: None,
            auditor_encrypted_amount: None,
            zk_proof: None,
        };

        let json = serde_json::to_string(&tx).unwrap();
        // Optional absent fields should not appear via skip_serializing_none.
        assert!(!json.contains("\"HolderEncryptionKey\""));
        assert!(!json.contains("\"ZKProof\""));
    }

    #[test]
    fn test_new_builder_and_accessors() {
        let mut tx = ConfidentialMPTConvert::new(
            "rUserAccount11111111111111111111".into(),
            None,
            None,
            None,
            None,
            None,
            None,
            None,
            None,
            "610F33".repeat(8).into(),
            "1000".into(),
            "AD3F".repeat(33).into(),
            "BC2E".repeat(33).into(),
            "EE".repeat(32).into(),
            None,
            None,
            None,
        )
        .with_fee(XRPAmount::from("20000"))
        .with_sequence(7);

        // with_fee/with_sequence route through the builder's
        // get_mut_common_fields() + into_self().
        assert_eq!(tx.get_common_fields().sequence, Some(7));
        assert_eq!(tx.get_common_fields().fee, Some(XRPAmount::from("20000")));
        assert_eq!(
            tx.get_transaction_type(),
            &TransactionType::ConfidentialMPTConvert
        );
        // No currency amounts to validate, so Model::get_errors succeeds.
        assert!(tx.get_errors().is_ok());

        // Transaction::get_mut_common_fields (distinct from the builder's
        // same-named method) — disambiguate via UFCS.
        let common =
            <ConfidentialMPTConvert as Transaction<'_, NoFlags>>::get_mut_common_fields(&mut tx);
        assert_eq!(common.sequence, Some(7));
    }

    #[test]
    fn test_serialize_with_auditor_mirror() {
        let tx = ConfidentialMPTConvert {
            common_fields: CommonFields {
                account: "rUserAccount11111111111111111111".into(),
                transaction_type: TransactionType::ConfidentialMPTConvert,
                ..Default::default()
            },
            mptoken_issuance_id: "610F33".repeat(4).into(),
            mpt_amount: "750".into(),
            holder_encrypted_amount: "AD3F".repeat(33).into(),
            issuer_encrypted_amount: "BC2E".repeat(33).into(),
            blinding_factor: "EE".repeat(32).into(),
            holder_encryption_key: None,
            // Issuance with a registered AuditorEncryptionKey requires the mirror.
            auditor_encrypted_amount: Some("CD".repeat(66).into()),
            zk_proof: None,
        };

        let json = serde_json::to_string(&tx).unwrap();
        assert!(json.contains("\"AuditorEncryptedAmount\""));

        let round_tripped: ConfidentialMPTConvert = serde_json::from_str(&json).unwrap();
        assert_eq!(round_tripped, tx);
    }

    // ACCT's AccountID is B5F762..37E8.
    const ACCT: &str = "rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh";
    // Issuance whose issuer AccountID (bytes 4..24) is ACCT.
    const ISS_OF_ACCT: &str = "00000001B5F762798A53D543A014CAF8B297CFF8F2F937E8";

    fn valid_convert() -> ConfidentialMPTConvert<'static> {
        ConfidentialMPTConvert {
            common_fields: CommonFields {
                account: ACCT.into(),
                transaction_type: TransactionType::ConfidentialMPTConvert,
                ..Default::default()
            },
            // Arbitrary issuance whose issuer is not ACCT.
            mptoken_issuance_id: "610F33".repeat(8).into(),
            mpt_amount: "1000".into(),
            holder_encrypted_amount: "AD3F".repeat(33).into(),
            issuer_encrypted_amount: "BC2E".repeat(33).into(),
            blinding_factor: "EE".repeat(32).into(),
            holder_encryption_key: None,
            auditor_encrypted_amount: None,
            zk_proof: None,
        }
    }

    #[test]
    fn test_valid_convert_passes() {
        assert!(valid_convert().get_errors().is_ok());
    }

    #[test]
    fn test_zero_amount_convert_allowed() {
        // A zero-amount Convert is the on-purpose key-registration / init path.
        let mut tx = valid_convert();
        tx.mpt_amount = "0".into();
        assert!(tx.get_errors().is_ok());
    }

    #[test]
    fn test_account_is_issuer_rejected() {
        let mut tx = valid_convert();
        tx.mptoken_issuance_id = ISS_OF_ACCT.into();
        assert!(tx.get_errors().is_err());
    }

    #[test]
    fn test_amount_above_mpt_max_rejected() {
        // 2^63 (i64::MAX + 1) parses as u64 but exceeds the on-ledger MPT cap.
        let mut tx = valid_convert();
        tx.mpt_amount = "9223372036854775808".into();
        assert!(tx.get_errors().is_err());
    }

    #[test]
    fn test_key_without_proof_rejected() {
        // HolderEncryptionKey and the Schnorr ZKProof are all-or-nothing.
        let mut tx = valid_convert();
        tx.holder_encryption_key = Some(("03".to_string() + &"8d".repeat(32)).into());
        assert!(tx.get_errors().is_err());
    }
}