lightning/offers/
refund.rs

1// This file is Copyright its original authors, visible in version control
2// history.
3//
4// This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5// or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7// You may not use this file except in accordance with one or both of these
8// licenses.
9
10//! Data structures and encoding for refunds.
11//!
12//! A [`Refund`] is an "offer for money" and is typically constructed by a merchant and presented
13//! directly to the customer. The recipient responds with a [`Bolt12Invoice`] to be paid.
14//!
15//! This is an [`InvoiceRequest`] produced *not* in response to an [`Offer`].
16//!
17//! [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
18//! [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
19//! [`Offer`]: crate::offers::offer::Offer
20//!
21//! # Example
22//!
23//! ```
24//! extern crate bitcoin;
25//! extern crate core;
26//! extern crate lightning;
27//!
28//! use core::convert::TryFrom;
29//! use core::time::Duration;
30//!
31//! use bitcoin::network::Network;
32//! use bitcoin::secp256k1::{Keypair, PublicKey, Secp256k1, SecretKey};
33//! use lightning::offers::parse::Bolt12ParseError;
34//! use lightning::offers::refund::{Refund, RefundBuilder};
35//! use lightning::util::ser::{Readable, Writeable};
36//!
37//! # use lightning::blinded_path::message::BlindedMessagePath;
38//! # #[cfg(feature = "std")]
39//! # use std::time::SystemTime;
40//! #
41//! # fn create_blinded_path() -> BlindedMessagePath { unimplemented!() }
42//! # fn create_another_blinded_path() -> BlindedMessagePath { unimplemented!() }
43//! #
44//! # #[cfg(feature = "std")]
45//! # fn build() -> Result<(), Bolt12ParseError> {
46//! let secp_ctx = Secp256k1::new();
47//! let keys = Keypair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
48//! let pubkey = PublicKey::from(keys);
49//!
50//! let expiration = SystemTime::now() + Duration::from_secs(24 * 60 * 60);
51//! let refund = RefundBuilder::new(vec![1; 32], pubkey, 20_000)?
52//!     .description("coffee, large".to_string())
53//!     .absolute_expiry(expiration.duration_since(SystemTime::UNIX_EPOCH).unwrap())
54//!     .issuer("Foo Bar".to_string())
55//!     .path(create_blinded_path())
56//!     .path(create_another_blinded_path())
57//!     .chain(Network::Bitcoin)
58//!     .payer_note("refund for order #12345".to_string())
59//!     .build()?;
60//!
61//! // Encode as a bech32 string for use in a QR code.
62//! let encoded_refund = refund.to_string();
63//!
64//! // Parse from a bech32 string after scanning from a QR code.
65//! let refund = encoded_refund.parse::<Refund>()?;
66//!
67//! // Encode refund as raw bytes.
68//! let mut bytes = Vec::new();
69//! refund.write(&mut bytes).unwrap();
70//!
71//! // Decode raw bytes into an refund.
72//! let refund = Refund::try_from(bytes)?;
73//! # Ok(())
74//! # }
75//! ```
76//!
77//! # Note
78//!
79//! If constructing a [`Refund`] for use with a [`ChannelManager`], use
80//! [`ChannelManager::create_refund_builder`] instead of [`RefundBuilder::new`].
81//!
82//! [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
83//! [`ChannelManager::create_refund_builder`]: crate::ln::channelmanager::ChannelManager::create_refund_builder
84
85use bitcoin::constants::ChainHash;
86use bitcoin::network::Network;
87use bitcoin::secp256k1::{PublicKey, Secp256k1, self};
88use core::hash::{Hash, Hasher};
89use core::ops::Deref;
90use core::str::FromStr;
91use core::time::Duration;
92use crate::sign::EntropySource;
93use crate::io;
94use crate::blinded_path::message::BlindedMessagePath;
95use crate::blinded_path::payment::BlindedPaymentPath;
96use crate::types::payment::PaymentHash;
97use crate::ln::channelmanager::PaymentId;
98use crate::types::features::InvoiceRequestFeatures;
99use crate::ln::inbound_payment::{ExpandedKey, IV_LEN};
100use crate::ln::msgs::{DecodeError, MAX_VALUE_MSAT};
101use crate::offers::invoice_request::{ExperimentalInvoiceRequestTlvStream, ExperimentalInvoiceRequestTlvStreamRef, InvoiceRequestTlvStream, InvoiceRequestTlvStreamRef};
102use crate::offers::nonce::Nonce;
103use crate::offers::offer::{ExperimentalOfferTlvStream, ExperimentalOfferTlvStreamRef, OfferTlvStream, OfferTlvStreamRef};
104use crate::offers::parse::{Bech32Encode, Bolt12ParseError, Bolt12SemanticError, ParsedMessage};
105use crate::offers::payer::{PayerContents, PayerTlvStream, PayerTlvStreamRef};
106use crate::offers::signer::{Metadata, MetadataMaterial, self};
107use crate::util::ser::{CursorReadable, Readable, WithoutLength, Writeable, Writer};
108use crate::util::string::PrintableString;
109
110#[cfg(not(c_bindings))]
111use {
112	crate::offers::invoice::{DerivedSigningPubkey, ExplicitSigningPubkey, InvoiceBuilder},
113};
114#[cfg(c_bindings)]
115use {
116	crate::offers::invoice::{InvoiceWithDerivedSigningPubkeyBuilder, InvoiceWithExplicitSigningPubkeyBuilder},
117};
118
119#[allow(unused_imports)]
120use crate::prelude::*;
121
122#[cfg(feature = "std")]
123use std::time::SystemTime;
124
125pub(super) const IV_BYTES_WITH_METADATA: &[u8; IV_LEN] = b"LDK Refund ~~~~~";
126pub(super) const IV_BYTES_WITHOUT_METADATA: &[u8; IV_LEN] = b"LDK Refund v2~~~";
127
128/// Builds a [`Refund`] for the "offer for money" flow.
129///
130/// See [module-level documentation] for usage.
131///
132/// This is not exported to bindings users as builder patterns don't map outside of move semantics.
133///
134/// [module-level documentation]: self
135pub struct RefundBuilder<'a, T: secp256k1::Signing> {
136	refund: RefundContents,
137	secp_ctx: Option<&'a Secp256k1<T>>,
138}
139
140/// Builds a [`Refund`] for the "offer for money" flow.
141///
142/// See [module-level documentation] for usage.
143///
144/// [module-level documentation]: self
145#[cfg(c_bindings)]
146#[derive(Clone)]
147pub struct RefundMaybeWithDerivedMetadataBuilder<'a> {
148	refund: RefundContents,
149	secp_ctx: Option<&'a Secp256k1<secp256k1::All>>,
150}
151
152macro_rules! refund_explicit_metadata_builder_methods { () => {
153	/// Creates a new builder for a refund using the `signing_pubkey` for the public node id to send
154	/// to if no [`Refund::paths`] are set. Otherwise, `signing_pubkey` may be a transient pubkey.
155	///
156	/// Additionally, sets the required (empty) [`Refund::description`], [`Refund::payer_metadata`],
157	/// and [`Refund::amount_msats`].
158	///
159	/// # Note
160	///
161	/// If constructing a [`Refund`] for use with a [`ChannelManager`], use
162	/// [`ChannelManager::create_refund_builder`] instead of [`RefundBuilder::new`].
163	///
164	/// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
165	/// [`ChannelManager::create_refund_builder`]: crate::ln::channelmanager::ChannelManager::create_refund_builder
166	pub fn new(
167		metadata: Vec<u8>, signing_pubkey: PublicKey, amount_msats: u64
168	) -> Result<Self, Bolt12SemanticError> {
169		if amount_msats > MAX_VALUE_MSAT {
170			return Err(Bolt12SemanticError::InvalidAmount);
171		}
172
173		let metadata = Metadata::Bytes(metadata);
174		Ok(Self {
175			refund: RefundContents {
176				payer: PayerContents(metadata), description: String::new(), absolute_expiry: None,
177				issuer: None, chain: None, amount_msats, features: InvoiceRequestFeatures::empty(),
178				quantity: None, payer_signing_pubkey: signing_pubkey, payer_note: None, paths: None,
179				#[cfg(test)]
180				experimental_foo: None,
181				#[cfg(test)]
182				experimental_bar: None,
183			},
184			secp_ctx: None,
185		})
186	}
187} }
188
189macro_rules! refund_builder_methods { (
190	$self: ident, $self_type: ty, $return_type: ty, $return_value: expr, $secp_context: ty $(, $self_mut: tt)?
191) => {
192	/// Similar to [`RefundBuilder::new`] except, if [`RefundBuilder::path`] is called, the payer id
193	/// is derived from the given [`ExpandedKey`] and nonce. This provides sender privacy by using a
194	/// different payer id for each refund, assuming a different nonce is used.  Otherwise, the
195	/// provided `node_id` is used for the payer id.
196	///
197	/// Also, sets the metadata when [`RefundBuilder::build`] is called such that it can be used by
198	/// [`Bolt12Invoice::verify_using_metadata`] to determine if the invoice was produced for the
199	/// refund given an [`ExpandedKey`]. However, if [`RefundBuilder::path`] is called, then the
200	/// metadata must be included in each [`BlindedMessagePath`] instead. In this case, use
201	/// [`Bolt12Invoice::verify_using_payer_data`].
202	///
203	/// The `payment_id` is encrypted in the metadata and should be unique. This ensures that only
204	/// one invoice will be paid for the refund and that payments can be uniquely identified.
205	///
206	/// [`Bolt12Invoice::verify_using_metadata`]: crate::offers::invoice::Bolt12Invoice::verify_using_metadata
207	/// [`Bolt12Invoice::verify_using_payer_data`]: crate::offers::invoice::Bolt12Invoice::verify_using_payer_data
208	/// [`ExpandedKey`]: crate::ln::inbound_payment::ExpandedKey
209	pub fn deriving_signing_pubkey(
210		node_id: PublicKey, expanded_key: &ExpandedKey, nonce: Nonce,
211		secp_ctx: &'a Secp256k1<$secp_context>, amount_msats: u64, payment_id: PaymentId
212	) -> Result<Self, Bolt12SemanticError> {
213		if amount_msats > MAX_VALUE_MSAT {
214			return Err(Bolt12SemanticError::InvalidAmount);
215		}
216
217		let payment_id = Some(payment_id);
218		let derivation_material = MetadataMaterial::new(nonce, expanded_key, payment_id);
219		let metadata = Metadata::DerivedSigningPubkey(derivation_material);
220		Ok(Self {
221			refund: RefundContents {
222				payer: PayerContents(metadata), description: String::new(), absolute_expiry: None,
223				issuer: None, chain: None, amount_msats, features: InvoiceRequestFeatures::empty(),
224				quantity: None, payer_signing_pubkey: node_id, payer_note: None, paths: None,
225				#[cfg(test)]
226				experimental_foo: None,
227				#[cfg(test)]
228				experimental_bar: None,
229			},
230			secp_ctx: Some(secp_ctx),
231		})
232	}
233
234	/// Sets the [`Refund::description`].
235	///
236	/// Successive calls to this method will override the previous setting.
237	pub fn description($($self_mut)* $self: $self_type, description: String) -> $return_type {
238		$self.refund.description = description;
239		$return_value
240	}
241
242	/// Sets the [`Refund::absolute_expiry`] as seconds since the Unix epoch.
243	#[cfg_attr(feature = "std", doc = "Any expiry that has already passed is valid and can be checked for using [`Refund::is_expired`].")]
244	///
245	/// Successive calls to this method will override the previous setting.
246	pub fn absolute_expiry($($self_mut)* $self: $self_type, absolute_expiry: Duration) -> $return_type {
247		$self.refund.absolute_expiry = Some(absolute_expiry);
248		$return_value
249	}
250
251	/// Sets the [`Refund::issuer`].
252	///
253	/// Successive calls to this method will override the previous setting.
254	pub fn issuer($($self_mut)* $self: $self_type, issuer: String) -> $return_type {
255		$self.refund.issuer = Some(issuer);
256		$return_value
257	}
258
259	/// Adds a blinded path to [`Refund::paths`]. Must include at least one path if only connected
260	/// by private channels or if [`Refund::payer_signing_pubkey`] is not a public node id.
261	///
262	/// Successive calls to this method will add another blinded path. Caller is responsible for not
263	/// adding duplicate paths.
264	pub fn path($($self_mut)* $self: $self_type, path: BlindedMessagePath) -> $return_type {
265		$self.refund.paths.get_or_insert_with(Vec::new).push(path);
266		$return_value
267	}
268
269	/// Sets the [`Refund::chain`] of the given [`Network`] for paying an invoice. If not
270	/// called, [`Network::Bitcoin`] is assumed.
271	///
272	/// Successive calls to this method will override the previous setting.
273	pub fn chain($self: $self_type, network: Network) -> $return_type {
274		$self.chain_hash(ChainHash::using_genesis_block(network))
275	}
276
277	/// Sets the [`Refund::chain`] of the given [`ChainHash`] for paying an invoice. If not called,
278	/// [`Network::Bitcoin`] is assumed.
279	///
280	/// Successive calls to this method will override the previous setting.
281	pub(crate) fn chain_hash($($self_mut)* $self: $self_type, chain: ChainHash) -> $return_type {
282		$self.refund.chain = Some(chain);
283		$return_value
284	}
285
286	/// Sets [`Refund::quantity`] of items. This is purely for informational purposes. It is useful
287	/// when the refund pertains to a [`Bolt12Invoice`] that paid for more than one item from an
288	/// [`Offer`] as specified by [`InvoiceRequest::quantity`].
289	///
290	/// Successive calls to this method will override the previous setting.
291	///
292	/// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
293	/// [`InvoiceRequest::quantity`]: crate::offers::invoice_request::InvoiceRequest::quantity
294	/// [`Offer`]: crate::offers::offer::Offer
295	pub fn quantity($($self_mut)* $self: $self_type, quantity: u64) -> $return_type {
296		$self.refund.quantity = Some(quantity);
297		$return_value
298	}
299
300	/// Sets the [`Refund::payer_note`].
301	///
302	/// Successive calls to this method will override the previous setting.
303	pub fn payer_note($($self_mut)* $self: $self_type, payer_note: String) -> $return_type {
304		$self.refund.payer_note = Some(payer_note);
305		$return_value
306	}
307
308	/// Builds a [`Refund`] after checking for valid semantics.
309	pub fn build($($self_mut)* $self: $self_type) -> Result<Refund, Bolt12SemanticError> {
310		if $self.refund.chain() == $self.refund.implied_chain() {
311			$self.refund.chain = None;
312		}
313
314		// Create the metadata for stateless verification of a Bolt12Invoice.
315		if $self.refund.payer.0.has_derivation_material() {
316			let mut metadata = core::mem::take(&mut $self.refund.payer.0);
317
318			let iv_bytes = if $self.refund.paths.is_none() {
319				metadata = metadata.without_keys();
320				IV_BYTES_WITH_METADATA
321			} else {
322				IV_BYTES_WITHOUT_METADATA
323			};
324
325			let mut tlv_stream = $self.refund.as_tlv_stream();
326			tlv_stream.0.metadata = None;
327			if metadata.derives_payer_keys() {
328				tlv_stream.2.payer_id = None;
329			}
330
331			let (derived_metadata, keys) =
332				metadata.derive_from(iv_bytes, tlv_stream, $self.secp_ctx);
333			metadata = derived_metadata;
334			if let Some(keys) = keys {
335				$self.refund.payer_signing_pubkey = keys.public_key();
336			}
337
338			$self.refund.payer.0 = metadata;
339		}
340
341		const REFUND_ALLOCATION_SIZE: usize = 512;
342		let mut bytes = Vec::with_capacity(REFUND_ALLOCATION_SIZE);
343		$self.refund.write(&mut bytes).unwrap();
344
345		Ok(Refund {
346			bytes,
347			#[cfg(not(c_bindings))]
348			contents: $self.refund,
349			#[cfg(c_bindings)]
350			contents: $self.refund.clone(),
351		})
352	}
353} }
354
355#[cfg(test)]
356macro_rules! refund_builder_test_methods { (
357	$self: ident, $self_type: ty, $return_type: ty, $return_value: expr $(, $self_mut: tt)?
358) => {
359	#[cfg_attr(c_bindings, allow(dead_code))]
360	pub(crate) fn clear_paths($($self_mut)* $self: $self_type) -> $return_type {
361		$self.refund.paths = None;
362		$return_value
363	}
364
365	#[cfg_attr(c_bindings, allow(dead_code))]
366	fn features_unchecked($($self_mut)* $self: $self_type, features: InvoiceRequestFeatures) -> $return_type {
367		$self.refund.features = features;
368		$return_value
369	}
370
371	#[cfg_attr(c_bindings, allow(dead_code))]
372	pub(super) fn experimental_foo($($self_mut)* $self: $self_type, experimental_foo: u64) -> $return_type {
373		$self.refund.experimental_foo = Some(experimental_foo);
374		$return_value
375	}
376
377	#[cfg_attr(c_bindings, allow(dead_code))]
378	pub(super) fn experimental_bar($($self_mut)* $self: $self_type, experimental_bar: u64) -> $return_type {
379		$self.refund.experimental_bar = Some(experimental_bar);
380		$return_value
381	}
382} }
383
384impl<'a> RefundBuilder<'a, secp256k1::SignOnly> {
385	refund_explicit_metadata_builder_methods!();
386}
387
388impl<'a, T: secp256k1::Signing> RefundBuilder<'a, T> {
389	refund_builder_methods!(self, Self, Self, self, T, mut);
390
391	#[cfg(test)]
392	refund_builder_test_methods!(self, Self, Self, self, mut);
393}
394
395#[cfg(all(c_bindings, not(test)))]
396impl<'a> RefundMaybeWithDerivedMetadataBuilder<'a> {
397	refund_explicit_metadata_builder_methods!();
398	refund_builder_methods!(self, &mut Self, (), (), secp256k1::All);
399}
400
401#[cfg(all(c_bindings, test))]
402impl<'a> RefundMaybeWithDerivedMetadataBuilder<'a> {
403	refund_explicit_metadata_builder_methods!();
404	refund_builder_methods!(self, &mut Self, &mut Self, self, secp256k1::All);
405	refund_builder_test_methods!(self, &mut Self, &mut Self, self);
406}
407
408#[cfg(c_bindings)]
409impl<'a> From<RefundBuilder<'a, secp256k1::All>>
410for RefundMaybeWithDerivedMetadataBuilder<'a> {
411	fn from(builder: RefundBuilder<'a, secp256k1::All>) -> Self {
412		let RefundBuilder { refund, secp_ctx } = builder;
413
414		Self { refund, secp_ctx }
415	}
416}
417
418#[cfg(c_bindings)]
419impl<'a> From<RefundMaybeWithDerivedMetadataBuilder<'a>>
420for RefundBuilder<'a, secp256k1::All> {
421	fn from(builder: RefundMaybeWithDerivedMetadataBuilder<'a>) -> Self {
422		let RefundMaybeWithDerivedMetadataBuilder { refund, secp_ctx } = builder;
423
424		Self { refund, secp_ctx }
425	}
426}
427
428/// A `Refund` is a request to send an [`Bolt12Invoice`] without a preceding [`Offer`].
429///
430/// Typically, after an invoice is paid, the recipient may publish a refund allowing the sender to
431/// recoup their funds. A refund may be used more generally as an "offer for money", such as with a
432/// bitcoin ATM.
433///
434/// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
435/// [`Offer`]: crate::offers::offer::Offer
436#[derive(Clone, Debug)]
437pub struct Refund {
438	pub(super) bytes: Vec<u8>,
439	pub(super) contents: RefundContents,
440}
441
442/// The contents of a [`Refund`], which may be shared with an [`Bolt12Invoice`].
443///
444/// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
445#[derive(Clone, Debug)]
446#[cfg_attr(test, derive(PartialEq))]
447pub(super) struct RefundContents {
448	pub(super) payer: PayerContents,
449	// offer fields
450	description: String,
451	absolute_expiry: Option<Duration>,
452	issuer: Option<String>,
453	// invoice_request fields
454	chain: Option<ChainHash>,
455	amount_msats: u64,
456	features: InvoiceRequestFeatures,
457	quantity: Option<u64>,
458	payer_signing_pubkey: PublicKey,
459	payer_note: Option<String>,
460	paths: Option<Vec<BlindedMessagePath>>,
461	#[cfg(test)]
462	experimental_foo: Option<u64>,
463	#[cfg(test)]
464	experimental_bar: Option<u64>,
465}
466
467impl Refund {
468	/// A complete description of the purpose of the refund. Intended to be displayed to the user
469	/// but with the caveat that it has not been verified in any way.
470	pub fn description(&self) -> PrintableString {
471		self.contents.description()
472	}
473
474	/// Duration since the Unix epoch when an invoice should no longer be sent.
475	///
476	/// If `None`, the refund does not expire.
477	pub fn absolute_expiry(&self) -> Option<Duration> {
478		self.contents.absolute_expiry()
479	}
480
481	/// Whether the refund has expired.
482	#[cfg(feature = "std")]
483	pub fn is_expired(&self) -> bool {
484		self.contents.is_expired()
485	}
486
487	/// Whether the refund has expired given the duration since the Unix epoch.
488	pub fn is_expired_no_std(&self, duration_since_epoch: Duration) -> bool {
489		self.contents.is_expired_no_std(duration_since_epoch)
490	}
491
492	/// The issuer of the refund, possibly beginning with `user@domain` or `domain`. Intended to be
493	/// displayed to the user but with the caveat that it has not been verified in any way.
494	pub fn issuer(&self) -> Option<PrintableString> {
495		self.contents.issuer()
496	}
497
498	/// Paths to the sender originating from publicly reachable nodes. Blinded paths provide sender
499	/// privacy by obfuscating its node id.
500	pub fn paths(&self) -> &[BlindedMessagePath] {
501		self.contents.paths()
502	}
503
504	/// An unpredictable series of bytes, typically containing information about the derivation of
505	/// [`payer_signing_pubkey`].
506	///
507	/// [`payer_signing_pubkey`]: Self::payer_signing_pubkey
508	pub fn payer_metadata(&self) -> &[u8] {
509		self.contents.metadata()
510	}
511
512	/// A chain that the refund is valid for.
513	pub fn chain(&self) -> ChainHash {
514		self.contents.chain()
515	}
516
517	/// The amount to refund in msats (i.e., the minimum lightning-payable unit for [`chain`]).
518	///
519	/// [`chain`]: Self::chain
520	pub fn amount_msats(&self) -> u64 {
521		self.contents.amount_msats()
522	}
523
524	/// Features pertaining to requesting an invoice.
525	pub fn features(&self) -> &InvoiceRequestFeatures {
526		&self.contents.features()
527	}
528
529	/// The quantity of an item that refund is for.
530	pub fn quantity(&self) -> Option<u64> {
531		self.contents.quantity()
532	}
533
534	/// A public node id to send to in the case where there are no [`paths`]. Otherwise, a possibly
535	/// transient pubkey.
536	///
537	/// [`paths`]: Self::paths
538	pub fn payer_signing_pubkey(&self) -> PublicKey {
539		self.contents.payer_signing_pubkey()
540	}
541
542	/// Payer provided note to include in the invoice.
543	pub fn payer_note(&self) -> Option<PrintableString> {
544		self.contents.payer_note()
545	}
546}
547
548macro_rules! respond_with_explicit_signing_pubkey_methods { ($self: ident, $builder: ty) => {
549	/// Creates an [`InvoiceBuilder`] for the refund with the given required fields and using the
550	/// [`Duration`] since [`std::time::SystemTime::UNIX_EPOCH`] as the creation time.
551	///
552	/// See [`Refund::respond_with_no_std`] for further details where the aforementioned creation
553	/// time is used for the `created_at` parameter.
554	///
555	/// This is not exported to bindings users as builder patterns don't map outside of move semantics.
556	///
557	/// [`Duration`]: core::time::Duration
558	#[cfg(feature = "std")]
559	pub fn respond_with(
560		&$self, payment_paths: Vec<BlindedPaymentPath>, payment_hash: PaymentHash,
561		signing_pubkey: PublicKey,
562	) -> Result<$builder, Bolt12SemanticError> {
563		let created_at = std::time::SystemTime::now()
564			.duration_since(std::time::SystemTime::UNIX_EPOCH)
565			.expect("SystemTime::now() should come after SystemTime::UNIX_EPOCH");
566
567		$self.respond_with_no_std(payment_paths, payment_hash, signing_pubkey, created_at)
568	}
569
570	/// Creates an [`InvoiceBuilder`] for the refund with the given required fields.
571	///
572	/// Unless [`InvoiceBuilder::relative_expiry`] is set, the invoice will expire two hours after
573	/// `created_at`, which is used to set [`Bolt12Invoice::created_at`].
574	#[cfg_attr(feature = "std", doc = "Useful for non-`std` builds where [`std::time::SystemTime`] is not available.")]
575	///
576	/// The caller is expected to remember the preimage of `payment_hash` in order to
577	/// claim a payment for the invoice.
578	///
579	/// The `signing_pubkey` is required to sign the invoice since refunds are not in response to an
580	/// offer, which does have a `signing_pubkey`.
581	///
582	/// The `payment_paths` parameter is useful for maintaining the payment recipient's privacy. It
583	/// must contain one or more elements ordered from most-preferred to least-preferred, if there's
584	/// a preference. Note, however, that any privacy is lost if a public node id is used for
585	/// `signing_pubkey`.
586	///
587	/// Errors if the request contains unknown required features.
588	///
589	/// This is not exported to bindings users as builder patterns don't map outside of move semantics.
590	///
591	/// [`Bolt12Invoice::created_at`]: crate::offers::invoice::Bolt12Invoice::created_at
592	pub fn respond_with_no_std(
593		&$self, payment_paths: Vec<BlindedPaymentPath>, payment_hash: PaymentHash,
594		signing_pubkey: PublicKey, created_at: Duration
595	) -> Result<$builder, Bolt12SemanticError> {
596		if $self.features().requires_unknown_bits() {
597			return Err(Bolt12SemanticError::UnknownRequiredFeatures);
598		}
599
600		<$builder>::for_refund($self, payment_paths, created_at, payment_hash, signing_pubkey)
601	}
602} }
603
604macro_rules! respond_with_derived_signing_pubkey_methods { ($self: ident, $builder: ty) => {
605	/// Creates an [`InvoiceBuilder`] for the refund using the given required fields and that uses
606	/// derived signing keys to sign the [`Bolt12Invoice`].
607	///
608	/// See [`Refund::respond_with`] for further details.
609	///
610	/// This is not exported to bindings users as builder patterns don't map outside of move semantics.
611	///
612	/// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
613	#[cfg(feature = "std")]
614	pub fn respond_using_derived_keys<ES: Deref>(
615		&$self, payment_paths: Vec<BlindedPaymentPath>, payment_hash: PaymentHash,
616		expanded_key: &ExpandedKey, entropy_source: ES
617	) -> Result<$builder, Bolt12SemanticError>
618	where
619		ES::Target: EntropySource,
620	{
621		let created_at = std::time::SystemTime::now()
622			.duration_since(std::time::SystemTime::UNIX_EPOCH)
623			.expect("SystemTime::now() should come after SystemTime::UNIX_EPOCH");
624
625		$self.respond_using_derived_keys_no_std(
626			payment_paths, payment_hash, created_at, expanded_key, entropy_source
627		)
628	}
629
630	/// Creates an [`InvoiceBuilder`] for the refund using the given required fields and that uses
631	/// derived signing keys to sign the [`Bolt12Invoice`].
632	///
633	/// See [`Refund::respond_with_no_std`] for further details.
634	///
635	/// This is not exported to bindings users as builder patterns don't map outside of move semantics.
636	///
637	/// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
638	pub fn respond_using_derived_keys_no_std<ES: Deref>(
639		&$self, payment_paths: Vec<BlindedPaymentPath>, payment_hash: PaymentHash,
640		created_at: core::time::Duration, expanded_key: &ExpandedKey, entropy_source: ES
641	) -> Result<$builder, Bolt12SemanticError>
642	where
643		ES::Target: EntropySource,
644	{
645		if $self.features().requires_unknown_bits() {
646			return Err(Bolt12SemanticError::UnknownRequiredFeatures);
647		}
648
649		let nonce = Nonce::from_entropy_source(entropy_source);
650		let keys = signer::derive_keys(nonce, expanded_key);
651		<$builder>::for_refund_using_keys($self, payment_paths, created_at, payment_hash, keys)
652	}
653} }
654
655#[cfg(not(c_bindings))]
656impl Refund {
657	respond_with_explicit_signing_pubkey_methods!(self, InvoiceBuilder<ExplicitSigningPubkey>);
658	respond_with_derived_signing_pubkey_methods!(self, InvoiceBuilder<DerivedSigningPubkey>);
659}
660
661#[cfg(c_bindings)]
662impl Refund {
663	respond_with_explicit_signing_pubkey_methods!(self, InvoiceWithExplicitSigningPubkeyBuilder);
664	respond_with_derived_signing_pubkey_methods!(self, InvoiceWithDerivedSigningPubkeyBuilder);
665}
666
667#[cfg(test)]
668impl Refund {
669	fn as_tlv_stream(&self) -> RefundTlvStreamRef {
670		self.contents.as_tlv_stream()
671	}
672}
673
674impl AsRef<[u8]> for Refund {
675	fn as_ref(&self) -> &[u8] {
676		&self.bytes
677	}
678}
679
680impl PartialEq for Refund {
681	fn eq(&self, other: &Self) -> bool {
682		self.bytes.eq(&other.bytes)
683	}
684}
685
686impl Eq for Refund {}
687
688impl Hash for Refund {
689	fn hash<H: Hasher>(&self, state: &mut H) {
690		self.bytes.hash(state);
691	}
692}
693
694impl RefundContents {
695	pub fn description(&self) -> PrintableString {
696		PrintableString(&self.description)
697	}
698
699	pub fn absolute_expiry(&self) -> Option<Duration> {
700		self.absolute_expiry
701	}
702
703	#[cfg(feature = "std")]
704	pub(super) fn is_expired(&self) -> bool {
705		SystemTime::UNIX_EPOCH
706			.elapsed()
707			.map(|duration_since_epoch| self.is_expired_no_std(duration_since_epoch))
708			.unwrap_or(false)
709	}
710
711	pub(super) fn is_expired_no_std(&self, duration_since_epoch: Duration) -> bool {
712		self.absolute_expiry
713			.map(|absolute_expiry| duration_since_epoch > absolute_expiry)
714			.unwrap_or(false)
715	}
716
717	pub fn issuer(&self) -> Option<PrintableString> {
718		self.issuer.as_ref().map(|issuer| PrintableString(issuer.as_str()))
719	}
720
721	pub fn paths(&self) -> &[BlindedMessagePath] {
722		self.paths.as_ref().map(|paths| paths.as_slice()).unwrap_or(&[])
723	}
724
725	pub(super) fn metadata(&self) -> &[u8] {
726		self.payer.0.as_bytes().map(|bytes| bytes.as_slice()).unwrap_or(&[])
727	}
728
729	pub(super) fn chain(&self) -> ChainHash {
730		self.chain.unwrap_or_else(|| self.implied_chain())
731	}
732
733	pub fn implied_chain(&self) -> ChainHash {
734		ChainHash::using_genesis_block(Network::Bitcoin)
735	}
736
737	pub fn amount_msats(&self) -> u64 {
738		self.amount_msats
739	}
740
741	/// Features pertaining to requesting an invoice.
742	pub fn features(&self) -> &InvoiceRequestFeatures {
743		&self.features
744	}
745
746	/// The quantity of an item that refund is for.
747	pub fn quantity(&self) -> Option<u64> {
748		self.quantity
749	}
750
751	/// A public node id to send to in the case where there are no [`paths`]. Otherwise, a possibly
752	/// transient pubkey.
753	///
754	/// [`paths`]: Self::paths
755	pub fn payer_signing_pubkey(&self) -> PublicKey {
756		self.payer_signing_pubkey
757	}
758
759	/// Payer provided note to include in the invoice.
760	pub fn payer_note(&self) -> Option<PrintableString> {
761		self.payer_note.as_ref().map(|payer_note| PrintableString(payer_note.as_str()))
762	}
763
764	pub(super) fn as_tlv_stream(&self) -> RefundTlvStreamRef {
765		let payer = PayerTlvStreamRef {
766			metadata: self.payer.0.as_bytes(),
767		};
768
769		let offer = OfferTlvStreamRef {
770			chains: None,
771			metadata: None,
772			currency: None,
773			amount: None,
774			description: Some(&self.description),
775			features: None,
776			absolute_expiry: self.absolute_expiry.map(|duration| duration.as_secs()),
777			paths: None,
778			issuer: self.issuer.as_ref(),
779			quantity_max: None,
780			issuer_id: None,
781		};
782
783		let features = {
784			if self.features == InvoiceRequestFeatures::empty() { None }
785			else { Some(&self.features) }
786		};
787
788		let invoice_request = InvoiceRequestTlvStreamRef {
789			chain: self.chain.as_ref(),
790			amount: Some(self.amount_msats),
791			features,
792			quantity: self.quantity,
793			payer_id: Some(&self.payer_signing_pubkey),
794			payer_note: self.payer_note.as_ref(),
795			paths: self.paths.as_ref(),
796			offer_from_hrn: None,
797		};
798
799		let experimental_offer = ExperimentalOfferTlvStreamRef {
800			#[cfg(test)]
801			experimental_foo: self.experimental_foo,
802		};
803
804		let experimental_invoice_request = ExperimentalInvoiceRequestTlvStreamRef {
805			#[cfg(test)]
806			experimental_bar: self.experimental_bar,
807		};
808
809		(payer, offer, invoice_request, experimental_offer, experimental_invoice_request)
810	}
811}
812
813impl Readable for Refund {
814	fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
815		let bytes: WithoutLength<Vec<u8>> = Readable::read(reader)?;
816		Self::try_from(bytes.0).map_err(|_| DecodeError::InvalidValue)
817	}
818}
819
820impl Writeable for Refund {
821	fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
822		WithoutLength(&self.bytes).write(writer)
823	}
824}
825
826impl Writeable for RefundContents {
827	fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
828		self.as_tlv_stream().write(writer)
829	}
830}
831
832type RefundTlvStream = (
833	PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream, ExperimentalOfferTlvStream,
834	ExperimentalInvoiceRequestTlvStream,
835);
836
837type RefundTlvStreamRef<'a> = (
838	PayerTlvStreamRef<'a>,
839	OfferTlvStreamRef<'a>,
840	InvoiceRequestTlvStreamRef<'a>,
841	ExperimentalOfferTlvStreamRef,
842	ExperimentalInvoiceRequestTlvStreamRef,
843);
844
845impl CursorReadable for RefundTlvStream {
846	fn read<R: AsRef<[u8]>>(r: &mut io::Cursor<R>) -> Result<Self, DecodeError> {
847		let payer = CursorReadable::read(r)?;
848		let offer = CursorReadable::read(r)?;
849		let invoice_request = CursorReadable::read(r)?;
850		let experimental_offer = CursorReadable::read(r)?;
851		let experimental_invoice_request = CursorReadable::read(r)?;
852
853		Ok((payer, offer, invoice_request, experimental_offer, experimental_invoice_request))
854	}
855}
856
857impl Bech32Encode for Refund {
858	const BECH32_HRP: &'static str = "lnr";
859}
860
861impl FromStr for Refund {
862	type Err = Bolt12ParseError;
863
864	fn from_str(s: &str) -> Result<Self, <Self as FromStr>::Err> {
865		Refund::from_bech32_str(s)
866	}
867}
868
869impl TryFrom<Vec<u8>> for Refund {
870	type Error = Bolt12ParseError;
871
872	fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
873		let refund = ParsedMessage::<RefundTlvStream>::try_from(bytes)?;
874		let ParsedMessage { bytes, tlv_stream } = refund;
875		let contents = RefundContents::try_from(tlv_stream)?;
876
877		Ok(Refund { bytes, contents })
878	}
879}
880
881impl TryFrom<RefundTlvStream> for RefundContents {
882	type Error = Bolt12SemanticError;
883
884	fn try_from(tlv_stream: RefundTlvStream) -> Result<Self, Self::Error> {
885		let (
886			PayerTlvStream { metadata: payer_metadata },
887			OfferTlvStream {
888				chains, metadata, currency, amount: offer_amount, description,
889				features: offer_features, absolute_expiry, paths: offer_paths, issuer, quantity_max,
890				issuer_id,
891			},
892			InvoiceRequestTlvStream {
893				chain, amount, features, quantity, payer_id, payer_note, paths,
894				offer_from_hrn,
895			},
896			ExperimentalOfferTlvStream {
897				#[cfg(test)]
898				experimental_foo,
899			},
900			ExperimentalInvoiceRequestTlvStream {
901				#[cfg(test)]
902				experimental_bar,
903			},
904		) = tlv_stream;
905
906		let payer = match payer_metadata {
907			None => return Err(Bolt12SemanticError::MissingPayerMetadata),
908			Some(metadata) => PayerContents(Metadata::Bytes(metadata)),
909		};
910
911		if metadata.is_some() {
912			return Err(Bolt12SemanticError::UnexpectedMetadata);
913		}
914
915		if chains.is_some() {
916			return Err(Bolt12SemanticError::UnexpectedChain);
917		}
918
919		if currency.is_some() || offer_amount.is_some() {
920			return Err(Bolt12SemanticError::UnexpectedAmount);
921		}
922
923		let description = match description {
924			None => return Err(Bolt12SemanticError::MissingDescription),
925			Some(description) => description,
926		};
927
928		if offer_features.is_some() {
929			return Err(Bolt12SemanticError::UnexpectedFeatures);
930		}
931
932		let absolute_expiry = absolute_expiry.map(Duration::from_secs);
933
934		if offer_paths.is_some() {
935			return Err(Bolt12SemanticError::UnexpectedPaths);
936		}
937
938		if quantity_max.is_some() {
939			return Err(Bolt12SemanticError::UnexpectedQuantity);
940		}
941
942		if issuer_id.is_some() {
943			return Err(Bolt12SemanticError::UnexpectedIssuerSigningPubkey);
944		}
945
946		if offer_from_hrn.is_some() {
947			// Only offers can be resolved using Human Readable Names
948			return Err(Bolt12SemanticError::UnexpectedHumanReadableName);
949		}
950
951		let amount_msats = match amount {
952			None => return Err(Bolt12SemanticError::MissingAmount),
953			Some(amount_msats) if amount_msats > MAX_VALUE_MSAT => {
954				return Err(Bolt12SemanticError::InvalidAmount);
955			},
956			Some(amount_msats) => amount_msats,
957		};
958
959		let features = features.unwrap_or_else(InvoiceRequestFeatures::empty);
960
961		let payer_signing_pubkey = match payer_id {
962			None => return Err(Bolt12SemanticError::MissingPayerSigningPubkey),
963			Some(payer_id) => payer_id,
964		};
965
966		Ok(RefundContents {
967			payer, description, absolute_expiry, issuer, chain, amount_msats, features, quantity,
968			payer_signing_pubkey, payer_note, paths,
969			#[cfg(test)]
970			experimental_foo,
971			#[cfg(test)]
972			experimental_bar,
973		})
974	}
975}
976
977impl core::fmt::Display for Refund {
978	fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
979		self.fmt_bech32_str(f)
980	}
981}
982
983#[cfg(test)]
984mod tests {
985	use super::{Refund, RefundTlvStreamRef};
986	#[cfg(not(c_bindings))]
987	use {
988		super::RefundBuilder,
989	};
990	#[cfg(c_bindings)]
991	use {
992		super::RefundMaybeWithDerivedMetadataBuilder as RefundBuilder,
993	};
994
995	use bitcoin::constants::ChainHash;
996	use bitcoin::network::Network;
997	use bitcoin::secp256k1::{Keypair, Secp256k1, SecretKey};
998
999	use core::time::Duration;
1000
1001	use crate::blinded_path::BlindedHop;
1002	use crate::blinded_path::message::BlindedMessagePath;
1003	use crate::ln::channelmanager::PaymentId;
1004	use crate::types::features::{InvoiceRequestFeatures, OfferFeatures};
1005	use crate::ln::inbound_payment::ExpandedKey;
1006	use crate::ln::msgs::{DecodeError, MAX_VALUE_MSAT};
1007	use crate::offers::invoice_request::{EXPERIMENTAL_INVOICE_REQUEST_TYPES, ExperimentalInvoiceRequestTlvStreamRef, INVOICE_REQUEST_TYPES, InvoiceRequestTlvStreamRef};
1008	use crate::offers::nonce::Nonce;
1009	use crate::offers::offer::{ExperimentalOfferTlvStreamRef, OfferTlvStreamRef};
1010	use crate::offers::parse::{Bolt12ParseError, Bolt12SemanticError};
1011	use crate::offers::payer::PayerTlvStreamRef;
1012	use crate::offers::test_utils::*;
1013	use crate::util::ser::{BigSize, Writeable};
1014	use crate::util::string::PrintableString;
1015	use crate::prelude::*;
1016
1017	trait ToBytes {
1018		fn to_bytes(&self) -> Vec<u8>;
1019	}
1020
1021	impl<'a> ToBytes for RefundTlvStreamRef<'a> {
1022		fn to_bytes(&self) -> Vec<u8> {
1023			let mut buffer = Vec::new();
1024			self.write(&mut buffer).unwrap();
1025			buffer
1026		}
1027	}
1028
1029	#[test]
1030	fn builds_refund_with_defaults() {
1031		let refund = RefundBuilder::new(vec![1; 32], payer_pubkey(), 1000).unwrap()
1032			.build().unwrap();
1033
1034		let mut buffer = Vec::new();
1035		refund.write(&mut buffer).unwrap();
1036
1037		assert_eq!(refund.bytes, buffer.as_slice());
1038		assert_eq!(refund.payer_metadata(), &[1; 32]);
1039		assert_eq!(refund.description(), PrintableString(""));
1040		assert_eq!(refund.absolute_expiry(), None);
1041		#[cfg(feature = "std")]
1042		assert!(!refund.is_expired());
1043		assert_eq!(refund.paths(), &[]);
1044		assert_eq!(refund.issuer(), None);
1045		assert_eq!(refund.chain(), ChainHash::using_genesis_block(Network::Bitcoin));
1046		assert_eq!(refund.amount_msats(), 1000);
1047		assert_eq!(refund.features(), &InvoiceRequestFeatures::empty());
1048		assert_eq!(refund.payer_signing_pubkey(), payer_pubkey());
1049		assert_eq!(refund.payer_note(), None);
1050
1051		assert_eq!(
1052			refund.as_tlv_stream(),
1053			(
1054				PayerTlvStreamRef { metadata: Some(&vec![1; 32]) },
1055				OfferTlvStreamRef {
1056					chains: None,
1057					metadata: None,
1058					currency: None,
1059					amount: None,
1060					description: Some(&String::from("")),
1061					features: None,
1062					absolute_expiry: None,
1063					paths: None,
1064					issuer: None,
1065					quantity_max: None,
1066					issuer_id: None,
1067				},
1068				InvoiceRequestTlvStreamRef {
1069					chain: None,
1070					amount: Some(1000),
1071					features: None,
1072					quantity: None,
1073					payer_id: Some(&payer_pubkey()),
1074					payer_note: None,
1075					paths: None,
1076					offer_from_hrn: None,
1077				},
1078				ExperimentalOfferTlvStreamRef {
1079					experimental_foo: None,
1080				},
1081				ExperimentalInvoiceRequestTlvStreamRef {
1082					experimental_bar: None,
1083				},
1084			),
1085		);
1086
1087		if let Err(e) = Refund::try_from(buffer) {
1088			panic!("error parsing refund: {:?}", e);
1089		}
1090	}
1091
1092	#[test]
1093	fn fails_building_refund_with_invalid_amount() {
1094		match RefundBuilder::new(vec![1; 32], payer_pubkey(), MAX_VALUE_MSAT + 1) {
1095			Ok(_) => panic!("expected error"),
1096			Err(e) => assert_eq!(e, Bolt12SemanticError::InvalidAmount),
1097		}
1098	}
1099
1100	#[test]
1101	fn builds_refund_with_metadata_derived() {
1102		let node_id = payer_pubkey();
1103		let expanded_key = ExpandedKey::new([42; 32]);
1104		let entropy = FixedEntropy {};
1105		let nonce = Nonce::from_entropy_source(&entropy);
1106		let secp_ctx = Secp256k1::new();
1107		let payment_id = PaymentId([1; 32]);
1108
1109		let refund = RefundBuilder
1110			::deriving_signing_pubkey(node_id, &expanded_key, nonce, &secp_ctx, 1000, payment_id)
1111			.unwrap()
1112			.experimental_foo(42)
1113			.experimental_bar(42)
1114			.build().unwrap();
1115		assert_eq!(refund.payer_signing_pubkey(), node_id);
1116
1117		// Fails verification with altered fields
1118		let invoice = refund
1119			.respond_with_no_std(payment_paths(), payment_hash(), recipient_pubkey(), now())
1120			.unwrap()
1121			.experimental_baz(42)
1122			.build().unwrap()
1123			.sign(recipient_sign).unwrap();
1124		match invoice.verify_using_metadata(&expanded_key, &secp_ctx) {
1125			Ok(payment_id) => assert_eq!(payment_id, PaymentId([1; 32])),
1126			Err(()) => panic!("verification failed"),
1127		}
1128		assert!(
1129			invoice.verify_using_payer_data(payment_id, nonce, &expanded_key, &secp_ctx).is_err()
1130		);
1131
1132		let mut tlv_stream = refund.as_tlv_stream();
1133		tlv_stream.2.amount = Some(2000);
1134
1135		let mut encoded_refund = Vec::new();
1136		tlv_stream.write(&mut encoded_refund).unwrap();
1137
1138		let invoice = Refund::try_from(encoded_refund).unwrap()
1139			.respond_with_no_std(payment_paths(), payment_hash(), recipient_pubkey(), now())
1140			.unwrap()
1141			.build().unwrap()
1142			.sign(recipient_sign).unwrap();
1143		assert!(invoice.verify_using_metadata(&expanded_key, &secp_ctx).is_err());
1144
1145		// Fails verification with altered metadata
1146		let mut tlv_stream = refund.as_tlv_stream();
1147		let metadata = tlv_stream.0.metadata.unwrap().iter().copied().rev().collect();
1148		tlv_stream.0.metadata = Some(&metadata);
1149
1150		let mut encoded_refund = Vec::new();
1151		tlv_stream.write(&mut encoded_refund).unwrap();
1152
1153		let invoice = Refund::try_from(encoded_refund).unwrap()
1154			.respond_with_no_std(payment_paths(), payment_hash(), recipient_pubkey(), now())
1155			.unwrap()
1156			.build().unwrap()
1157			.sign(recipient_sign).unwrap();
1158		assert!(invoice.verify_using_metadata(&expanded_key, &secp_ctx).is_err());
1159	}
1160
1161	#[test]
1162	fn builds_refund_with_derived_signing_pubkey() {
1163		let node_id = payer_pubkey();
1164		let expanded_key = ExpandedKey::new([42; 32]);
1165		let entropy = FixedEntropy {};
1166		let nonce = Nonce::from_entropy_source(&entropy);
1167		let secp_ctx = Secp256k1::new();
1168		let payment_id = PaymentId([1; 32]);
1169
1170		let blinded_path = BlindedMessagePath::from_raw(
1171			pubkey(40), pubkey(41),
1172			vec![
1173				BlindedHop { blinded_node_id: pubkey(43), encrypted_payload: vec![0; 43] },
1174				BlindedHop { blinded_node_id: node_id, encrypted_payload: vec![0; 44] },
1175			]
1176		);
1177
1178		let refund = RefundBuilder
1179			::deriving_signing_pubkey(node_id, &expanded_key, nonce, &secp_ctx, 1000, payment_id)
1180			.unwrap()
1181			.path(blinded_path)
1182			.experimental_foo(42)
1183			.experimental_bar(42)
1184			.build().unwrap();
1185		assert_ne!(refund.payer_signing_pubkey(), node_id);
1186
1187		let invoice = refund
1188			.respond_with_no_std(payment_paths(), payment_hash(), recipient_pubkey(), now())
1189			.unwrap()
1190			.experimental_baz(42)
1191			.build().unwrap()
1192			.sign(recipient_sign).unwrap();
1193		assert!(invoice.verify_using_metadata(&expanded_key, &secp_ctx).is_err());
1194		assert!(
1195			invoice.verify_using_payer_data(payment_id, nonce, &expanded_key, &secp_ctx).is_ok()
1196		);
1197
1198		// Fails verification with altered fields
1199		let mut tlv_stream = refund.as_tlv_stream();
1200		tlv_stream.2.amount = Some(2000);
1201
1202		let mut encoded_refund = Vec::new();
1203		tlv_stream.write(&mut encoded_refund).unwrap();
1204
1205		let invoice = Refund::try_from(encoded_refund).unwrap()
1206			.respond_with_no_std(payment_paths(), payment_hash(), recipient_pubkey(), now())
1207			.unwrap()
1208			.build().unwrap()
1209			.sign(recipient_sign).unwrap();
1210		assert!(
1211			invoice.verify_using_payer_data(payment_id, nonce, &expanded_key, &secp_ctx).is_err()
1212		);
1213
1214		// Fails verification with altered payer_id
1215		let mut tlv_stream = refund.as_tlv_stream();
1216		let payer_id = pubkey(1);
1217		tlv_stream.2.payer_id = Some(&payer_id);
1218
1219		let mut encoded_refund = Vec::new();
1220		tlv_stream.write(&mut encoded_refund).unwrap();
1221
1222		let invoice = Refund::try_from(encoded_refund).unwrap()
1223			.respond_with_no_std(payment_paths(), payment_hash(), recipient_pubkey(), now())
1224			.unwrap()
1225			.build().unwrap()
1226			.sign(recipient_sign).unwrap();
1227		assert!(
1228			invoice.verify_using_payer_data(payment_id, nonce, &expanded_key, &secp_ctx).is_err()
1229		);
1230	}
1231
1232	#[test]
1233	fn builds_refund_with_absolute_expiry() {
1234		let future_expiry = Duration::from_secs(u64::max_value());
1235		let past_expiry = Duration::from_secs(0);
1236		let now = future_expiry - Duration::from_secs(1_000);
1237
1238		let refund = RefundBuilder::new(vec![1; 32], payer_pubkey(), 1000).unwrap()
1239			.absolute_expiry(future_expiry)
1240			.build()
1241			.unwrap();
1242		let (_, tlv_stream, _, _, _) = refund.as_tlv_stream();
1243		#[cfg(feature = "std")]
1244		assert!(!refund.is_expired());
1245		assert!(!refund.is_expired_no_std(now));
1246		assert_eq!(refund.absolute_expiry(), Some(future_expiry));
1247		assert_eq!(tlv_stream.absolute_expiry, Some(future_expiry.as_secs()));
1248
1249		let refund = RefundBuilder::new(vec![1; 32], payer_pubkey(), 1000).unwrap()
1250			.absolute_expiry(future_expiry)
1251			.absolute_expiry(past_expiry)
1252			.build()
1253			.unwrap();
1254		let (_, tlv_stream, _, _, _) = refund.as_tlv_stream();
1255		#[cfg(feature = "std")]
1256		assert!(refund.is_expired());
1257		assert!(refund.is_expired_no_std(now));
1258		assert_eq!(refund.absolute_expiry(), Some(past_expiry));
1259		assert_eq!(tlv_stream.absolute_expiry, Some(past_expiry.as_secs()));
1260	}
1261
1262	#[test]
1263	fn builds_refund_with_paths() {
1264		let paths = vec![
1265			BlindedMessagePath::from_raw(
1266				pubkey(40), pubkey(41),
1267				vec![
1268					BlindedHop { blinded_node_id: pubkey(43), encrypted_payload: vec![0; 43] },
1269					BlindedHop { blinded_node_id: pubkey(44), encrypted_payload: vec![0; 44] },
1270				]
1271			),
1272			BlindedMessagePath::from_raw(
1273				pubkey(40), pubkey(41),
1274				vec![
1275					BlindedHop { blinded_node_id: pubkey(45), encrypted_payload: vec![0; 45] },
1276					BlindedHop { blinded_node_id: pubkey(46), encrypted_payload: vec![0; 46] },
1277				]
1278			),
1279		];
1280
1281		let refund = RefundBuilder::new(vec![1; 32], payer_pubkey(), 1000).unwrap()
1282			.path(paths[0].clone())
1283			.path(paths[1].clone())
1284			.build()
1285			.unwrap();
1286		let (_, _, invoice_request_tlv_stream, _, _) = refund.as_tlv_stream();
1287		assert_eq!(refund.payer_signing_pubkey(), pubkey(42));
1288		assert_eq!(refund.paths(), paths.as_slice());
1289		assert_ne!(pubkey(42), pubkey(44));
1290		assert_eq!(invoice_request_tlv_stream.payer_id, Some(&pubkey(42)));
1291		assert_eq!(invoice_request_tlv_stream.paths, Some(&paths));
1292	}
1293
1294	#[test]
1295	fn builds_refund_with_issuer() {
1296		let refund = RefundBuilder::new(vec![1; 32], payer_pubkey(), 1000).unwrap()
1297			.issuer("bar".into())
1298			.build()
1299			.unwrap();
1300		let (_, tlv_stream, _, _, _) = refund.as_tlv_stream();
1301		assert_eq!(refund.issuer(), Some(PrintableString("bar")));
1302		assert_eq!(tlv_stream.issuer, Some(&String::from("bar")));
1303
1304		let refund = RefundBuilder::new(vec![1; 32], payer_pubkey(), 1000).unwrap()
1305			.issuer("bar".into())
1306			.issuer("baz".into())
1307			.build()
1308			.unwrap();
1309		let (_, tlv_stream, _, _, _) = refund.as_tlv_stream();
1310		assert_eq!(refund.issuer(), Some(PrintableString("baz")));
1311		assert_eq!(tlv_stream.issuer, Some(&String::from("baz")));
1312	}
1313
1314	#[test]
1315	fn builds_refund_with_chain() {
1316		let mainnet = ChainHash::using_genesis_block(Network::Bitcoin);
1317		let testnet = ChainHash::using_genesis_block(Network::Testnet);
1318
1319		let refund = RefundBuilder::new(vec![1; 32], payer_pubkey(), 1000).unwrap()
1320			.chain(Network::Bitcoin)
1321			.build().unwrap();
1322		let (_, _, tlv_stream, _, _) = refund.as_tlv_stream();
1323		assert_eq!(refund.chain(), mainnet);
1324		assert_eq!(tlv_stream.chain, None);
1325
1326		let refund = RefundBuilder::new(vec![1; 32], payer_pubkey(), 1000).unwrap()
1327			.chain(Network::Testnet)
1328			.build().unwrap();
1329		let (_, _, tlv_stream, _, _) = refund.as_tlv_stream();
1330		assert_eq!(refund.chain(), testnet);
1331		assert_eq!(tlv_stream.chain, Some(&testnet));
1332
1333		let refund = RefundBuilder::new(vec![1; 32], payer_pubkey(), 1000).unwrap()
1334			.chain(Network::Regtest)
1335			.chain(Network::Testnet)
1336			.build().unwrap();
1337		let (_, _, tlv_stream, _, _) = refund.as_tlv_stream();
1338		assert_eq!(refund.chain(), testnet);
1339		assert_eq!(tlv_stream.chain, Some(&testnet));
1340	}
1341
1342	#[test]
1343	fn builds_refund_with_quantity() {
1344		let refund = RefundBuilder::new(vec![1; 32], payer_pubkey(), 1000).unwrap()
1345			.quantity(10)
1346			.build().unwrap();
1347		let (_, _, tlv_stream, _, _) = refund.as_tlv_stream();
1348		assert_eq!(refund.quantity(), Some(10));
1349		assert_eq!(tlv_stream.quantity, Some(10));
1350
1351		let refund = RefundBuilder::new(vec![1; 32], payer_pubkey(), 1000).unwrap()
1352			.quantity(10)
1353			.quantity(1)
1354			.build().unwrap();
1355		let (_, _, tlv_stream, _, _) = refund.as_tlv_stream();
1356		assert_eq!(refund.quantity(), Some(1));
1357		assert_eq!(tlv_stream.quantity, Some(1));
1358	}
1359
1360	#[test]
1361	fn builds_refund_with_payer_note() {
1362		let refund = RefundBuilder::new(vec![1; 32], payer_pubkey(), 1000).unwrap()
1363			.payer_note("bar".into())
1364			.build().unwrap();
1365		let (_, _, tlv_stream, _, _) = refund.as_tlv_stream();
1366		assert_eq!(refund.payer_note(), Some(PrintableString("bar")));
1367		assert_eq!(tlv_stream.payer_note, Some(&String::from("bar")));
1368
1369		let refund = RefundBuilder::new(vec![1; 32], payer_pubkey(), 1000).unwrap()
1370			.payer_note("bar".into())
1371			.payer_note("baz".into())
1372			.build().unwrap();
1373		let (_, _, tlv_stream, _, _) = refund.as_tlv_stream();
1374		assert_eq!(refund.payer_note(), Some(PrintableString("baz")));
1375		assert_eq!(tlv_stream.payer_note, Some(&String::from("baz")));
1376	}
1377
1378	#[test]
1379	fn fails_responding_with_unknown_required_features() {
1380		match RefundBuilder::new(vec![1; 32], payer_pubkey(), 1000).unwrap()
1381			.features_unchecked(InvoiceRequestFeatures::unknown())
1382			.build().unwrap()
1383			.respond_with_no_std(payment_paths(), payment_hash(), recipient_pubkey(), now())
1384		{
1385			Ok(_) => panic!("expected error"),
1386			Err(e) => assert_eq!(e, Bolt12SemanticError::UnknownRequiredFeatures),
1387		}
1388	}
1389
1390	#[test]
1391	fn parses_refund_with_metadata() {
1392		let refund = RefundBuilder::new(vec![1; 32], payer_pubkey(), 1000).unwrap()
1393			.build().unwrap();
1394		if let Err(e) = refund.to_string().parse::<Refund>() {
1395			panic!("error parsing refund: {:?}", e);
1396		}
1397
1398		let mut tlv_stream = refund.as_tlv_stream();
1399		tlv_stream.0.metadata = None;
1400
1401		match Refund::try_from(tlv_stream.to_bytes()) {
1402			Ok(_) => panic!("expected error"),
1403			Err(e) => {
1404				assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingPayerMetadata));
1405			},
1406		}
1407	}
1408
1409	#[test]
1410	fn parses_refund_with_description() {
1411		let refund = RefundBuilder::new(vec![1; 32], payer_pubkey(), 1000).unwrap()
1412			.build().unwrap();
1413		if let Err(e) = refund.to_string().parse::<Refund>() {
1414			panic!("error parsing refund: {:?}", e);
1415		}
1416
1417		let mut tlv_stream = refund.as_tlv_stream();
1418		tlv_stream.1.description = None;
1419
1420		match Refund::try_from(tlv_stream.to_bytes()) {
1421			Ok(_) => panic!("expected error"),
1422			Err(e) => {
1423				assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingDescription));
1424			},
1425		}
1426	}
1427
1428	#[test]
1429	fn parses_refund_with_amount() {
1430		let refund = RefundBuilder::new(vec![1; 32], payer_pubkey(), 1000).unwrap()
1431			.build().unwrap();
1432		if let Err(e) = refund.to_string().parse::<Refund>() {
1433			panic!("error parsing refund: {:?}", e);
1434		}
1435
1436		let mut tlv_stream = refund.as_tlv_stream();
1437		tlv_stream.2.amount = None;
1438
1439		match Refund::try_from(tlv_stream.to_bytes()) {
1440			Ok(_) => panic!("expected error"),
1441			Err(e) => {
1442				assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingAmount));
1443			},
1444		}
1445
1446		let mut tlv_stream = refund.as_tlv_stream();
1447		tlv_stream.2.amount = Some(MAX_VALUE_MSAT + 1);
1448
1449		match Refund::try_from(tlv_stream.to_bytes()) {
1450			Ok(_) => panic!("expected error"),
1451			Err(e) => {
1452				assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::InvalidAmount));
1453			},
1454		}
1455	}
1456
1457	#[test]
1458	fn parses_refund_with_payer_id() {
1459		let refund = RefundBuilder::new(vec![1; 32], payer_pubkey(), 1000).unwrap()
1460			.build().unwrap();
1461		if let Err(e) = refund.to_string().parse::<Refund>() {
1462			panic!("error parsing refund: {:?}", e);
1463		}
1464
1465		let mut tlv_stream = refund.as_tlv_stream();
1466		tlv_stream.2.payer_id = None;
1467
1468		match Refund::try_from(tlv_stream.to_bytes()) {
1469			Ok(_) => panic!("expected error"),
1470			Err(e) => {
1471				assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingPayerSigningPubkey));
1472			},
1473		}
1474	}
1475
1476	#[test]
1477	fn parses_refund_with_optional_fields() {
1478		let past_expiry = Duration::from_secs(0);
1479		let paths = vec![
1480			BlindedMessagePath::from_raw(
1481				pubkey(40), pubkey(41),
1482				vec![
1483					BlindedHop { blinded_node_id: pubkey(43), encrypted_payload: vec![0; 43] },
1484					BlindedHop { blinded_node_id: pubkey(44), encrypted_payload: vec![0; 44] },
1485				]
1486			),
1487			BlindedMessagePath::from_raw(
1488				pubkey(40), pubkey(41),
1489				vec![
1490					BlindedHop { blinded_node_id: pubkey(45), encrypted_payload: vec![0; 45] },
1491					BlindedHop { blinded_node_id: pubkey(46), encrypted_payload: vec![0; 46] },
1492				]
1493			),
1494		];
1495
1496		let refund = RefundBuilder::new(vec![1; 32], payer_pubkey(), 1000).unwrap()
1497			.absolute_expiry(past_expiry)
1498			.issuer("bar".into())
1499			.path(paths[0].clone())
1500			.path(paths[1].clone())
1501			.chain(Network::Testnet)
1502			.features_unchecked(InvoiceRequestFeatures::unknown())
1503			.quantity(10)
1504			.payer_note("baz".into())
1505			.build()
1506			.unwrap();
1507		match refund.to_string().parse::<Refund>() {
1508			Ok(refund) => {
1509				assert_eq!(refund.absolute_expiry(), Some(past_expiry));
1510				#[cfg(feature = "std")]
1511				assert!(refund.is_expired());
1512				assert_eq!(refund.paths(), &paths[..]);
1513				assert_eq!(refund.issuer(), Some(PrintableString("bar")));
1514				assert_eq!(refund.chain(), ChainHash::using_genesis_block(Network::Testnet));
1515				assert_eq!(refund.features(), &InvoiceRequestFeatures::unknown());
1516				assert_eq!(refund.quantity(), Some(10));
1517				assert_eq!(refund.payer_note(), Some(PrintableString("baz")));
1518			},
1519			Err(e) => panic!("error parsing refund: {:?}", e),
1520		}
1521	}
1522
1523	#[test]
1524	fn fails_parsing_refund_with_unexpected_fields() {
1525		let refund = RefundBuilder::new(vec![1; 32], payer_pubkey(), 1000).unwrap()
1526			.build().unwrap();
1527		if let Err(e) = refund.to_string().parse::<Refund>() {
1528			panic!("error parsing refund: {:?}", e);
1529		}
1530
1531		let metadata = vec![42; 32];
1532		let mut tlv_stream = refund.as_tlv_stream();
1533		tlv_stream.1.metadata = Some(&metadata);
1534
1535		match Refund::try_from(tlv_stream.to_bytes()) {
1536			Ok(_) => panic!("expected error"),
1537			Err(e) => {
1538				assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::UnexpectedMetadata));
1539			},
1540		}
1541
1542		let chains = vec![ChainHash::using_genesis_block(Network::Testnet)];
1543		let mut tlv_stream = refund.as_tlv_stream();
1544		tlv_stream.1.chains = Some(&chains);
1545
1546		match Refund::try_from(tlv_stream.to_bytes()) {
1547			Ok(_) => panic!("expected error"),
1548			Err(e) => {
1549				assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::UnexpectedChain));
1550			},
1551		}
1552
1553		let mut tlv_stream = refund.as_tlv_stream();
1554		tlv_stream.1.currency = Some(&b"USD");
1555		tlv_stream.1.amount = Some(1000);
1556
1557		match Refund::try_from(tlv_stream.to_bytes()) {
1558			Ok(_) => panic!("expected error"),
1559			Err(e) => {
1560				assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::UnexpectedAmount));
1561			},
1562		}
1563
1564		let features = OfferFeatures::unknown();
1565		let mut tlv_stream = refund.as_tlv_stream();
1566		tlv_stream.1.features = Some(&features);
1567
1568		match Refund::try_from(tlv_stream.to_bytes()) {
1569			Ok(_) => panic!("expected error"),
1570			Err(e) => {
1571				assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::UnexpectedFeatures));
1572			},
1573		}
1574
1575		let mut tlv_stream = refund.as_tlv_stream();
1576		tlv_stream.1.quantity_max = Some(10);
1577
1578		match Refund::try_from(tlv_stream.to_bytes()) {
1579			Ok(_) => panic!("expected error"),
1580			Err(e) => {
1581				assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::UnexpectedQuantity));
1582			},
1583		}
1584
1585		let issuer_id = payer_pubkey();
1586		let mut tlv_stream = refund.as_tlv_stream();
1587		tlv_stream.1.issuer_id = Some(&issuer_id);
1588
1589		match Refund::try_from(tlv_stream.to_bytes()) {
1590			Ok(_) => panic!("expected error"),
1591			Err(e) => {
1592				assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::UnexpectedIssuerSigningPubkey));
1593			},
1594		}
1595	}
1596
1597	#[test]
1598	fn parses_refund_with_unknown_tlv_records() {
1599		const UNKNOWN_ODD_TYPE: u64 = INVOICE_REQUEST_TYPES.end - 1;
1600		assert!(UNKNOWN_ODD_TYPE % 2 == 1);
1601
1602		let refund = RefundBuilder::new(vec![1; 32], payer_pubkey(), 1000).unwrap()
1603			.build().unwrap();
1604
1605		let mut encoded_refund = Vec::new();
1606		refund.write(&mut encoded_refund).unwrap();
1607		BigSize(UNKNOWN_ODD_TYPE).write(&mut encoded_refund).unwrap();
1608		BigSize(32).write(&mut encoded_refund).unwrap();
1609		[42u8; 32].write(&mut encoded_refund).unwrap();
1610
1611		match Refund::try_from(encoded_refund.clone()) {
1612			Ok(refund) => assert_eq!(refund.bytes, encoded_refund),
1613			Err(e) => panic!("error parsing refund: {:?}", e),
1614		}
1615
1616		const UNKNOWN_EVEN_TYPE: u64 = INVOICE_REQUEST_TYPES.end - 2;
1617		assert!(UNKNOWN_EVEN_TYPE % 2 == 0);
1618
1619		let refund = RefundBuilder::new(vec![1; 32], payer_pubkey(), 1000).unwrap()
1620			.build().unwrap();
1621
1622		let mut encoded_refund = Vec::new();
1623		refund.write(&mut encoded_refund).unwrap();
1624		BigSize(UNKNOWN_EVEN_TYPE).write(&mut encoded_refund).unwrap();
1625		BigSize(32).write(&mut encoded_refund).unwrap();
1626		[42u8; 32].write(&mut encoded_refund).unwrap();
1627
1628		match Refund::try_from(encoded_refund) {
1629			Ok(_) => panic!("expected error"),
1630			Err(e) => assert_eq!(e, Bolt12ParseError::Decode(DecodeError::UnknownRequiredFeature)),
1631		}
1632	}
1633
1634	#[test]
1635	fn parses_refund_with_experimental_tlv_records() {
1636		const UNKNOWN_ODD_TYPE: u64 = EXPERIMENTAL_INVOICE_REQUEST_TYPES.start + 1;
1637		assert!(UNKNOWN_ODD_TYPE % 2 == 1);
1638
1639		let refund = RefundBuilder::new(vec![1; 32], payer_pubkey(), 1000).unwrap()
1640			.build().unwrap();
1641
1642		let mut encoded_refund = Vec::new();
1643		refund.write(&mut encoded_refund).unwrap();
1644		BigSize(UNKNOWN_ODD_TYPE).write(&mut encoded_refund).unwrap();
1645		BigSize(32).write(&mut encoded_refund).unwrap();
1646		[42u8; 32].write(&mut encoded_refund).unwrap();
1647
1648		match Refund::try_from(encoded_refund.clone()) {
1649			Ok(refund) => assert_eq!(refund.bytes, encoded_refund),
1650			Err(e) => panic!("error parsing refund: {:?}", e),
1651		}
1652
1653		const UNKNOWN_EVEN_TYPE: u64 = EXPERIMENTAL_INVOICE_REQUEST_TYPES.start;
1654		assert!(UNKNOWN_EVEN_TYPE % 2 == 0);
1655
1656		let refund = RefundBuilder::new(vec![1; 32], payer_pubkey(), 1000).unwrap()
1657			.build().unwrap();
1658
1659		let mut encoded_refund = Vec::new();
1660		refund.write(&mut encoded_refund).unwrap();
1661		BigSize(UNKNOWN_EVEN_TYPE).write(&mut encoded_refund).unwrap();
1662		BigSize(32).write(&mut encoded_refund).unwrap();
1663		[42u8; 32].write(&mut encoded_refund).unwrap();
1664
1665		match Refund::try_from(encoded_refund) {
1666			Ok(_) => panic!("expected error"),
1667			Err(e) => assert_eq!(e, Bolt12ParseError::Decode(DecodeError::UnknownRequiredFeature)),
1668		}
1669	}
1670
1671	#[test]
1672	fn fails_parsing_refund_with_out_of_range_tlv_records() {
1673		let secp_ctx = Secp256k1::new();
1674		let keys = Keypair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
1675		let refund = RefundBuilder::new(vec![1; 32], keys.public_key(), 1000).unwrap()
1676			.build().unwrap();
1677
1678		let mut encoded_refund = Vec::new();
1679		refund.write(&mut encoded_refund).unwrap();
1680		BigSize(1002).write(&mut encoded_refund).unwrap();
1681		BigSize(32).write(&mut encoded_refund).unwrap();
1682		[42u8; 32].write(&mut encoded_refund).unwrap();
1683
1684		match Refund::try_from(encoded_refund) {
1685			Ok(_) => panic!("expected error"),
1686			Err(e) => assert_eq!(e, Bolt12ParseError::Decode(DecodeError::InvalidValue)),
1687		}
1688
1689		let mut encoded_refund = Vec::new();
1690		refund.write(&mut encoded_refund).unwrap();
1691		BigSize(EXPERIMENTAL_INVOICE_REQUEST_TYPES.end).write(&mut encoded_refund).unwrap();
1692		BigSize(32).write(&mut encoded_refund).unwrap();
1693		[42u8; 32].write(&mut encoded_refund).unwrap();
1694
1695		match Refund::try_from(encoded_refund) {
1696			Ok(_) => panic!("expected error"),
1697			Err(e) => assert_eq!(e, Bolt12ParseError::Decode(DecodeError::InvalidValue)),
1698		}
1699	}
1700}