Update documentation on `[u8; 32]` wrappers for clarity
[rust-lightning] / lightning / src / offers / offer.rs
index f9cc07b3117de6534d10dd8cfa4eb59f3c95a76a..8e93a93f8736f0163038c25977cbec303977b0c7 100644 (file)
@@ -79,7 +79,6 @@
 use bitcoin::blockdata::constants::ChainHash;
 use bitcoin::network::constants::Network;
 use bitcoin::secp256k1::{KeyPair, PublicKey, Secp256k1, self};
-use core::convert::TryFrom;
 use core::hash::{Hash, Hasher};
 use core::num::NonZeroU64;
 use core::ops::Deref;
@@ -91,11 +90,11 @@ use crate::blinded_path::BlindedPath;
 use crate::ln::channelmanager::PaymentId;
 use crate::ln::features::OfferFeatures;
 use crate::ln::inbound_payment::{ExpandedKey, IV_LEN, Nonce};
-use crate::ln::msgs::MAX_VALUE_MSAT;
-use crate::offers::merkle::TlvStream;
+use crate::ln::msgs::{DecodeError, MAX_VALUE_MSAT};
+use crate::offers::merkle::{TaggedHash, TlvStream};
 use crate::offers::parse::{Bech32Encode, Bolt12ParseError, Bolt12SemanticError, ParsedMessage};
 use crate::offers::signer::{Metadata, MetadataMaterial, self};
-use crate::util::ser::{HighZeroBytesDroppedBigSize, WithoutLength, Writeable, Writer};
+use crate::util::ser::{HighZeroBytesDroppedBigSize, Readable, WithoutLength, Writeable, Writer};
 use crate::util::string::PrintableString;
 
 #[cfg(not(c_bindings))]
@@ -115,6 +114,37 @@ use std::time::SystemTime;
 
 pub(super) const IV_BYTES: &[u8; IV_LEN] = b"LDK Offer ~~~~~~";
 
+/// An identifier for an [`Offer`] built using [`DerivedMetadata`].
+#[derive(Clone, Copy, Debug, Eq, PartialEq)]
+pub struct OfferId(pub [u8; 32]);
+
+impl OfferId {
+       const ID_TAG: &'static str = "LDK Offer ID";
+
+       fn from_valid_offer_tlv_stream(bytes: &[u8]) -> Self {
+               let tagged_hash = TaggedHash::from_valid_tlv_stream_bytes(Self::ID_TAG, bytes);
+               Self(tagged_hash.to_bytes())
+       }
+
+       fn from_valid_invreq_tlv_stream(bytes: &[u8]) -> Self {
+               let tlv_stream = TlvStream::new(bytes).range(OFFER_TYPES);
+               let tagged_hash = TaggedHash::from_tlv_stream(Self::ID_TAG, tlv_stream);
+               Self(tagged_hash.to_bytes())
+       }
+}
+
+impl Writeable for OfferId {
+       fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
+               self.0.write(w)
+       }
+}
+
+impl Readable for OfferId {
+       fn read<R: io::Read>(r: &mut R) -> Result<Self, DecodeError> {
+               Ok(OfferId(Readable::read(r)?))
+       }
+}
+
 /// Builds an [`Offer`] for the "offer to be paid" flow.
 ///
 /// See [module-level documentation] for usage.
