cdk 0.16.0-rc.0

Core Cashu Development Kit library implementing the Cashu protocol
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
//! HTLC (NUT-14) tests for swap functionality
//!
//! These tests verify that the mint correctly validates HTLC spending conditions
//! during swap operations, including:
//! - Hash preimage verification
//! - Locktime enforcement
//! - Refund keys
//! - Signature validation

use cdk_common::nuts::{Conditions, SigFlag, SpendingConditions};
use cdk_common::Amount;

use crate::test_helpers::nut10::{
    create_test_hash_and_preimage, create_test_keypair, unzip3, TestMintHelper,
};

/// Test: HTLC requiring preimage and one signature
///
/// Creates HTLC-locked proofs and verifies:
/// 1. Spending with only preimage fails (signature required)
/// 2. Spending with only signature fails (preimage required)
/// 3. Spending with both preimage and signature succeeds
#[tokio::test]
async fn test_htlc_requiring_preimage_and_one_signature() {
    let test_mint = TestMintHelper::new().await.unwrap();
    let mint = test_mint.mint();

    // Generate keypair for Alice
    let (alice_secret, alice_pubkey) = create_test_keypair();

    // Create hash and preimage
    let (hash, preimage) = create_test_hash_and_preimage();

    println!("Alice pubkey: {}", alice_pubkey);
    println!("Hash: {}", hash);
    println!("Preimage: {}", preimage);

    // Step 1: Mint regular proofs
    let input_amount = Amount::from(10);
    let input_proofs = test_mint.mint_proofs(input_amount).await.unwrap();

    // Step 2: Create HTLC spending conditions (hash locked to Alice's key)
    let spending_conditions = SpendingConditions::new_htlc_hash(
        &hash,
        Some(Conditions {
            locktime: None,
            pubkeys: Some(vec![alice_pubkey]),
            refund_keys: None,
            num_sigs: None, // Default (1)
            sig_flag: SigFlag::default(),
            num_sigs_refund: None,
        }),
    )
    .unwrap();
    println!("Created HTLC spending conditions");

    // Step 3: Create HTLC blinded messages (outputs)
    let split_amounts = test_mint.split_amount(input_amount).unwrap();
    let split_display: Vec<String> = split_amounts.iter().map(|a| a.to_string()).collect();
    println!("Split {} into [{}]", input_amount, split_display.join("+"));

    let (htlc_outputs, blinding_factors, secrets) = unzip3(
        split_amounts
            .iter()
            .map(|&amt| test_mint.create_blinded_message(amt, &spending_conditions))
            .collect(),
    );
    println!(
        "Created {} HTLC outputs locked to alice with hash",
        htlc_outputs.len()
    );

    // Step 4: Swap regular proofs for HTLC proofs (no signature needed on inputs)
    let swap_request =
        cdk_common::nuts::SwapRequest::new(input_proofs.clone(), htlc_outputs.clone());
    let swap_response = mint
        .process_swap_request(swap_request)
        .await
        .expect("Failed to swap for HTLC proofs");
    println!("Swap successful! Got BlindSignatures for our HTLC outputs");

    // Step 5: Construct the HTLC proofs
    use cdk_common::dhke::construct_proofs;
    let htlc_proofs = construct_proofs(
        swap_response.signatures.clone(),
        blinding_factors.clone(),
        secrets.clone(),
        &test_mint.public_keys_of_the_active_sat_keyset,
    )
    .unwrap();

    let proof_amounts: Vec<String> = htlc_proofs.iter().map(|p| p.amount.to_string()).collect();
    println!(
        "Constructed {} HTLC proof(s) [{}]",
        htlc_proofs.len(),
        proof_amounts.join("+")
    );

    // Step 6: Try to spend with only preimage (should fail - signature required)
    use crate::test_helpers::mint::create_test_blinded_messages;
    let (new_outputs, _) = create_test_blinded_messages(mint, input_amount)
        .await
        .unwrap();
    let mut swap_request_preimage_only =
        cdk_common::nuts::SwapRequest::new(htlc_proofs.clone(), new_outputs.clone());

    // Add only preimage (no signature)
    for proof in swap_request_preimage_only.inputs_mut() {
        proof.add_preimage(preimage.clone());
    }

    let result = mint.process_swap_request(swap_request_preimage_only).await;
    assert!(
        result.is_err(),
        "Should fail with only preimage (no signature)"
    );
    println!("✓ Spending with ONLY preimage failed as expected");

    // Step 7: Try to spend with only signature (should fail - preimage required)
    let mut swap_request_signature_only =
        cdk_common::nuts::SwapRequest::new(htlc_proofs.clone(), new_outputs.clone());

    // Add only signature (no preimage)
    for proof in swap_request_signature_only.inputs_mut() {
        proof.sign_p2pk(alice_secret.clone()).unwrap();
    }

    let result = mint.process_swap_request(swap_request_signature_only).await;
    assert!(
        result.is_err(),
        "Should fail with only signature (no preimage)"
    );
    println!("✓ Spending with ONLY signature failed as expected");

    // Step 8: Now try to spend the HTLC proofs with correct preimage + signature
    let mut swap_request_both =
        cdk_common::nuts::SwapRequest::new(htlc_proofs.clone(), new_outputs.clone());

    // Add preimage and sign all proofs
    for proof in swap_request_both.inputs_mut() {
        proof.add_preimage(preimage.clone());
        proof.sign_p2pk(alice_secret.clone()).unwrap();
    }

    let result = mint.process_swap_request(swap_request_both).await;
    assert!(
        result.is_ok(),
        "Should succeed with correct preimage and signature"
    );
    println!("✓ HTLC spent successfully with correct preimage AND signature");
}

