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
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
//! NUT-14: Hashed Time Lock Contacts (HTLC)
//!
//! <https://github.com/cashubtc/nuts/blob/main/14.md>
use std::str::FromStr;
use bitcoin::hashes::sha256::Hash as Sha256Hash;
use bitcoin::hashes::Hash;
use bitcoin::secp256k1::schnorr::Signature;
use serde::{Deserialize, Serialize};
use thiserror::Error;
use super::nut00::Witness;
use super::nut10::Secret;
use super::nut11::valid_signatures;
use super::{Conditions, Proof};
use crate::nut10::get_pubkeys_and_required_sigs;
use crate::nut11::extract_signatures_from_witness;
use crate::util::{hex, unix_time};
use crate::SpendingConditions;
pub mod serde_htlc_witness;
/// NUT14 Errors
#[derive(Debug, Error)]
pub enum Error {
/// Incorrect secret kind
#[error("Secret is not a HTLC secret")]
IncorrectSecretKind,
/// HTLC locktime has already passed
#[error("Locktime in past")]
LocktimeInPast,
/// Witness signature is not valid
#[error("Invalid signature")]
InvalidSignature,
/// Hash Required
#[error("Hash required")]
HashRequired,
/// Hash is not valid
#[error("Hash is not valid")]
InvalidHash,
/// Preimage does not match
#[error("Preimage does not match")]
Preimage,
/// HTLC preimage must be valid hex encoding
#[error("Preimage must be valid hex encoding")]
InvalidHexPreimage,
/// HTLC preimage must be exactly 32 bytes
#[error("Preimage must be exactly 32 bytes (64 hex characters)")]
PreimageInvalidSize,
/// Witness Signatures not provided
#[error("Witness did not provide signatures")]
SignaturesNotProvided,
/// SIG_ALL not supported in this context
#[error("SIG_ALL proofs must be verified using a different method")]
SigAllNotSupportedHere,
/// HTLC Spend conditions not met
#[error("HTLC spend conditions are not met")]
SpendConditionsNotMet,
/// From hex error
#[error(transparent)]
HexError(#[from] hex::Error),
/// Secp256k1 error
#[error(transparent)]
Secp256k1(#[from] bitcoin::secp256k1::Error),
/// NUT11 Error
#[error(transparent)]
NUT11(#[from] super::nut11::Error),
#[error(transparent)]
/// Serde Error
Serde(#[from] serde_json::Error),
}
/// HTLC Witness
#[derive(Default, Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[cfg_attr(feature = "swagger", derive(utoipa::ToSchema))]
pub struct HTLCWitness {
/// Preimage
pub preimage: String,
/// Signatures
#[serde(skip_serializing_if = "Option::is_none")]
pub signatures: Option<Vec<String>>,
}
impl HTLCWitness {
/// Decode the preimage from hex and verify it's exactly 32 bytes
///
/// Returns the 32-byte preimage data if valid, or an error if:
/// - The hex decoding fails
/// - The decoded data is not exactly 32 bytes
pub fn preimage_data(&self) -> Result<[u8; 32], Error> {
const REQUIRED_PREIMAGE_BYTES: usize = 32;
// Decode the 64-character hex string to bytes
let preimage_bytes = hex::decode(&self.preimage).map_err(|_| Error::InvalidHexPreimage)?;
// Verify the preimage is exactly 32 bytes
if preimage_bytes.len() != REQUIRED_PREIMAGE_BYTES {
return Err(Error::PreimageInvalidSize);
}
// Convert to fixed-size array
let mut array = [0u8; 32];
array.copy_from_slice(&preimage_bytes);
Ok(array)
}
}
impl Proof {
/// Verify HTLC
///
/// Per NUT-14, there are two spending pathways:
/// 1. Receiver path (preimage + pubkeys): ALWAYS available
/// 2. Sender/Refund path (refund keys, no preimage): available AFTER locktime
///
/// The verification tries to determine which path is being used based on
/// the witness provided, then validates accordingly.
pub fn verify_htlc(&self) -> Result<(), Error> {
let secret: Secret = self.secret.clone().try_into()?;
let spending_conditions: Conditions = secret
.secret_data()
.tags()
.cloned()
.unwrap_or_default()
.try_into()
.map_err(|_| Error::SpendConditionsNotMet)?;
if spending_conditions.sig_flag == super::SigFlag::SigAll {
return Err(Error::SigAllNotSupportedHere);
}
if secret.kind() != super::Kind::HTLC {
return Err(Error::IncorrectSecretKind);
}
// Get the spending requirements (includes both receiver and refund paths)
let now = unix_time();
let requirements =
super::nut10::get_pubkeys_and_required_sigs(&secret, now).map_err(|err| match err {
super::nut10::Error::NUT14(nut14_err) => nut14_err,
_ => Error::SpendConditionsNotMet,
})?;
// Try to extract HTLC witness - must be correct type
let htlc_witness = match &self.witness {
Some(Witness::HTLCWitness(witness)) => witness,
_ => {
// Wrong witness type or no witness
// If refund path is available with 0 required sigs, anyone can spend
if let Some(refund_path) = &requirements.refund_path {
if refund_path.required_sigs == 0 {
return Ok(());
}
}
return Err(Error::IncorrectSecretKind);
}
};
// Try to verify the preimage and capture the specific error if it fails
let preimage_result = verify_htlc_preimage(htlc_witness, &secret);
// Determine which path to use:
// - If preimage is valid → use receiver path (always available)
// - If preimage is invalid/missing → try refund path (if available)
if preimage_result.is_ok() {
// Receiver path: preimage valid, now check signatures against pubkeys
if requirements.required_sigs == 0 {
return Ok(());
}
let witness_signatures = htlc_witness
.signatures
.as_ref()
.ok_or(Error::SignaturesNotProvided)?;
let signatures: Vec<Signature> = witness_signatures
.iter()
.map(|s| Signature::from_str(s))
.collect::<Result<Vec<_>, _>>()?;
let msg: &[u8] = self.secret.as_bytes();
let valid_sig_count = valid_signatures(msg, &requirements.pubkeys, &signatures)?;
if valid_sig_count >= requirements.required_sigs {
Ok(())
} else {
Err(Error::NUT11(super::nut11::Error::SpendConditionsNotMet))
}
} else if let Some(refund_path) = &requirements.refund_path {
// Refund path: preimage not valid/provided, but locktime has passed
// Check signatures against refund keys
if refund_path.required_sigs == 0 {
// Anyone can spend (locktime passed, no refund keys)
return Ok(());
}
let witness_signatures = htlc_witness
.signatures
.as_ref()
.ok_or(Error::SignaturesNotProvided)?;
let signatures: Vec<Signature> = witness_signatures
.iter()
.map(|s| Signature::from_str(s))
.collect::<Result<Vec<_>, _>>()?;
let msg: &[u8] = self.secret.as_bytes();
let valid_sig_count = valid_signatures(msg, &refund_path.pubkeys, &signatures)?;
if valid_sig_count >= refund_path.required_sigs {
Ok(())
} else {
Err(Error::NUT11(super::nut11::Error::SpendConditionsNotMet))
}
} else {
// No valid preimage and refund path not available (locktime not passed)
// Return the specific error from preimage verification
preimage_result
}
}
/// Add Preimage
#[inline]
pub fn add_preimage(&mut self, preimage: String) {
let signatures = self
.witness
.as_ref()
.map(super::nut00::Witness::signatures)
.unwrap_or_default();
self.witness = Some(Witness::HTLCWitness(HTLCWitness {
preimage,
signatures,
}))
}
}
impl SpendingConditions {
/// New HTLC [SpendingConditions]
pub fn new_htlc(preimage: String, conditions: Option<Conditions>) -> Result<Self, Error> {
const MAX_PREIMAGE_BYTES: usize = 32;
let preimage_bytes = hex::decode(preimage)?;
if preimage_bytes.len() != MAX_PREIMAGE_BYTES {
return Err(Error::PreimageInvalidSize);
}
let htlc = Sha256Hash::hash(&preimage_bytes);
Ok(Self::HTLCConditions {
data: htlc,
conditions,
})
}
/// New HTLC [SpendingConditions] from a hash directly instead of preimage
pub fn new_htlc_hash(hash: &str, conditions: Option<Conditions>) -> Result<Self, Error> {
let hash = Sha256Hash::from_str(hash).map_err(|_| Error::InvalidHash)?;
Ok(Self::HTLCConditions {
data: hash,
conditions,
})
}
}
/// Verify that a preimage matches the hash in the secret data
///
/// The preimage should be a 64-character hex string representing 32 bytes.
/// We decode it from hex, hash it with SHA256, and compare to the hash in secret.data
fn verify_htlc_preimage(witness: &HTLCWitness, secret: &Secret) -> Result<(), Error> {
use bitcoin::hashes::sha256::Hash as Sha256Hash;
use bitcoin::hashes::Hash;
// Get the hash lock from the secret data
let hash_lock =
Sha256Hash::from_str(secret.secret_data().data()).map_err(|_| Error::InvalidHash)?;
// Decode and validate the preimage (returns [u8; 32])
let preimage_bytes = witness.preimage_data()?;
// Hash the 32-byte preimage
let preimage_hash = Sha256Hash::hash(&preimage_bytes);
// Compare with the hash lock
if hash_lock.ne(&preimage_hash) {
return Err(Error::Preimage);
}
Ok(())
}
/// Verify HTLC SIG_ALL signatures
///
/// Do NOT call this directly. This is called only from 'verify_full_sig_all_check',
/// which has already done many important SIG_ALL checks. This performs the final
/// signature verification for SIG_ALL+HTLC transactions.
///
/// Per NUT-14, there are two spending pathways:
/// 1. Receiver path (preimage + pubkeys): ALWAYS available
/// 2. Sender/Refund path (refund keys, no preimage): available AFTER locktime
pub(crate) fn verify_sig_all_htlc(first_input: &Proof, msg_to_sign: String) -> Result<(), Error> {
// Get the first input, as it's the one with the signatures
let first_secret =
Secret::try_from(&first_input.secret).map_err(|_| Error::IncorrectSecretKind)?;
// Record current time for locktime evaluation
let current_time = crate::util::unix_time();
// Get the spending requirements (includes both receiver and refund paths)
let requirements = get_pubkeys_and_required_sigs(&first_secret, current_time)
.map_err(|_| Error::SpendConditionsNotMet)?;
// Try to extract HTLC witness and check if preimage is valid
let htlc_witness = match first_input.witness.as_ref() {
Some(super::Witness::HTLCWitness(witness)) => Some(witness),
_ => None,
};
// Check if a valid preimage is provided
let preimage_valid = htlc_witness
.map(|w| verify_htlc_preimage(w, &first_secret).is_ok())
.unwrap_or(false);
// Check for "anyone can spend" case first (preimage invalid, locktime passed, no refund keys)
// This doesn't require any signatures
if !preimage_valid {
if let Some(refund_path) = &requirements.refund_path {
if refund_path.required_sigs == 0 {
return Ok(());
}
}
}
// Get the witness (needed for signature extraction)
let first_witness = first_input
.witness
.as_ref()
.ok_or(Error::SignaturesNotProvided)?;
// Determine which path to use:
// - If preimage is valid → use receiver path (always available)
// - If preimage is invalid/missing → try refund path (if available)
if preimage_valid {
// Receiver path: preimage valid, now check SIG_ALL signatures against pubkeys
if requirements.required_sigs == 0 {
return Ok(());
}
let signatures = extract_signatures_from_witness(first_witness)?;
let valid_sig_count = super::nut11::valid_signatures(
msg_to_sign.as_bytes(),
&requirements.pubkeys,
&signatures,
)
.map_err(|_| Error::InvalidSignature)?;
if valid_sig_count >= requirements.required_sigs {
Ok(())
} else {
Err(Error::SpendConditionsNotMet)
}
} else if let Some(refund_path) = &requirements.refund_path {
// Refund path: preimage not valid/provided, but locktime has passed
// Check SIG_ALL signatures against refund keys
let signatures = extract_signatures_from_witness(first_witness)?;
let valid_sig_count = super::nut11::valid_signatures(
msg_to_sign.as_bytes(),
&refund_path.pubkeys,
&signatures,
)
.map_err(|_| Error::InvalidSignature)?;
if valid_sig_count >= refund_path.required_sigs {
Ok(())
} else {
Err(Error::SpendConditionsNotMet)
}
} else {
// No valid preimage and refund path not available (locktime not passed)
Err(Error::SpendConditionsNotMet)
}
}
#[cfg(test)]
mod tests {
use bitcoin::hashes::sha256::Hash as Sha256Hash;
use bitcoin::hashes::Hash;
use super::*;
use crate::nuts::nut00::Witness;
use crate::nuts::nut10::Kind;
use crate::nuts::Nut10Secret;
use crate::secret::Secret as SecretString;
use crate::SecretData;
/// Tests that verify_htlc correctly accepts a valid HTLC with the correct preimage.
///
/// This test ensures that a properly formed HTLC proof with the correct preimage
/// passes verification.
///
/// Mutant testing: Combined with negative tests, this catches mutations that
/// replace verify_htlc with Ok(()) since the negative tests will fail.
#[test]
fn test_verify_htlc_valid() {
// Create a valid HTLC secret with a known preimage (32 bytes)
let preimage_bytes = [42u8; 32]; // 32-byte preimage
let hash = Sha256Hash::hash(&preimage_bytes);
let hash_str = hash.to_string();
let nut10_secret = Nut10Secret::new(
Kind::HTLC,
SecretData::new(hash_str, None::<Vec<Vec<String>>>),
);
let secret: SecretString = nut10_secret.try_into().unwrap();
let htlc_witness = HTLCWitness {
preimage: hex::encode(preimage_bytes),
signatures: None,
};
let proof = Proof {
amount: crate::Amount::from(1),
keyset_id: crate::nuts::nut02::Id::from_str("00deadbeef123456").unwrap(),
secret,
c: crate::nuts::nut01::PublicKey::from_hex(
"02a9acc1e48c25eeeb9289b5031cc57da9fe72f3fe2861d264bdc074209b107ba2",
)
.unwrap(),
witness: Some(Witness::HTLCWitness(htlc_witness)),
dleq: None,
p2pk_e: None,
};
// Valid HTLC should verify successfully
assert!(proof.verify_htlc().is_ok());
}
/// Tests that verify_htlc correctly rejects an HTLC with a wrong preimage.
///
/// This test is critical for security - if the verification function doesn't properly
/// check the preimage against the hash, an attacker could spend HTLC-locked funds
/// without knowing the correct preimage.
///
/// Mutant testing: Catches mutations that replace verify_htlc with Ok(()) or remove
/// the preimage verification logic.
#[test]
fn test_verify_htlc_wrong_preimage() {
// Create an HTLC secret with a specific hash (32 bytes)
let correct_preimage_bytes = [42u8; 32];
let hash = Sha256Hash::hash(&correct_preimage_bytes);
let hash_str = hash.to_string();
let nut10_secret = Nut10Secret::new(
Kind::HTLC,
SecretData::new(hash_str, None::<Vec<Vec<String>>>),
);
let secret: SecretString = nut10_secret.try_into().unwrap();
// Use a different preimage in the witness
let wrong_preimage_bytes = [99u8; 32]; // Different from correct preimage
let htlc_witness = HTLCWitness {
preimage: hex::encode(wrong_preimage_bytes),
signatures: None,
};
let proof = Proof {
amount: crate::Amount::from(1),
keyset_id: crate::nuts::nut02::Id::from_str("00deadbeef123456").unwrap(),
secret,
c: crate::nuts::nut01::PublicKey::from_hex(
"02a9acc1e48c25eeeb9289b5031cc57da9fe72f3fe2861d264bdc074209b107ba2",
)
.unwrap(),
witness: Some(Witness::HTLCWitness(htlc_witness)),
dleq: None,
p2pk_e: None,
};
// Verification should fail with wrong preimage
let result = proof.verify_htlc();
assert!(result.is_err());
assert!(matches!(result.unwrap_err(), Error::Preimage));
}
/// Tests that verify_htlc correctly rejects an HTLC with an invalid hash format.
///
/// This test ensures that the verification function properly validates that the
/// hash in the secret data is a valid SHA256 hash.
///
/// Mutant testing: Catches mutations that replace verify_htlc with Ok(()) or
/// remove the hash validation logic.
#[test]
fn test_verify_htlc_invalid_hash() {
// Create an HTLC secret with an invalid hash (not a valid hex string)
let invalid_hash = "not_a_valid_hash";
let nut10_secret = Nut10Secret::new(
Kind::HTLC,
SecretData::new(invalid_hash.to_string(), None::<Vec<Vec<String>>>),
);
let secret: SecretString = nut10_secret.try_into().unwrap();
let preimage_bytes = [42u8; 32]; // Valid 32-byte preimage
let htlc_witness = HTLCWitness {
preimage: hex::encode(preimage_bytes),
signatures: None,
};
let proof = Proof {
amount: crate::Amount::from(1),
keyset_id: crate::nuts::nut02::Id::from_str("00deadbeef123456").unwrap(),
secret,
c: crate::nuts::nut01::PublicKey::from_hex(
"02a9acc1e48c25eeeb9289b5031cc57da9fe72f3fe2861d264bdc074209b107ba2",
)
.unwrap(),
witness: Some(Witness::HTLCWitness(htlc_witness)),
dleq: None,
p2pk_e: None,
};
// Verification should fail with invalid hash
let result = proof.verify_htlc();
assert!(result.is_err());
assert!(matches!(result.unwrap_err(), Error::InvalidHash));
}
/// Tests that verify_htlc correctly rejects an HTLC with the wrong witness type.
///
/// This test ensures that the verification function checks that the witness is
/// of the correct type (HTLCWitness) and not some other witness type.
///
/// Mutant testing: Catches mutations that replace verify_htlc with Ok(()) or
/// remove the witness type check.
#[test]
fn test_verify_htlc_wrong_witness_type() {
// Create an HTLC secret
let preimage = "test_preimage";
let hash = Sha256Hash::hash(preimage.as_bytes());
let hash_str = hash.to_string();
let nut10_secret = Nut10Secret::new(
Kind::HTLC,
SecretData::new(hash_str, None::<Vec<Vec<String>>>),
);
let secret: SecretString = nut10_secret.try_into().unwrap();
// Create proof with wrong witness type (P2PKWitness instead of HTLCWitness)
let proof = Proof {
amount: crate::Amount::from(1),
keyset_id: crate::nuts::nut02::Id::from_str("00deadbeef123456").unwrap(),
secret,
c: crate::nuts::nut01::PublicKey::from_hex(
"02a9acc1e48c25eeeb9289b5031cc57da9fe72f3fe2861d264bdc074209b107ba2",
)
.unwrap(),
witness: Some(Witness::P2PKWitness(super::super::nut11::P2PKWitness {
signatures: vec![],
})),
dleq: None,
p2pk_e: None,
};
// Verification should fail with wrong witness type
let result = proof.verify_htlc();
assert!(result.is_err());
assert!(matches!(result.unwrap_err(), Error::IncorrectSecretKind));
}
/// Tests that add_preimage correctly adds a preimage to the proof.
///
/// This test ensures that add_preimage actually modifies the witness and doesn't
/// just return without doing anything.
///
/// Mutant testing: Catches mutations that replace add_preimage with () without
/// actually adding the preimage.
#[test]
fn test_add_preimage() {
let preimage_bytes = [42u8; 32]; // 32-byte preimage
let hash = Sha256Hash::hash(&preimage_bytes);
let hash_str = hash.to_string();
let nut10_secret = Nut10Secret::new(
Kind::HTLC,
SecretData::new(hash_str, None::<Vec<Vec<String>>>),
);
let secret: SecretString = nut10_secret.try_into().unwrap();
let mut proof = Proof {
amount: crate::Amount::from(1),
keyset_id: crate::nuts::nut02::Id::from_str("00deadbeef123456").unwrap(),
secret,
c: crate::nuts::nut01::PublicKey::from_hex(
"02a9acc1e48c25eeeb9289b5031cc57da9fe72f3fe2861d264bdc074209b107ba2",
)
.unwrap(),
witness: None,
dleq: None,
p2pk_e: None,
};
// Initially, witness should be None
assert!(proof.witness.is_none());
// Add preimage (hex-encoded)
let preimage_hex = hex::encode(preimage_bytes);
proof.add_preimage(preimage_hex.clone());
// After adding, witness should be Some with HTLCWitness
assert!(proof.witness.is_some());
if let Some(Witness::HTLCWitness(witness)) = &proof.witness {
assert_eq!(witness.preimage, preimage_hex);
} else {
panic!("Expected HTLCWitness");
}
// The proof with added preimage should verify successfully
assert!(proof.verify_htlc().is_ok());
}
/// Tests that verify_htlc requires BOTH locktime expired AND no refund keys for "anyone can spend".
///
/// This test verifies that when locktime has passed and refund keys are present,
/// a signature from the refund keys is required (not anyone-can-spend).
///
/// Per NUT-14: After locktime, the refund path requires signatures from refund keys.
/// The "anyone can spend" case only applies when locktime passed AND no refund keys.
#[test]
fn test_htlc_locktime_and_refund_keys_logic() {
use crate::nuts::nut01::PublicKey;
use crate::nuts::nut10::Conditions;
let correct_preimage_bytes = [42u8; 32]; // 32-byte preimage
let hash = Sha256Hash::hash(&correct_preimage_bytes);
let hash_str = hash.to_string();
// Use WRONG preimage to force using refund path (not receiver path)
let wrong_preimage_bytes = [99u8; 32];
// Test: Locktime has passed (locktime=1) but refund keys ARE present
// Since we provide wrong preimage, receiver path fails, so we try refund path.
// Refund path with refund keys present should require a signature.
let refund_pubkey = PublicKey::from_hex(
"02a9acc1e48c25eeeb9289b5031cc57da9fe72f3fe2861d264bdc074209b107ba2",
)
.unwrap();
let conditions_with_refund = Conditions {
locktime: Some(1), // Locktime in past (current time is much larger)
pubkeys: None,
refund_keys: Some(vec![refund_pubkey]), // Refund key present
num_sigs: None,
sig_flag: crate::nuts::nut11::SigFlag::default(),
num_sigs_refund: None,
};
let nut10_secret = Nut10Secret::new(
Kind::HTLC,
SecretData::new(hash_str, Some(conditions_with_refund)),
);
let secret: SecretString = nut10_secret.try_into().unwrap();
let htlc_witness = HTLCWitness {
preimage: hex::encode(wrong_preimage_bytes), // Wrong preimage!
signatures: None, // No signature provided
};
let proof = Proof {
amount: crate::Amount::from(1),
keyset_id: crate::nuts::nut02::Id::from_str("00deadbeef123456").unwrap(),
secret,
c: crate::nuts::nut01::PublicKey::from_hex(
"02a9acc1e48c25eeeb9289b5031cc57da9fe72f3fe2861d264bdc074209b107ba2",
)
.unwrap(),
witness: Some(Witness::HTLCWitness(htlc_witness)),
dleq: None,
p2pk_e: None,
};
// Should FAIL because:
// 1. Wrong preimage means receiver path fails
// 2. Falls back to refund path (locktime passed)
// 3. Refund keys are present, so signature is required
// 4. No signature provided
let result = proof.verify_htlc();
assert!(
result.is_err(),
"Should fail when using refund path with refund keys but no signature"
);
}
}