@@ -196,7 +226,7 @@ macro_rules! offer_explicit_metadata_builder_methods { (
                        offer: OfferContents {
                                chains: None, metadata: None, amount: None, description,
                                features: OfferFeatures::empty(), absolute_expiry: None, issuer: None, paths: None,
-                               supported_quantity: Quantity::One, signing_pubkey,
+                               supported_quantity: Quantity::One, signing_pubkey: Some(signing_pubkey),
                        },
                        metadata_strategy: core::marker::PhantomData,
                        secp_ctx: None,
@@ -235,7 +265,7 @@ macro_rules! offer_derived_metadata_builder_methods { ($secp_context: ty) => {
                        offer: OfferContents {
                                chains: None, metadata: Some(metadata), amount: None, description,
                                features: OfferFeatures::empty(), absolute_expiry: None, issuer: None, paths: None,
-                               supported_quantity: Quantity::One, signing_pubkey: node_id,
+                               supported_quantity: Quantity::One, signing_pubkey: Some(node_id),
                        },
                        metadata_strategy: core::marker::PhantomData,
                        secp_ctx: Some(secp_ctx),
@@ -361,7 +391,7 @@ macro_rules! offer_builder_methods { (
                                let (derived_metadata, keys) = metadata.derive_from(tlv_stream, $self.secp_ctx);
                                metadata = derived_metadata;
                                if let Some(keys) = keys {
-                                       $self.offer.signing_pubkey = keys.public_key();
+                                       $self.offer.signing_pubkey = Some(keys.public_key());
                                }
                        }
 
@@ -371,12 +401,15 @@ macro_rules! offer_builder_methods { (
                let mut bytes = Vec::new();
                $self.offer.write(&mut bytes).unwrap();
 
+               let id = OfferId::from_valid_offer_tlv_stream(&bytes);
+
                Offer {
                        bytes,
                        #[cfg(not(c_bindings))]
                        contents: $self.offer,
                        #[cfg(c_bindings)]
-                       contents: $self.offer.clone()
+                       contents: $self.offer.clone(),
+                       id,
                }
        }
 } }
@@ -403,6 +436,12 @@ macro_rules! offer_builder_test_methods { (
                $return_value
        }
 
+       #[cfg_attr(c_bindings, allow(dead_code))]
+       pub(crate) fn clear_signing_pubkey($($self_mut)* $self: $self_type) -> $return_type {
+               $self.offer.signing_pubkey = None;
+               $return_value
+       }
+
        #[cfg_attr(c_bindings, allow(dead_code))]
        pub(super) fn build_unchecked($self: $self_type) -> Offer {
                $self.build_without_checks()
@@ -460,6 +499,16 @@ for OfferWithDerivedMetadataBuilder<'a> {
        }
 }
 
+#[cfg(c_bindings)]
+impl<'a> From<OfferWithDerivedMetadataBuilder<'a>>
+for OfferBuilder<'a, DerivedMetadata, secp256k1::All> {
+       fn from(builder: OfferWithDerivedMetadataBuilder<'a>) -> Self {
+               let OfferWithDerivedMetadataBuilder { offer, metadata_strategy, secp_ctx } = builder;
+
+               Self { offer, metadata_strategy, secp_ctx }
+       }
+}
+
 /// An `Offer` is a potentially long-lived proposal for payment of a good or service.
 ///
 /// An offer is a precursor to an [`InvoiceRequest`]. A merchant publishes an offer from which a
@@ -479,6 +528,7 @@ pub struct Offer {
        // fields.
        pub(super) bytes: Vec<u8>,
        pub(super) contents: OfferContents,
+       id: OfferId,
 }
 
 /// The contents of an [`Offer`], which may be shared with an [`InvoiceRequest`] or a
@@ -498,7 +548,7 @@ pub(super) struct OfferContents {
        issuer: Option<String>,
        paths: Option<Vec<BlindedPath>>,
        supported_quantity: Quantity,
-       signing_pubkey: PublicKey,
+       signing_pubkey: Option<PublicKey>,
 }
 
 macro_rules! offer_accessors { ($self: ident, $contents: expr) => {
@@ -560,7 +610,7 @@ macro_rules! offer_accessors { ($self: ident, $contents: expr) => {
        }
 
        /// The public key used by the recipient to sign invoices.
-       pub fn signing_pubkey(&$self) -> bitcoin::secp256k1::PublicKey {
+       pub fn signing_pubkey(&$self) -> Option<bitcoin::secp256k1::PublicKey> {
                $contents.signing_pubkey()
        }
 } }
@@ -568,6 +618,11 @@ macro_rules! offer_accessors { ($self: ident, $contents: expr) => {
 impl Offer {
        offer_accessors!(self, self.contents);
 
+       /// Returns the id of the offer.
+       pub fn id(&self) -> OfferId {
+               self.id
+       }
+
        pub(super) fn implied_chain(&self) -> ChainHash {
                self.contents.implied_chain()
        }
@@ -837,14 +892,14 @@ impl OfferContents {
                }
        }
 
-       pub(super) fn signing_pubkey(&self) -> PublicKey {
+       pub(super) fn signing_pubkey(&self) -> Option<PublicKey> {
                self.signing_pubkey
        }
 
        /// Verifies that the offer metadata was produced from the offer in the TLV stream.
        pub(super) fn verify<T: secp256k1::Signing>(
                &self, bytes: &[u8], key: &ExpandedKey, secp_ctx: &Secp256k1<T>
-       ) -> Result<Option<KeyPair>, ()> {
+       ) -> Result<(OfferId, Option<KeyPair>), ()> {
                match self.metadata() {
                        Some(metadata) => {
                                let tlv_stream = TlvStream::new(bytes).range(OFFER_TYPES).filter(|record| {
@@ -856,9 +911,17 @@ impl OfferContents {
                                                _ => true,
                                        }
                                });
-                               signer::verify_recipient_metadata(
-                                       metadata, key, IV_BYTES, self.signing_pubkey(), tlv_stream, secp_ctx
-                               )
+                               let signing_pubkey = match self.signing_pubkey() {
+                                       Some(signing_pubkey) => signing_pubkey,
+                                       None => return Err(()),
+                               };
+                               let keys = signer::verify_recipient_metadata(
+                                       metadata, key, IV_BYTES, signing_pubkey, tlv_stream, secp_ctx
+                               )?;
+
+                               let offer_id = OfferId::from_valid_invreq_tlv_stream(bytes);
+
+                               Ok((offer_id, keys))
                        },
                        None => Err(()),
                }
@@ -888,7 +951,7 @@ impl OfferContents {
                        paths: self.paths.as_ref(),
                        issuer: self.issuer.as_ref(),
                        quantity_max: self.supported_quantity.to_tlv_record(),
-                       node_id: Some(&self.signing_pubkey),
+                       node_id: self.signing_pubkey.as_ref(),
                }
        }
 }
@@ -993,7 +1056,9 @@ impl TryFrom<Vec<u8>> for Offer {
                let offer = ParsedMessage::<OfferTlvStream>::try_from(bytes)?;
                let ParsedMessage { bytes, tlv_stream } = offer;
                let contents = OfferContents::try_from(tlv_stream)?;
-               Ok(Offer { bytes, contents })
+               let id = OfferId::from_valid_offer_tlv_stream(&bytes);
+
+               Ok(Offer { bytes, contents, id })
        }
 }
 
@@ -1034,9 +1099,10 @@ impl TryFrom<OfferTlvStream> for OfferContents {
                        Some(n) => Quantity::Bounded(NonZeroU64::new(n).unwrap()),
                };
 
-               let signing_pubkey = match node_id {
-                       None => return Err(Bolt12SemanticError::MissingSigningPubkey),
-                       Some(node_id) => node_id,
+               let (signing_pubkey, paths) = match (node_id, paths) {
+                       (None, None) => return Err(Bolt12SemanticError::MissingSigningPubkey),
+                       (_, Some(paths)) if paths.is_empty() => return Err(Bolt12SemanticError::MissingPaths),
+                       (node_id, paths) => (node_id, paths),
                };
 
                Ok(OfferContents {
@@ -1067,10 +1133,9 @@ mod tests {
        use bitcoin::blockdata::constants::ChainHash;
        use bitcoin::network::constants::Network;
        use bitcoin::secp256k1::Secp256k1;
-       use core::convert::TryFrom;
        use core::num::NonZeroU64;
        use core::time::Duration;
-       use crate::blinded_path::{BlindedHop, BlindedPath};
+       use crate::blinded_path::{BlindedHop, BlindedPath, IntroductionNode};
        use crate::sign::KeyMaterial;
        use crate::ln::features::OfferFeatures;
        use crate::ln::inbound_payment::ExpandedKey;
@@ -1100,7 +1165,7 @@ mod tests {
                assert_eq!(offer.paths(), &[]);
                assert_eq!(offer.issuer(), None);
                assert_eq!(offer.supported_quantity(), Quantity::One);
-               assert_eq!(offer.signing_pubkey(), pubkey(42));
+               assert_eq!(offer.signing_pubkey(), Some(pubkey(42)));
 
                assert_eq!(
                        offer.as_tlv_stream(),
@@ -1197,12 +1262,15 @@ mod tests {
                        ::deriving_signing_pubkey(desc, node_id, &expanded_key, &entropy, &secp_ctx)
                        .amount_msats(1000)
                        .build().unwrap();
-               assert_eq!(offer.signing_pubkey(), node_id);
+               assert_eq!(offer.signing_pubkey(), Some(node_id));
 
                let invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
                        .build().unwrap()
                        .sign(payer_sign).unwrap();
-               assert!(invoice_request.verify(&expanded_key, &secp_ctx).is_ok());
+               match invoice_request.verify(&expanded_key, &secp_ctx) {
+                       Ok(invoice_request) => assert_eq!(invoice_request.offer_id, offer.id()),
+                       Err(_) => panic!("unexpected error"),
+               }
 
                // Fails verification with altered offer field
                let mut tlv_stream = offer.as_tlv_stream();
@@ -1241,7 +1309,7 @@ mod tests {
                let secp_ctx = Secp256k1::new();
 
                let blinded_path = BlindedPath {
-                       introduction_node_id: pubkey(40),
+                       introduction_node: IntroductionNode::NodeId(pubkey(40)),
                        blinding_point: pubkey(41),
                        blinded_hops: vec![
                                BlindedHop { blinded_node_id: pubkey(42), encrypted_payload: vec![0; 43] },
@@ -1256,12 +1324,15 @@ mod tests {
                        .amount_msats(1000)
                        .path(blinded_path)
                        .build().unwrap();
-               assert_ne!(offer.signing_pubkey(), node_id);
+               assert_ne!(offer.signing_pubkey(), Some(node_id));
 
                let invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
                        .build().unwrap()
                        .sign(payer_sign).unwrap();
-               assert!(invoice_request.verify(&expanded_key, &secp_ctx).is_ok());
+               match invoice_request.verify(&expanded_key, &secp_ctx) {
+                       Ok(invoice_request) => assert_eq!(invoice_request.offer_id, offer.id()),
+                       Err(_) => panic!("unexpected error"),
+               }
 
                // Fails verification with altered offer field
                let mut tlv_stream = offer.as_tlv_stream();
@@ -1387,7 +1458,7 @@ mod tests {
        fn builds_offer_with_paths() {
                let paths = vec![
                        BlindedPath {
-                               introduction_node_id: pubkey(40),
+                               introduction_node: IntroductionNode::NodeId(pubkey(40)),
                                blinding_point: pubkey(41),
                                blinded_hops: vec![
                                        BlindedHop { blinded_node_id: pubkey(43), encrypted_payload: vec![0; 43] },
@@ -1395,7 +1466,7 @@ mod tests {
                                ],
                        },
                        BlindedPath {
-                               introduction_node_id: pubkey(40),
+                               introduction_node: IntroductionNode::NodeId(pubkey(40)),
                                blinding_point: pubkey(41),
                                blinded_hops: vec![
                                        BlindedHop { blinded_node_id: pubkey(45), encrypted_payload: vec![0; 45] },
@@ -1411,7 +1482,7 @@ mod tests {
                        .unwrap();
                let tlv_stream = offer.as_tlv_stream();
                assert_eq!(offer.paths(), paths.as_slice());
-               assert_eq!(offer.signing_pubkey(), pubkey(42));
+               assert_eq!(offer.signing_pubkey(), Some(pubkey(42)));
                assert_ne!(pubkey(42), pubkey(44));
                assert_eq!(tlv_stream.paths, Some(&paths));
                assert_eq!(tlv_stream.node_id, Some(&pubkey(42)));
@@ -1577,7 +1648,7 @@ mod tests {
        fn parses_offer_with_paths() {
                let offer = OfferBuilder::new("foo".into(), pubkey(42))
                        .path(BlindedPath {
-                               introduction_node_id: pubkey(40),
+                               introduction_node: IntroductionNode::NodeId(pubkey(40)),
                                blinding_point: pubkey(41),
                                blinded_hops: vec![
                                        BlindedHop { blinded_node_id: pubkey(43), encrypted_payload: vec![0; 43] },
@@ -1585,7 +1656,7 @@ mod tests {
                                ],
                        })
                        .path(BlindedPath {
-                               introduction_node_id: pubkey(40),
+                               introduction_node: IntroductionNode::NodeId(pubkey(40)),
                                blinding_point: pubkey(41),
                                blinded_hops: vec![
                                        BlindedHop { blinded_node_id: pubkey(45), encrypted_payload: vec![0; 45] },
@@ -1598,12 +1669,31 @@ mod tests {
                        panic!("error parsing offer: {:?}", e);
                }
 
+               let offer = OfferBuilder::new("foo".into(), pubkey(42))
+                       .path(BlindedPath {
+                               introduction_node: IntroductionNode::NodeId(pubkey(40)),
+                               blinding_point: pubkey(41),
+                               blinded_hops: vec![
+                                       BlindedHop { blinded_node_id: pubkey(43), encrypted_payload: vec![0; 43] },
+                                       BlindedHop { blinded_node_id: pubkey(44), encrypted_payload: vec![0; 44] },
+                               ],
+                       })
+                       .clear_signing_pubkey()
+                       .build()
+                       .unwrap();
+               if let Err(e) = offer.to_string().parse::<Offer>() {
+                       panic!("error parsing offer: {:?}", e);
+               }
+
                let mut builder = OfferBuilder::new("foo".into(), pubkey(42));
                builder.offer.paths = Some(vec![]);
 
                let offer = builder.build().unwrap();
-               if let Err(e) = offer.to_string().parse::<Offer>() {
-                       panic!("error parsing offer: {:?}", e);
+               match offer.to_string().parse::<Offer>() {
+                       Ok(_) => panic!("expected error"),
+                       Err(e) => {
+                               assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingPaths));
+                       },
                }
        }