/// Test: HTLC with wrong preimage
///
/// Verifies that providing an incorrect preimage fails even with correct signature
#[tokio::test]
async fn test_htlc_wrong_preimage() {
    let test_mint = TestMintHelper::new().await.unwrap();
    let mint = test_mint.mint();

    let (alice_secret, alice_pubkey) = create_test_keypair();
    let (hash, _correct_preimage) = create_test_hash_and_preimage();

    // Mint regular proofs and swap for HTLC proofs
    let input_amount = Amount::from(10);
    let input_proofs = test_mint.mint_proofs(input_amount).await.unwrap();

    let spending_conditions = SpendingConditions::new_htlc_hash(
        &hash,
        Some(Conditions {
            locktime: None,
            pubkeys: Some(vec![alice_pubkey]),
            refund_keys: None,
            num_sigs: None,
            sig_flag: SigFlag::default(),
            num_sigs_refund: None,
        }),
    )
    .unwrap();

    let split_amounts = test_mint.split_amount(input_amount).unwrap();
    let (htlc_outputs, blinding_factors, secrets) = unzip3(
        split_amounts
            .iter()
            .map(|&amt| test_mint.create_blinded_message(amt, &spending_conditions))
            .collect(),
    );

    let swap_request =
        cdk_common::nuts::SwapRequest::new(input_proofs.clone(), htlc_outputs.clone());
    let swap_response = mint.process_swap_request(swap_request).await.unwrap();

    use cdk_common::dhke::construct_proofs;
    let htlc_proofs = construct_proofs(
        swap_response.signatures.clone(),
        blinding_factors.clone(),
        secrets.clone(),
        &test_mint.public_keys_of_the_active_sat_keyset,
    )
    .unwrap();

    // Try to spend with WRONG preimage (but correct signature)
    use crate::test_helpers::mint::create_test_blinded_messages;
    let (new_outputs, _) = create_test_blinded_messages(mint, input_amount)
        .await
        .unwrap();
    let mut swap_request =
        cdk_common::nuts::SwapRequest::new(htlc_proofs.clone(), new_outputs.clone());

    let wrong_preimage = "this_is_the_wrong_preimage";
    for proof in swap_request.inputs_mut() {
        proof.add_preimage(wrong_preimage.to_string());
        proof.sign_p2pk(alice_secret.clone()).unwrap();
    }

    let result = mint.process_swap_request(swap_request).await;
    assert!(result.is_err(), "Should fail with wrong preimage");
    println!("✓ HTLC with wrong preimage failed as expected");
}

