cdk-ffi 0.17.5

FFI bindings for cdk wallet
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
//! Proof-related FFI types

use std::str::FromStr;

use cdk::nuts::State as CdkState;
use serde::{Deserialize, Serialize};

use super::amount::{Amount, CurrencyUnit};
use super::mint::MintUrl;
use crate::error::FfiError;

/// FFI-compatible Proof state
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, uniffi::Enum)]
pub enum ProofState {
    Unspent,
    Pending,
    Spent,
    Reserved,
    PendingSpent,
}

impl From<CdkState> for ProofState {
    fn from(state: CdkState) -> Self {
        match state {
            CdkState::Unspent => ProofState::Unspent,
            CdkState::Pending => ProofState::Pending,
            CdkState::Spent => ProofState::Spent,
            CdkState::Reserved => ProofState::Reserved,
            CdkState::PendingSpent => ProofState::PendingSpent,
        }
    }
}

impl From<ProofState> for CdkState {
    fn from(state: ProofState) -> Self {
        match state {
            ProofState::Unspent => CdkState::Unspent,
            ProofState::Pending => CdkState::Pending,
            ProofState::Spent => CdkState::Spent,
            ProofState::Reserved => CdkState::Reserved,
            ProofState::PendingSpent => CdkState::PendingSpent,
        }
    }
}

/// FFI-compatible Proof
#[derive(Debug, Clone, Serialize, Deserialize, uniffi::Record)]
pub struct Proof {
    /// Proof amount
    pub amount: Amount,
    /// Secret (as string)
    pub secret: String,
    /// Unblinded signature C (as hex string)
    pub c: String,
    /// Keyset ID (as hex string)
    pub keyset_id: String,
    /// Optional witness
    pub witness: Option<Witness>,
    /// Optional DLEQ proof
    pub dleq: Option<ProofDleq>,
    /// Optional P2BK Ephemeral Public Key (NUT-28)
    pub p2pk_e: Option<String>,
}

impl From<cdk::nuts::Proof> for Proof {
    fn from(proof: cdk::nuts::Proof) -> Self {
        Self {
            amount: proof.amount.into(),
            secret: proof.secret.to_string(),
            c: proof.c.to_string(),
            keyset_id: proof.keyset_id.to_string(),
            witness: proof.witness.map(|w| w.into()),
            dleq: proof.dleq.map(|d| d.into()),
            p2pk_e: proof.p2pk_e.map(|p| p.to_string()),
        }
    }
}

impl TryFrom<Proof> for cdk::nuts::Proof {
    type Error = FfiError;

    fn try_from(proof: Proof) -> Result<Self, Self::Error> {
        use std::str::FromStr;

        use cdk::nuts::Id;

        Ok(Self {
            amount: proof.amount.into(),
            secret: cdk::secret::Secret::from_str(&proof.secret)
                .map_err(|e| FfiError::internal(format!("Invalid secret: {}", e)))?,
            c: cdk::nuts::PublicKey::from_str(&proof.c)
                .map_err(|e| FfiError::internal(format!("Invalid public key: {}", e)))?,
            keyset_id: Id::from_str(&proof.keyset_id)
                .map_err(|e| FfiError::internal(format!("Invalid keyset ID: {}", e)))?,
            witness: proof.witness.map(|w| w.into()),
            dleq: proof.dleq.map(TryInto::try_into).transpose()?,
            p2pk_e: proof
                .p2pk_e
                .map(|p| cdk::nuts::PublicKey::from_str(&p))
                .transpose()
                .map_err(|e| FfiError::internal(format!("Invalid p2pk_e: {}", e)))?,
        })
    }
}

/// Get the Y value (hash_to_curve of secret) for a proof
#[uniffi::export]
pub fn proof_y(proof: &Proof) -> Result<String, FfiError> {
    // Convert to CDK proof to calculate Y
    let cdk_proof: cdk::nuts::Proof = proof.clone().try_into()?;
    Ok(cdk_proof.y()?.to_string())
}

