|
| 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 static BOLT 12 invoices. |
| 11 | +
|
| 12 | +use crate::blinded_path::BlindedPath; |
| 13 | +use crate::io; |
| 14 | +use crate::ln::features::{Bolt12InvoiceFeatures, OfferFeatures}; |
| 15 | +use crate::ln::msgs::DecodeError; |
| 16 | +use crate::offers::invoice::{ |
| 17 | + construct_payment_paths, filter_fallbacks, is_expired, BlindedPathIter, BlindedPayInfo, |
| 18 | + BlindedPayInfoIter, FallbackAddress, SIGNATURE_TAG, |
| 19 | +}; |
| 20 | +use crate::offers::invoice_macros::invoice_accessors_common; |
| 21 | +use crate::offers::merkle::{self, SignatureTlvStream, TaggedHash}; |
| 22 | +use crate::offers::offer::{Amount, OfferContents, OfferTlvStream, Quantity}; |
| 23 | +use crate::offers::parse::{Bolt12ParseError, Bolt12SemanticError, ParsedMessage}; |
| 24 | +use crate::util::ser::{ |
| 25 | + HighZeroBytesDroppedBigSize, Iterable, SeekReadable, WithoutLength, Writeable, Writer, |
| 26 | +}; |
| 27 | +use crate::util::string::PrintableString; |
| 28 | +use bitcoin::address::Address; |
| 29 | +use bitcoin::blockdata::constants::ChainHash; |
| 30 | +use bitcoin::secp256k1::schnorr::Signature; |
| 31 | +use bitcoin::secp256k1::PublicKey; |
| 32 | +use core::time::Duration; |
| 33 | + |
| 34 | +/// Static invoices default to expiring after 24 hours. |
| 35 | +const DEFAULT_RELATIVE_EXPIRY: Duration = Duration::from_secs(3600 * 24); |
| 36 | + |
| 37 | +/// A `StaticInvoice` is a reusable payment request corresponding to an [`Offer`]. |
| 38 | +/// |
| 39 | +/// A static invoice may be sent in response to an [`InvoiceRequest`] and includes all the |
| 40 | +/// information needed to pay the recipient. However, unlike [`Bolt12Invoice`]s, static invoices do |
| 41 | +/// not provide proof-of-payment. Therefore, [`Bolt12Invoice`]s should be preferred when the |
| 42 | +/// recipient is online to provide one. |
| 43 | +/// |
| 44 | +/// [`Offer`]: crate::offers::offer::Offer |
| 45 | +/// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest |
| 46 | +/// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice |
| 47 | +pub struct StaticInvoice { |
| 48 | + bytes: Vec<u8>, |
| 49 | + contents: InvoiceContents, |
| 50 | + signature: Signature, |
| 51 | + tagged_hash: TaggedHash, |
| 52 | +} |
| 53 | + |
| 54 | +/// The contents of a [`StaticInvoice`] for responding to an [`Offer`]. |
| 55 | +/// |
| 56 | +/// [`Offer`]: crate::offers::offer::Offer |
| 57 | +struct InvoiceContents { |
| 58 | + offer: OfferContents, |
| 59 | + payment_paths: Vec<(BlindedPayInfo, BlindedPath)>, |
| 60 | + created_at: Duration, |
| 61 | + relative_expiry: Option<Duration>, |
| 62 | + fallbacks: Option<Vec<FallbackAddress>>, |
| 63 | + features: Bolt12InvoiceFeatures, |
| 64 | + signing_pubkey: PublicKey, |
| 65 | +} |
| 66 | + |
| 67 | +macro_rules! invoice_accessors { ($self: ident, $contents: expr) => { |
| 68 | + /// The chain that must be used when paying the invoice. [`StaticInvoice`]s currently can only be |
| 69 | + /// created from offers that support a single chain. |
| 70 | + pub fn chain(&$self) -> ChainHash { |
| 71 | + $contents.chain() |
| 72 | + } |
| 73 | + |
| 74 | + /// Opaque bytes set by the originating [`Offer::metadata`]. |
| 75 | + /// |
| 76 | + /// [`Offer::metadata`]: crate::offers::offer::Offer::metadata |
| 77 | + pub fn metadata(&$self) -> Option<&Vec<u8>> { |
| 78 | + $contents.metadata() |
| 79 | + } |
| 80 | + |
| 81 | + /// The minimum amount required for a successful payment of a single item. |
| 82 | + /// |
| 83 | + /// From [`Offer::amount`]. |
| 84 | + /// |
| 85 | + /// [`Offer::amount`]: crate::offers::offer::Offer::amount |
| 86 | + pub fn amount(&$self) -> Option<Amount> { |
| 87 | + $contents.amount() |
| 88 | + } |
| 89 | + |
| 90 | + /// Features pertaining to the originating [`Offer`], from [`Offer::offer_features`]. |
| 91 | + /// |
| 92 | + /// [`Offer`]: crate::offers::offer::Offer |
| 93 | + /// [`Offer::offer_features`]: crate::offers::offer::Offer::offer_features |
| 94 | + pub fn offer_features(&$self) -> &OfferFeatures { |
| 95 | + $contents.offer_features() |
| 96 | + } |
| 97 | + |
| 98 | + /// A complete description of the purpose of the originating offer, from [`Offer::description`]. |
| 99 | + /// |
| 100 | + /// [`Offer::description`]: crate::offers::offer::Offer::description |
| 101 | + pub fn description(&$self) -> Option<PrintableString> { |
| 102 | + $contents.description() |
| 103 | + } |
| 104 | + |
| 105 | + /// Duration since the Unix epoch when an invoice should no longer be requested, from |
| 106 | + /// [`Offer::absolute_expiry`]. |
| 107 | + /// |
| 108 | + /// [`Offer::absolute_expiry`]: crate::offers::offer::Offer::absolute_expiry |
| 109 | + pub fn absolute_expiry(&$self) -> Option<Duration> { |
| 110 | + $contents.absolute_expiry() |
| 111 | + } |
| 112 | + |
| 113 | + /// The issuer of the offer, from [`Offer::issuer`]. |
| 114 | + /// |
| 115 | + /// [`Offer::issuer`]: crate::offers::offer::Offer::issuer |
| 116 | + pub fn issuer(&$self) -> Option<PrintableString> { |
| 117 | + $contents.issuer() |
| 118 | + } |
| 119 | + |
| 120 | + /// Paths to the recipient originating from publicly reachable nodes, from [`Offer::paths`]. |
| 121 | + /// |
| 122 | + /// [`Offer::paths`]: crate::offers::offer::Offer::paths |
| 123 | + pub fn message_paths(&$self) -> &[BlindedPath] { |
| 124 | + $contents.message_paths() |
| 125 | + } |
| 126 | + |
| 127 | + /// The quantity of items supported, from [`Offer::supported_quantity`]. |
| 128 | + /// |
| 129 | + /// [`Offer::supported_quantity`]: crate::offers::offer::Offer::supported_quantity |
| 130 | + pub fn supported_quantity(&$self) -> Quantity { |
| 131 | + $contents.supported_quantity() |
| 132 | + } |
| 133 | +} } |
| 134 | + |
| 135 | +impl StaticInvoice { |
| 136 | + invoice_accessors_common!(self, self.contents, StaticInvoice); |
| 137 | + invoice_accessors!(self, self.contents); |
| 138 | + |
| 139 | + /// Signature of the invoice verified using [`StaticInvoice::signing_pubkey`]. |
| 140 | + pub fn signature(&self) -> Signature { |
| 141 | + self.signature |
| 142 | + } |
| 143 | + |
| 144 | + /// Hash that was used for signing the invoice. |
| 145 | + pub fn signable_hash(&self) -> [u8; 32] { |
| 146 | + self.tagged_hash.as_digest().as_ref().clone() |
| 147 | + } |
| 148 | +} |
| 149 | + |
| 150 | +impl InvoiceContents { |
| 151 | + fn chain(&self) -> ChainHash { |
| 152 | + debug_assert_eq!(self.offer.chains().len(), 1); |
| 153 | + self.offer.chains().first().cloned().unwrap_or_else(|| self.offer.implied_chain()) |
| 154 | + } |
| 155 | + |
| 156 | + fn metadata(&self) -> Option<&Vec<u8>> { |
| 157 | + self.offer.metadata() |
| 158 | + } |
| 159 | + |
| 160 | + fn amount(&self) -> Option<Amount> { |
| 161 | + self.offer.amount() |
| 162 | + } |
| 163 | + |
| 164 | + fn offer_features(&self) -> &OfferFeatures { |
| 165 | + self.offer.features() |
| 166 | + } |
| 167 | + |
| 168 | + fn description(&self) -> Option<PrintableString> { |
| 169 | + self.offer.description() |
| 170 | + } |
| 171 | + |
| 172 | + fn absolute_expiry(&self) -> Option<Duration> { |
| 173 | + self.offer.absolute_expiry() |
| 174 | + } |
| 175 | + |
| 176 | + fn issuer(&self) -> Option<PrintableString> { |
| 177 | + self.offer.issuer() |
| 178 | + } |
| 179 | + |
| 180 | + fn message_paths(&self) -> &[BlindedPath] { |
| 181 | + self.offer.paths() |
| 182 | + } |
| 183 | + |
| 184 | + fn supported_quantity(&self) -> Quantity { |
| 185 | + self.offer.supported_quantity() |
| 186 | + } |
| 187 | + |
| 188 | + fn payment_paths(&self) -> &[(BlindedPayInfo, BlindedPath)] { |
| 189 | + &self.payment_paths[..] |
| 190 | + } |
| 191 | + |
| 192 | + fn created_at(&self) -> Duration { |
| 193 | + self.created_at |
| 194 | + } |
| 195 | + |
| 196 | + fn relative_expiry(&self) -> Duration { |
| 197 | + self.relative_expiry.unwrap_or(DEFAULT_RELATIVE_EXPIRY) |
| 198 | + } |
| 199 | + |
| 200 | + #[cfg(feature = "std")] |
| 201 | + fn is_expired(&self) -> bool { |
| 202 | + is_expired(self.created_at(), self.relative_expiry()) |
| 203 | + } |
| 204 | + |
| 205 | + fn fallbacks(&self) -> Vec<Address> { |
| 206 | + let chain = |
| 207 | + self.offer.chains().first().cloned().unwrap_or_else(|| self.offer.implied_chain()); |
| 208 | + self.fallbacks |
| 209 | + .as_ref() |
| 210 | + .map(|fallbacks| filter_fallbacks(chain, fallbacks)) |
| 211 | + .unwrap_or_else(Vec::new) |
| 212 | + } |
| 213 | + |
| 214 | + fn features(&self) -> &Bolt12InvoiceFeatures { |
| 215 | + &self.features |
| 216 | + } |
| 217 | + |
| 218 | + fn signing_pubkey(&self) -> PublicKey { |
| 219 | + self.signing_pubkey |
| 220 | + } |
| 221 | +} |
| 222 | + |
| 223 | +impl Writeable for StaticInvoice { |
| 224 | + fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> { |
| 225 | + WithoutLength(&self.bytes).write(writer) |
| 226 | + } |
| 227 | +} |
| 228 | + |
| 229 | +impl TryFrom<Vec<u8>> for StaticInvoice { |
| 230 | + type Error = Bolt12ParseError; |
| 231 | + |
| 232 | + fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> { |
| 233 | + let parsed_invoice = ParsedMessage::<FullInvoiceTlvStream>::try_from(bytes)?; |
| 234 | + StaticInvoice::try_from(parsed_invoice) |
| 235 | + } |
| 236 | +} |
| 237 | + |
| 238 | +tlv_stream!(InvoiceTlvStream, InvoiceTlvStreamRef, 160..240, { |
| 239 | + (160, paths: (Vec<BlindedPath>, WithoutLength, Iterable<'a, BlindedPathIter<'a>, BlindedPath>)), |
| 240 | + (162, blindedpay: (Vec<BlindedPayInfo>, WithoutLength, Iterable<'a, BlindedPayInfoIter<'a>, BlindedPayInfo>)), |
| 241 | + (164, created_at: (u64, HighZeroBytesDroppedBigSize)), |
| 242 | + (166, relative_expiry: (u32, HighZeroBytesDroppedBigSize)), |
| 243 | + (172, fallbacks: (Vec<FallbackAddress>, WithoutLength)), |
| 244 | + (174, features: (Bolt12InvoiceFeatures, WithoutLength)), |
| 245 | + (176, node_id: PublicKey), |
| 246 | +}); |
| 247 | + |
| 248 | +type FullInvoiceTlvStream = (OfferTlvStream, InvoiceTlvStream, SignatureTlvStream); |
| 249 | + |
| 250 | +impl SeekReadable for FullInvoiceTlvStream { |
| 251 | + fn read<R: io::Read + io::Seek>(r: &mut R) -> Result<Self, DecodeError> { |
| 252 | + let offer = SeekReadable::read(r)?; |
| 253 | + let invoice = SeekReadable::read(r)?; |
| 254 | + let signature = SeekReadable::read(r)?; |
| 255 | + |
| 256 | + Ok((offer, invoice, signature)) |
| 257 | + } |
| 258 | +} |
| 259 | + |
| 260 | +impl TryFrom<ParsedMessage<FullInvoiceTlvStream>> for StaticInvoice { |
| 261 | + type Error = Bolt12ParseError; |
| 262 | + |
| 263 | + fn try_from(invoice: ParsedMessage<FullInvoiceTlvStream>) -> Result<Self, Self::Error> { |
| 264 | + let ParsedMessage { bytes, tlv_stream } = invoice; |
| 265 | + let (offer_tlv_stream, invoice_tlv_stream, SignatureTlvStream { signature }) = tlv_stream; |
| 266 | + let contents = InvoiceContents::try_from((offer_tlv_stream, invoice_tlv_stream))?; |
| 267 | + |
| 268 | + let signature = match signature { |
| 269 | + None => { |
| 270 | + return Err(Bolt12ParseError::InvalidSemantics( |
| 271 | + Bolt12SemanticError::MissingSignature, |
| 272 | + )) |
| 273 | + }, |
| 274 | + Some(signature) => signature, |
| 275 | + }; |
| 276 | + let tagged_hash = TaggedHash::from_valid_tlv_stream_bytes(SIGNATURE_TAG, &bytes); |
| 277 | + let pubkey = contents.signing_pubkey; |
| 278 | + merkle::verify_signature(&signature, &tagged_hash, pubkey)?; |
| 279 | + |
| 280 | + Ok(StaticInvoice { bytes, contents, signature, tagged_hash }) |
| 281 | + } |
| 282 | +} |
| 283 | + |
| 284 | +impl TryFrom<(OfferTlvStream, InvoiceTlvStream)> for InvoiceContents { |
| 285 | + type Error = Bolt12SemanticError; |
| 286 | + |
| 287 | + fn try_from(tlv_stream: (OfferTlvStream, InvoiceTlvStream)) -> Result<Self, Self::Error> { |
| 288 | + let ( |
| 289 | + offer_tlv_stream, |
| 290 | + InvoiceTlvStream { |
| 291 | + paths, |
| 292 | + blindedpay, |
| 293 | + created_at, |
| 294 | + relative_expiry, |
| 295 | + fallbacks, |
| 296 | + features, |
| 297 | + node_id, |
| 298 | + }, |
| 299 | + ) = tlv_stream; |
| 300 | + |
| 301 | + let payment_paths = construct_payment_paths(blindedpay, paths)?; |
| 302 | + |
| 303 | + let created_at = match created_at { |
| 304 | + None => return Err(Bolt12SemanticError::MissingCreationTime), |
| 305 | + Some(timestamp) => Duration::from_secs(timestamp), |
| 306 | + }; |
| 307 | + |
| 308 | + let relative_expiry = relative_expiry.map(Into::<u64>::into).map(Duration::from_secs); |
| 309 | + |
| 310 | + let features = features.unwrap_or_else(Bolt12InvoiceFeatures::empty); |
| 311 | + |
| 312 | + let signing_pubkey = match node_id { |
| 313 | + None => return Err(Bolt12SemanticError::MissingSigningPubkey), |
| 314 | + Some(node_id) => node_id, |
| 315 | + }; |
| 316 | + |
| 317 | + Ok(InvoiceContents { |
| 318 | + offer: OfferContents::try_from(offer_tlv_stream)?, |
| 319 | + payment_paths, |
| 320 | + created_at, |
| 321 | + relative_expiry, |
| 322 | + fallbacks, |
| 323 | + features, |
| 324 | + signing_pubkey, |
| 325 | + }) |
| 326 | + } |
| 327 | +} |
0 commit comments