/// Test: HTLC locktime after expiry (refund path)
///
/// Verifies that after locktime expires, refund keys can spend without preimage
#[tokio::test]
async fn test_htlc_locktime_after_expiry() {
    let test_mint = TestMintHelper::new().await.unwrap();
    let mint = test_mint.mint();

    let (_alice_secret, alice_pubkey) = create_test_keypair();
    let (bob_secret, bob_pubkey) = create_test_keypair();
    let (hash, _preimage) = create_test_hash_and_preimage();

    // Create HTLC with locktime in the PAST (already expired) and Bob as refund key
    let past_locktime = cdk_common::util::unix_time() - 1000;

    let input_amount = Amount::from(10);
    let input_proofs = test_mint.mint_proofs(input_amount).await.unwrap();

    let spending_conditions = SpendingConditions::new_htlc_hash(
        &hash,
        Some(Conditions {
            locktime: Some(past_locktime),
            pubkeys: Some(vec![alice_pubkey]),
            refund_keys: Some(vec![bob_pubkey]),
            num_sigs: None,
            sig_flag: SigFlag::default(),
            num_sigs_refund: None,
        }),
    )
    .unwrap();

    let split_amounts = test_mint.split_amount(input_amount).unwrap();
    let (htlc_outputs, blinding_factors, secrets) = unzip3(
        split_amounts
            .iter()
            .map(|&amt| test_mint.create_blinded_message(amt, &spending_conditions))
            .collect(),
    );

    let swap_request =
        cdk_common::nuts::SwapRequest::new(input_proofs.clone(), htlc_outputs.clone());
    let swap_response = mint.process_swap_request(swap_request).await.unwrap();

    use cdk_common::dhke::construct_proofs;
    let htlc_proofs = construct_proofs(
        swap_response.signatures.clone(),
        blinding_factors.clone(),
        secrets.clone(),
        &test_mint.public_keys_of_the_active_sat_keyset,
    )
    .unwrap();

    // After locktime, Bob (refund key) can spend WITHOUT preimage
    use crate::test_helpers::mint::create_test_blinded_messages;
    let (new_outputs, _) = create_test_blinded_messages(mint, input_amount)
        .await
        .unwrap();
    let mut swap_request =
        cdk_common::nuts::SwapRequest::new(htlc_proofs.clone(), new_outputs.clone());

    // Bob signs (no preimage needed after locktime)
    // Note: Must call add_preimage first (even with empty string) to create HTLC witness,
    // otherwise sign_p2pk creates P2PK witness instead
    for proof in swap_request.inputs_mut() {
        proof.add_preimage(String::new()); // Empty preimage for refund path
        proof.sign_p2pk(bob_secret.clone()).unwrap();
    }

    let result = mint.process_swap_request(swap_request).await;
    assert!(
        result.is_ok(),
        "Bob should be able to spend after locktime without preimage"
    );
    println!("✓ HTLC spent by refund key after locktime (no preimage needed)");
}

/// Test: HTLC with multisig (preimage + 2-of-3 signatures)
///
/// Verifies that HTLC can require preimage AND multiple signatures
#[tokio::test]
async fn test_htlc_multisig_2of3() {
    let test_mint = TestMintHelper::new().await.unwrap();
    let mint = test_mint.mint();

    let (alice_secret, alice_pubkey) = create_test_keypair();
    let (bob_secret, bob_pubkey) = create_test_keypair();
    let (_charlie_secret, charlie_pubkey) = create_test_keypair();
    let (hash, preimage) = create_test_hash_and_preimage();

    // Create HTLC requiring preimage + 2-of-3 signatures (Alice, Bob, Charlie)
    let input_amount = Amount::from(10);
    let input_proofs = test_mint.mint_proofs(input_amount).await.unwrap();

    let spending_conditions = SpendingConditions::new_htlc_hash(
        &hash,
        Some(Conditions {
            locktime: None,
            pubkeys: Some(vec![alice_pubkey, bob_pubkey, charlie_pubkey]),
            refund_keys: None,
            num_sigs: Some(2), // Require 2 of 3
            sig_flag: SigFlag::default(),
            num_sigs_refund: None,
        }),
    )
    .unwrap();

    let split_amounts = test_mint.split_amount(input_amount).unwrap();
    let (htlc_outputs, blinding_factors, secrets) = unzip3(
        split_amounts
            .iter()
            .map(|&amt| test_mint.create_blinded_message(amt, &spending_conditions))
            .collect(),
    );

    let swap_request =
        cdk_common::nuts::SwapRequest::new(input_proofs.clone(), htlc_outputs.clone());
    let swap_response = mint.process_swap_request(swap_request).await.unwrap();

    use cdk_common::dhke::construct_proofs;
    let htlc_proofs = construct_proofs(
        swap_response.signatures.clone(),
        blinding_factors.clone(),
        secrets.clone(),
        &test_mint.public_keys_of_the_active_sat_keyset,
    )
    .unwrap();

    // Try with preimage + only 1 signature (should fail - need 2)
    use crate::test_helpers::mint::create_test_blinded_messages;
    let (new_outputs, _) = create_test_blinded_messages(mint, input_amount)
        .await
        .unwrap();
    let mut swap_request_one_sig =
        cdk_common::nuts::SwapRequest::new(htlc_proofs.clone(), new_outputs.clone());

    for proof in swap_request_one_sig.inputs_mut() {
        proof.add_preimage(preimage.clone());
        proof.sign_p2pk(alice_secret.clone()).unwrap(); // Only Alice signs
    }

    let result = mint.process_swap_request(swap_request_one_sig).await;
    assert!(
        result.is_err(),
        "Should fail with only 1 signature (need 2)"
    );
    println!("✓ HTLC with 1-of-3 signatures failed as expected");

    // Now with preimage + 2 signatures (Alice and Bob) - should succeed
    let mut swap_request_two_sigs =
        cdk_common::nuts::SwapRequest::new(htlc_proofs.clone(), new_outputs.clone());

    for proof in swap_request_two_sigs.inputs_mut() {
        proof.add_preimage(preimage.clone());
        proof.sign_p2pk(alice_secret.clone()).unwrap();
        proof.sign_p2pk(bob_secret.clone()).unwrap();
    }

    let result = mint.process_swap_request(swap_request_two_sigs).await;
    assert!(
        result.is_ok(),
        "Should succeed with preimage + 2-of-3 signatures"
    );
    println!("✓ HTLC spent with preimage + 2-of-3 signatures");
}