/// Check if proof is active with given keyset IDs
#[uniffi::export]
pub fn proof_is_active(proof: &Proof, active_keyset_ids: Vec<String>) -> bool {
    use cdk::nuts::Id;
    let ids: Vec<Id> = active_keyset_ids
        .into_iter()
        .filter_map(|id| Id::from_str(&id).ok())
        .collect();

    // A proof is active if its keyset_id is in the active list
    if let Ok(keyset_id) = Id::from_str(&proof.keyset_id) {
        ids.contains(&keyset_id)
    } else {
        false
    }
}

/// Check if proof has DLEQ proof
#[uniffi::export]
pub fn proof_has_dleq(proof: &Proof) -> bool {
    proof.dleq.is_some()
}

/// Verify HTLC witness on a proof
#[uniffi::export]
pub fn proof_verify_htlc(proof: &Proof) -> Result<(), FfiError> {
    let cdk_proof: cdk::nuts::Proof = proof.clone().try_into()?;
    cdk_proof.verify_htlc().map_err(FfiError::internal)
}

/// Verify DLEQ proof on a proof
#[uniffi::export]
pub fn proof_verify_dleq(
    proof: &Proof,
    mint_pubkey: super::keys::PublicKey,
) -> Result<(), FfiError> {
    let cdk_proof: cdk::nuts::Proof = proof.clone().try_into()?;
    let cdk_pubkey: cdk::nuts::PublicKey = mint_pubkey.try_into()?;
    cdk_proof
        .verify_dleq(cdk_pubkey)
        .map_err(FfiError::internal)
}

/// Sign a P2PK proof with a secret key, returning a new signed proof
#[uniffi::export]
pub fn proof_sign_p2pk(proof: Proof, secret_key_hex: String) -> Result<Proof, FfiError> {
    let mut cdk_proof: cdk::nuts::Proof = proof.try_into()?;
    let secret_key = cdk::nuts::SecretKey::from_hex(&secret_key_hex)
        .map_err(|e| FfiError::internal(format!("Invalid secret key: {}", e)))?;

    cdk_proof
        .sign_p2pk(secret_key)
        .map_err(FfiError::internal)?;

    Ok(cdk_proof.into())
}

/// FFI-compatible Proofs (vector of Proof)
pub type Proofs = Vec<Proof>;

/// FFI-compatible DLEQ proof for proofs
#[derive(Debug, Clone, Serialize, Deserialize, uniffi::Record)]
pub struct ProofDleq {
    /// e value (hex-encoded SecretKey)
    pub e: String,
    /// s value (hex-encoded SecretKey)
    pub s: String,
    /// r value - blinding factor (hex-encoded SecretKey)
    pub r: String,
}

/// FFI-compatible DLEQ proof for blind signatures
#[derive(Debug, Clone, Serialize, Deserialize, uniffi::Record)]
pub struct BlindSignatureDleq {
    /// e value (hex-encoded SecretKey)
    pub e: String,
    /// s value (hex-encoded SecretKey)
    pub s: String,
}

impl From<cdk::nuts::ProofDleq> for ProofDleq {
    fn from(dleq: cdk::nuts::ProofDleq) -> Self {
        Self {
            e: dleq.e.to_secret_hex(),
            s: dleq.s.to_secret_hex(),
            r: dleq.r.to_secret_hex(),
        }
    }
}

impl TryFrom<ProofDleq> for cdk::nuts::ProofDleq {
    type Error = FfiError;

    fn try_from(dleq: ProofDleq) -> Result<Self, Self::Error> {
        Ok(Self {
            e: cdk::nuts::SecretKey::from_hex(&dleq.e)
                .map_err(|e| FfiError::internal(format!("Invalid dleq e: {}", e)))?,
            s: cdk::nuts::SecretKey::from_hex(&dleq.s)
                .map_err(|e| FfiError::internal(format!("Invalid dleq s: {}", e)))?,
            r: cdk::nuts::SecretKey::from_hex(&dleq.r)
                .map_err(|e| FfiError::internal(format!("Invalid dleq r: {}", e)))?,
        })
    }
}