/// Test: HTLC receiver path still works after locktime (NUT-14 compliance)
///
/// Per NUT-14: "This pathway is ALWAYS available to the receivers, as possession
/// of the preimage confirms performance of the Sender's wishes."
///
/// This test verifies that even after locktime has passed, the receiver can still
/// spend using the preimage + pubkeys path (not just the refund path).
#[tokio::test]
async fn test_htlc_receiver_path_after_locktime() {
    let test_mint = TestMintHelper::new().await.unwrap();
    let mint = test_mint.mint();

    let (alice_secret, alice_pubkey) = create_test_keypair();
    let (_bob_secret, bob_pubkey) = create_test_keypair();
    let (hash, preimage) = create_test_hash_and_preimage();

    // Create HTLC with locktime in the PAST (already expired)
    // Alice is the receiver (pubkeys), Bob is the refund key
    let past_locktime = cdk_common::util::unix_time() - 1000;

    let input_amount = Amount::from(10);
    let input_proofs = test_mint.mint_proofs(input_amount).await.unwrap();

    let spending_conditions = SpendingConditions::new_htlc_hash(
        &hash,
        Some(Conditions {
            locktime: Some(past_locktime),
            pubkeys: Some(vec![alice_pubkey]),
            refund_keys: Some(vec![bob_pubkey]),
            num_sigs: None,
            sig_flag: SigFlag::default(),
            num_sigs_refund: None,
        }),
    )
    .unwrap();

    let split_amounts = test_mint.split_amount(input_amount).unwrap();
    let (htlc_outputs, blinding_factors, secrets) = unzip3(
        split_amounts
            .iter()
            .map(|&amt| test_mint.create_blinded_message(amt, &spending_conditions))
            .collect(),
    );

    let swap_request =
        cdk_common::nuts::SwapRequest::new(input_proofs.clone(), htlc_outputs.clone());
    let swap_response = mint.process_swap_request(swap_request).await.unwrap();

    use cdk_common::dhke::construct_proofs;
    let htlc_proofs = construct_proofs(
        swap_response.signatures.clone(),
        blinding_factors.clone(),
        secrets.clone(),
        &test_mint.public_keys_of_the_active_sat_keyset,
    )
    .unwrap();

    // Even though locktime has passed, Alice (receiver) should STILL be able to spend
    // using the preimage + her signature (receiver path is ALWAYS available per NUT-14)
    use crate::test_helpers::mint::create_test_blinded_messages;
    let (new_outputs, _) = create_test_blinded_messages(mint, input_amount)
        .await
        .unwrap();
    let mut swap_request =
        cdk_common::nuts::SwapRequest::new(htlc_proofs.clone(), new_outputs.clone());

    // Alice provides preimage and signs (receiver path)
    for proof in swap_request.inputs_mut() {
        proof.add_preimage(preimage.clone());
        proof.sign_p2pk(alice_secret.clone()).unwrap();
    }

    let result = mint.process_swap_request(swap_request).await;
    assert!(
        result.is_ok(),
        "Receiver should be able to spend with preimage even after locktime"
    );
    println!("✓ HTLC receiver path works after locktime (NUT-14 compliant)");
}