impl From<cdk::nuts::BlindSignatureDleq> for BlindSignatureDleq {
    fn from(dleq: cdk::nuts::BlindSignatureDleq) -> Self {
        Self {
            e: dleq.e.to_secret_hex(),
            s: dleq.s.to_secret_hex(),
        }
    }
}

impl TryFrom<BlindSignatureDleq> for cdk::nuts::BlindSignatureDleq {
    type Error = FfiError;

    fn try_from(dleq: BlindSignatureDleq) -> Result<Self, Self::Error> {
        Ok(Self {
            e: cdk::nuts::SecretKey::from_hex(&dleq.e).map_err(|e| {
                FfiError::internal(format!("Invalid blind signature dleq e: {}", e))
            })?,
            s: cdk::nuts::SecretKey::from_hex(&dleq.s).map_err(|e| {
                FfiError::internal(format!("Invalid blind signature dleq s: {}", e))
            })?,
        })
    }
}

/// Helper function to calculate total amount of proofs
#[uniffi::export]
pub fn proofs_total_amount(proofs: &Proofs) -> Result<Amount, FfiError> {
    let cdk_proofs: Result<Vec<cdk::nuts::Proof>, _> =
        proofs.iter().map(|p| p.clone().try_into()).collect();
    let cdk_proofs = cdk_proofs?;
    use cdk::nuts::ProofsMethods;
    Ok(cdk_proofs.total_amount()?.into())
}

/// FFI-compatible Conditions (for spending conditions)
#[derive(Debug, Clone, Serialize, Deserialize, uniffi::Record)]
pub struct Conditions {
    /// Unix locktime after which refund keys can be used
    pub locktime: Option<u64>,
    /// Additional Public keys (as hex strings)
    pub pubkeys: Vec<String>,
    /// Refund keys (as hex strings)
    pub refund_keys: Vec<String>,
    /// Number of signatures required (default 1)
    pub num_sigs: Option<u64>,
    /// Signature flag (0 = SigInputs, 1 = SigAll)
    pub sig_flag: u8,
    /// Number of refund signatures required (default 1)
    pub num_sigs_refund: Option<u64>,
}

impl From<cdk::nuts::nut10::Conditions> for Conditions {
    fn from(conditions: cdk::nuts::nut10::Conditions) -> Self {
        Self {
            locktime: conditions.locktime,
            pubkeys: conditions
                .pubkeys
                .unwrap_or_default()
                .into_iter()
                .map(|p| p.to_string())
                .collect(),
            refund_keys: conditions
                .refund_keys
                .unwrap_or_default()
                .into_iter()
                .map(|p| p.to_string())
                .collect(),
            num_sigs: conditions.num_sigs,
            sig_flag: match conditions.sig_flag {
                cdk::nuts::nut11::SigFlag::SigInputs => 0,
                cdk::nuts::nut11::SigFlag::SigAll => 1,
            },
            num_sigs_refund: conditions.num_sigs_refund,
        }
    }
}

impl TryFrom<Conditions> for cdk::nuts::nut10::Conditions {
    type Error = FfiError;

    fn try_from(conditions: Conditions) -> Result<Self, Self::Error> {
        let pubkeys = if conditions.pubkeys.is_empty() {
            None
        } else {
            Some(
                conditions
                    .pubkeys
                    .into_iter()
                    .map(|s| {
                        s.parse()
                            .map_err(|e| FfiError::internal(format!("Invalid pubkey: {}", e)))
                    })
                    .collect::<Result<Vec<_>, _>>()?,
            )
        };

        let refund_keys = if conditions.refund_keys.is_empty() {
            None
        } else {
            Some(
                conditions
                    .refund_keys
                    .into_iter()
                    .map(|s| {
                        s.parse()
                            .map_err(|e| FfiError::internal(format!("Invalid refund key: {}", e)))
                    })
                    .collect::<Result<Vec<_>, _>>()?,
            )
        };

        let sig_flag = match conditions.sig_flag {
            0 => cdk::nuts::nut11::SigFlag::SigInputs,
            1 => cdk::nuts::nut11::SigFlag::SigAll,
            _ => return Err(FfiError::internal("Invalid sig_flag value")),
        };

        Ok(Self {
            locktime: conditions.locktime,
            pubkeys,
            refund_keys,
            num_sigs: conditions.num_sigs,
            sig_flag,
            num_sigs_refund: conditions.num_sigs_refund,
        })
    }
}

impl Conditions {
    /// Convert Conditions to JSON string
    pub fn to_json(&self) -> Result<String, FfiError> {
        Ok(serde_json::to_string(self)?)
    }
}

/// Decode Conditions from JSON string
#[uniffi::export]
pub fn decode_conditions(json: String) -> Result<Conditions, FfiError> {
    Ok(serde_json::from_str(&json)?)
}

/// Encode Conditions to JSON string
#[uniffi::export]
pub fn encode_conditions(conditions: Conditions) -> Result<String, FfiError> {
    Ok(serde_json::to_string(&conditions)?)
}

/// FFI-compatible Witness
#[derive(Debug, Clone, Serialize, Deserialize, uniffi::Enum)]
pub enum Witness {
    /// P2PK Witness
    P2PK {
        /// Signatures
        signatures: Vec<String>,
    },
    /// HTLC Witness
    HTLC {
        /// Preimage
        preimage: String,
        /// Optional signatures
        signatures: Option<Vec<String>>,
    },
}

impl From<cdk::nuts::Witness> for Witness {
    fn from(witness: cdk::nuts::Witness) -> Self {
        match witness {
            cdk::nuts::Witness::P2PKWitness(p2pk) => Self::P2PK {
                signatures: p2pk.signatures,
            },
            cdk::nuts::Witness::HTLCWitness(htlc) => Self::HTLC {
                preimage: htlc.preimage,
                signatures: htlc.signatures,
            },
        }
    }
}

impl From<Witness> for cdk::nuts::Witness {
    fn from(witness: Witness) -> Self {
        match witness {
            Witness::P2PK { signatures } => {
                Self::P2PKWitness(cdk::nuts::nut11::P2PKWitness { signatures })
            }
            Witness::HTLC {
                preimage,
                signatures,
            } => Self::HTLCWitness(cdk::nuts::nut14::HTLCWitness {
                preimage,
                signatures,
            }),
        }
    }
}

/// FFI-compatible SpendingConditions
#[derive(Debug, Clone, Serialize, Deserialize, uniffi::Enum)]
pub enum SpendingConditions {
    /// P2PK (Pay to Public Key) conditions
    P2PK {
        /// The public key (as hex string)
        pubkey: String,
        /// Additional conditions
        conditions: Option<Conditions>,
    },
    /// HTLC (Hash Time Locked Contract) conditions
    HTLC {
        /// Hash of the preimage (as hex string)
        hash: String,
        /// Additional conditions
        conditions: Option<Conditions>,
    },
}

impl From<cdk::nuts::SpendingConditions> for SpendingConditions {
    fn from(spending_conditions: cdk::nuts::SpendingConditions) -> Self {
        match spending_conditions {
            cdk::nuts::SpendingConditions::P2PKConditions { data, conditions } => Self::P2PK {
                pubkey: data.to_string(),
                conditions: conditions.map(Into::into),
            },
            cdk::nuts::SpendingConditions::HTLCConditions { data, conditions } => Self::HTLC {
                hash: data.to_string(),
                conditions: conditions.map(Into::into),
            },
        }
    }
}

impl TryFrom<SpendingConditions> for cdk::nuts::SpendingConditions {
    type Error = FfiError;

    fn try_from(spending_conditions: SpendingConditions) -> Result<Self, Self::Error> {
        match spending_conditions {
            SpendingConditions::P2PK { pubkey, conditions } => {
                let pubkey = pubkey
                    .parse()
                    .map_err(|e| FfiError::internal(format!("Invalid pubkey: {}", e)))?;
                let conditions = conditions.map(|c| c.try_into()).transpose()?;
                Ok(Self::P2PKConditions {
                    data: pubkey,
                    conditions,
                })
            }
            SpendingConditions::HTLC { hash, conditions } => {
                let hash = hash
                    .parse()
                    .map_err(|e| FfiError::internal(format!("Invalid hash: {}", e)))?;
                let conditions = conditions.map(|c| c.try_into()).transpose()?;
                Ok(Self::HTLCConditions {
                    data: hash,
                    conditions,
                })
            }
        }
    }
}

/// FFI-compatible ProofInfo
#[derive(Debug, Clone, uniffi::Record)]
pub struct ProofInfo {
    /// Proof
    pub proof: Proof,
    /// Y value (hash_to_curve of secret)
    pub y: super::keys::PublicKey,
    /// Mint URL
    pub mint_url: MintUrl,
    /// Proof state
    pub state: ProofState,
    /// Proof Spending Conditions
    pub spending_condition: Option<SpendingConditions>,
    /// Currency unit
    pub unit: CurrencyUnit,
    /// Operation ID that is using/spending this proof
    pub used_by_operation: Option<String>,
    /// Operation ID that created this proof
    pub created_by_operation: Option<String>,
}

impl From<cdk::types::ProofInfo> for ProofInfo {
    fn from(info: cdk::types::ProofInfo) -> Self {
        Self {
            proof: info.proof.into(),
            y: info.y.into(),
            mint_url: info.mint_url.into(),
            state: info.state.into(),
            spending_condition: info.spending_condition.map(Into::into),
            unit: info.unit.into(),
            used_by_operation: info.used_by_operation.map(|u| u.to_string()),
            created_by_operation: info.created_by_operation.map(|u| u.to_string()),
        }
    }
}

/// Decode ProofInfo from JSON string
#[uniffi::export]
pub fn decode_proof_info(json: String) -> Result<ProofInfo, FfiError> {
    let info: cdk::types::ProofInfo = serde_json::from_str(&json)?;
    Ok(info.into())
}

/// Encode ProofInfo to JSON string
#[uniffi::export]
pub fn encode_proof_info(info: ProofInfo) -> Result<String, FfiError> {
    use std::str::FromStr;
    // Convert to cdk::types::ProofInfo for serialization
    let cdk_info = cdk::types::ProofInfo {
        proof: info.proof.try_into()?,
        y: info.y.try_into()?,
        mint_url: info.mint_url.try_into()?,
        state: info.state.into(),
        spending_condition: info.spending_condition.map(TryInto::try_into).transpose()?,
        unit: info.unit.into(),
        used_by_operation: info
            .used_by_operation
            .map(|id| uuid::Uuid::from_str(&id))
            .transpose()
            .map_err(|e| FfiError::internal(e.to_string()))?,
        created_by_operation: info
            .created_by_operation
            .map(|id| uuid::Uuid::from_str(&id))
            .transpose()
            .map_err(|e| FfiError::internal(e.to_string()))?,
    };
    Ok(serde_json::to_string(&cdk_info)?)
}

/// FFI-compatible ProofStateUpdate
#[derive(Debug, Clone, Serialize, Deserialize, uniffi::Record)]
pub struct ProofStateUpdate {
    /// Y value (hash_to_curve of secret)
    pub y: String,
    /// Current state
    pub state: ProofState,
    /// Optional witness data
    pub witness: Option<String>,
}

impl From<cdk::nuts::nut07::ProofState> for ProofStateUpdate {
    fn from(proof_state: cdk::nuts::nut07::ProofState) -> Self {
        Self {
            y: proof_state.y.to_string(),
            state: proof_state.state.into(),
            witness: proof_state.witness.map(|w| format!("{:?}", w)),
        }
    }
}

impl ProofStateUpdate {
    /// Convert ProofStateUpdate to JSON string
    pub fn to_json(&self) -> Result<String, FfiError> {
        Ok(serde_json::to_string(self)?)
    }
}

/// Decode ProofStateUpdate from JSON string
#[uniffi::export]
pub fn decode_proof_state_update(json: String) -> Result<ProofStateUpdate, FfiError> {
    Ok(serde_json::from_str(&json)?)
}

/// Encode ProofStateUpdate to JSON string
#[uniffi::export]
pub fn encode_proof_state_update(update: ProofStateUpdate) -> Result<String, FfiError> {
    Ok(serde_json::to_string(&update)?)
}