Skip to content

Commit 12b3135

Browse files
committed
Invoice request raw byte encoding and decoding
When reading an offer, an `invoice_request` message is sent over the wire. Implement Writeable for encoding the message and TryFrom for decoding it by defining in terms of TLV streams. These streams represent content for the payer metadata (0), reflected `offer` (1-79), `invoice_request` (80-159), and signature (240).
1 parent 6ca1d63 commit 12b3135

File tree

7 files changed

+247
-8
lines changed

7 files changed

+247
-8
lines changed

lightning/src/offers/invoice_request.rs

Lines changed: 123 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -12,9 +12,14 @@
1212
use bitcoin::blockdata::constants::ChainHash;
1313
use bitcoin::secp256k1::PublicKey;
1414
use bitcoin::secp256k1::schnorr::Signature;
15+
use core::convert::TryFrom;
16+
use crate::io;
1517
use crate::ln::features::OfferFeatures;
16-
use crate::offers::offer::OfferContents;
17-
use crate::offers::payer::PayerContents;
18+
use crate::offers::merkle::{SignatureTlvStream, self};
19+
use crate::offers::offer::{Amount, OfferContents, OfferTlvStream};
20+
use crate::offers::parse::{ParseError, SemanticError};
21+
use crate::offers::payer::{PayerContents, PayerTlvStream};
22+
use crate::util::ser::{HighZeroBytesDroppedBigSize, Readable, WithoutLength, Writeable, Writer};
1823

1924
use crate::prelude::*;
2025

@@ -49,7 +54,7 @@ impl InvoiceRequest {
4954
/// [`payer_id`].
5055
///
5156
/// [`payer_id`]: Self::payer_id
52-
pub fn payer_info(&self) -> Option<&Vec<u8>> {
57+
pub fn metadata(&self) -> Option<&Vec<u8>> {
5358
self.contents.payer.0.as_ref()
5459
}
5560

@@ -74,9 +79,9 @@ impl InvoiceRequest {
7479
self.contents.features.as_ref()
7580
}
7681

77-
/// The quantity of the offer's item conforming to [`Offer::supported_quantity`].
82+
/// The quantity of the offer's item conforming to [`Offer::is_valid_quantity`].
7883
///
79-
/// [`Offer::supported_quantity`]: crate::offers::offer::Offer::supported_quantity
84+
/// [`Offer::is_valid_quantity`]: crate::offers::offer::Offer::is_valid_quantity
8085
pub fn quantity(&self) -> Option<u64> {
8186
self.contents.quantity
8287
}
@@ -98,3 +103,116 @@ impl InvoiceRequest {
98103
self.signature
99104
}
100105
}
106+
107+
impl Writeable for InvoiceRequest {
108+
fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
109+
WithoutLength(&self.bytes).write(writer)
110+
}
111+
}
112+
113+
impl TryFrom<Vec<u8>> for InvoiceRequest {
114+
type Error = ParseError;
115+
116+
fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
117+
let tlv_stream: FullInvoiceRequestTlvStream = Readable::read(&mut &bytes[..])?;
118+
InvoiceRequest::try_from((bytes, tlv_stream))
119+
}
120+
}
121+
122+
tlv_stream!(InvoiceRequestTlvStream, InvoiceRequestTlvStreamRef, {
123+
(80, chain: ChainHash),
124+
(82, amount: (u64, HighZeroBytesDroppedBigSize)),
125+
(84, features: OfferFeatures),
126+
(86, quantity: (u64, HighZeroBytesDroppedBigSize)),
127+
(88, payer_id: PublicKey),
128+
(89, payer_note: (String, WithoutLength)),
129+
});
130+
131+
type ParsedInvoiceRequest = (Vec<u8>, FullInvoiceRequestTlvStream);
132+
133+
type FullInvoiceRequestTlvStream =
134+
(PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream, SignatureTlvStream);
135+
136+
type PartialInvoiceRequestTlvStream = (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream);
137+
138+
impl TryFrom<ParsedInvoiceRequest> for InvoiceRequest {
139+
type Error = ParseError;
140+
141+
fn try_from(invoice_request: ParsedInvoiceRequest) -> Result<Self, Self::Error> {
142+
let (bytes, tlv_stream) = invoice_request;
143+
let (
144+
payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream,
145+
SignatureTlvStream { signature },
146+
) = tlv_stream;
147+
let contents = InvoiceRequestContents::try_from(
148+
(payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream)
149+
)?;
150+
151+
if let Some(signature) = &signature {
152+
let tag = concat!("lightning", "invoice_request", "signature");
153+
merkle::verify_signature(signature, tag, &bytes, contents.payer_id)?;
154+
}
155+
156+
Ok(InvoiceRequest { bytes, contents, signature })
157+
}
158+
}
159+
160+
impl TryFrom<PartialInvoiceRequestTlvStream> for InvoiceRequestContents {
161+
type Error = SemanticError;
162+
163+
fn try_from(tlv_stream: PartialInvoiceRequestTlvStream) -> Result<Self, Self::Error> {
164+
let (
165+
PayerTlvStream { metadata },
166+
offer_tlv_stream,
167+
InvoiceRequestTlvStream { chain, amount, features, quantity, payer_id, payer_note },
168+
) = tlv_stream;
169+
170+
let payer = PayerContents(metadata);
171+
let offer = OfferContents::try_from(offer_tlv_stream)?;
172+
173+
if !offer.supports_chain(chain.unwrap_or_else(|| offer.implied_chain())) {
174+
return Err(SemanticError::UnsupportedChain);
175+
}
176+
177+
let amount_msats = match (offer.amount(), amount) {
178+
(Some(_), None) => return Err(SemanticError::MissingAmount),
179+
// TODO: Handle currency case
180+
(Some(Amount::Currency { .. }), _) => return Err(SemanticError::UnsupportedCurrency),
181+
(_, amount_msats) => amount_msats,
182+
};
183+
184+
if let Some(features) = &features {
185+
if features.requires_unknown_bits() {
186+
return Err(SemanticError::UnknownRequiredFeatures);
187+
}
188+
}
189+
190+
let expects_quantity = offer.expects_quantity();
191+
let quantity = match quantity {
192+
None if expects_quantity => return Err(SemanticError::MissingQuantity),
193+
Some(_) if !expects_quantity => return Err(SemanticError::UnexpectedQuantity),
194+
Some(quantity) if !offer.is_valid_quantity(quantity) => {
195+
return Err(SemanticError::InvalidQuantity);
196+
}
197+
quantity => quantity,
198+
};
199+
200+
{
201+
let amount_msats = amount_msats.unwrap_or(offer.amount_msats());
202+
let quantity = quantity.unwrap_or(1);
203+
if amount_msats < offer.expected_invoice_amount_msats(quantity) {
204+
return Err(SemanticError::InsufficientAmount);
205+
}
206+
}
207+
208+
209+
let payer_id = match payer_id {
210+
None => return Err(SemanticError::MissingPayerId),
211+
Some(payer_id) => payer_id,
212+
};
213+
214+
Ok(InvoiceRequestContents {
215+
payer, offer, chain, amount_msats, features, quantity, payer_id, payer_note,
216+
})
217+
}
218+
}

lightning/src/offers/merkle.rs

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,8 @@
1010
//! Tagged hashes for use in signature calculation and verification.
1111
1212
use bitcoin::hashes::{Hash, HashEngine, sha256};
13+
use bitcoin::secp256k1::{Message, PublicKey, Secp256k1, self};
14+
use bitcoin::secp256k1::schnorr::Signature;
1315
use crate::io;
1416
use crate::util::ser::{BigSize, Readable};
1517

@@ -18,6 +20,23 @@ use crate::prelude::*;
1820
/// Valid type range for signature TLV records.
1921
const SIGNATURE_TYPES: core::ops::RangeInclusive<u64> = 240..=1000;
2022

23+
tlv_stream!(SignatureTlvStream, SignatureTlvStreamRef, {
24+
(240, signature: Signature),
25+
});
26+
27+
/// Verifies the signature with a pubkey over the given bytes using a tagged hash as the message
28+
/// digest.
29+
pub(super) fn verify_signature(
30+
signature: &Signature, tag: &str, bytes: &[u8], pubkey: PublicKey,
31+
) -> Result<(), secp256k1::Error> {
32+
let tag = sha256::Hash::hash(tag.as_bytes());
33+
let merkle_root = root_hash(bytes);
34+
let digest = Message::from_slice(&tagged_hash(tag, merkle_root)).unwrap();
35+
let pubkey = pubkey.into();
36+
let secp_ctx = Secp256k1::verification_only();
37+
secp_ctx.verify_schnorr(signature, &digest, &pubkey)
38+
}
39+
2140
/// Computes a merkle root hash for the given data, which must be a well-formed TLV stream
2241
/// containing at least one TLV record.
2342
fn root_hash(data: &[u8]) -> sha256::Hash {

lightning/src/offers/offer.rs

Lines changed: 57 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -251,6 +251,11 @@ impl Offer {
251251
self.contents.chains()
252252
}
253253

254+
/// Returns whether the given chain is supported by the offer.
255+
pub fn supports_chain(&self, chain: ChainHash) -> bool {
256+
self.contents.supports_chain(chain)
257+
}
258+
254259
// TODO: Link to corresponding method in `InvoiceRequest`.
255260
/// Opaque bytes set by the originator. Useful for authentication and validating fields since it
256261
/// is reflected in `invoice_request` messages along with all the other fields from the `offer`.
@@ -260,7 +265,12 @@ impl Offer {
260265

261266
/// The minimum amount required for a successful payment of a single item.
262267
pub fn amount(&self) -> Option<&Amount> {
263-
self.contents.amount.as_ref()
268+
self.contents.amount()
269+
}
270+
271+
/// Returns the minimum amount in msats required for the given quantity.
272+
pub fn expected_invoice_amount_msats(&self, quantity: u64) -> u64 {
273+
self.contents.expected_invoice_amount_msats(quantity)
264274
}
265275

266276
/// A complete description of the purpose of the payment. Intended to be displayed to the user
@@ -310,6 +320,18 @@ impl Offer {
310320
self.contents.supported_quantity()
311321
}
312322

323+
/// Returns whether the given quantity is valid for the offer.
324+
pub fn is_valid_quantity(&self, quantity: u64) -> bool {
325+
self.contents.is_valid_quantity(quantity)
326+
}
327+
328+
/// Returns whether a quantity is expected in an [`InvoiceRequest`] for the offer.
329+
///
330+
/// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
331+
pub fn expects_quantity(&self) -> bool {
332+
self.contents.expects_quantity()
333+
}
334+
313335
/// The public key used by the recipient to sign invoices.
314336
pub fn signing_pubkey(&self) -> PublicKey {
315337
self.contents.signing_pubkey.unwrap()
@@ -336,14 +358,42 @@ impl OfferContents {
336358
ChainHash::using_genesis_block(Network::Bitcoin)
337359
}
338360

361+
pub fn supports_chain(&self, chain: ChainHash) -> bool {
362+
self.chains().contains(&chain)
363+
}
364+
365+
pub fn amount(&self) -> Option<&Amount> {
366+
self.amount.as_ref()
367+
}
368+
339369
pub fn amount_msats(&self) -> u64 {
340-
self.amount.as_ref().map(Amount::as_msats).unwrap_or(0)
370+
self.amount().map(Amount::as_msats).unwrap_or(0)
371+
}
372+
373+
pub fn expected_invoice_amount_msats(&self, quantity: u64) -> u64 {
374+
self.amount_msats() * quantity
341375
}
342376

343377
pub fn supported_quantity(&self) -> Quantity {
344378
self.supported_quantity
345379
}
346380

381+
pub fn is_valid_quantity(&self, quantity: u64) -> bool {
382+
match self.supported_quantity {
383+
Quantity::One => false,
384+
Quantity::Many => quantity > 0,
385+
Quantity::Max(n) => quantity > 0 && quantity <= n.get(),
386+
}
387+
}
388+
389+
pub fn expects_quantity(&self) -> bool {
390+
match self.supported_quantity {
391+
Quantity::One => false,
392+
Quantity::Many => true,
393+
Quantity::Max(_) => true,
394+
}
395+
}
396+
347397
fn as_tlv_stream(&self) -> OfferTlvStreamRef {
348398
let (currency, amount) = match &self.amount {
349399
None => (None, None),
@@ -581,6 +631,7 @@ mod tests {
581631

582632
assert_eq!(offer.bytes, buffer.as_slice());
583633
assert_eq!(offer.chains(), vec![ChainHash::using_genesis_block(Network::Bitcoin)]);
634+
assert!(offer.supports_chain(ChainHash::using_genesis_block(Network::Bitcoin)));
584635
assert_eq!(offer.metadata(), None);
585636
assert_eq!(offer.amount(), None);
586637
assert_eq!(offer.description(), PrintableString("foo"));
@@ -622,6 +673,7 @@ mod tests {
622673
.chain(Network::Bitcoin)
623674
.build()
624675
.unwrap();
676+
assert!(offer.supports_chain(chain));
625677
assert_eq!(offer.chains(), vec![chain]);
626678
assert_eq!(offer.as_tlv_stream().chains, Some(&vec![chain]));
627679

@@ -630,6 +682,7 @@ mod tests {
630682
.chain(Network::Bitcoin)
631683
.build()
632684
.unwrap();
685+
assert!(offer.supports_chain(chain));
633686
assert_eq!(offer.chains(), vec![chain]);
634687
assert_eq!(offer.as_tlv_stream().chains, Some(&vec![chain]));
635688

@@ -638,6 +691,8 @@ mod tests {
638691
.chain(Network::Testnet)
639692
.build()
640693
.unwrap();
694+
assert!(offer.supports_chain(chains[0]));
695+
assert!(offer.supports_chain(chains[1]));
641696
assert_eq!(offer.chains(), chains);
642697
assert_eq!(offer.as_tlv_stream().chains, Some(&chains));
643698
}

lightning/src/offers/parse.rs

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
1212
use bitcoin::bech32;
1313
use bitcoin::bech32::{FromBase32, ToBase32};
14+
use bitcoin::secp256k1;
1415
use core::convert::TryFrom;
1516
use core::fmt;
1617
use crate::ln::msgs::DecodeError;
@@ -67,23 +68,39 @@ pub enum ParseError {
6768
Decode(DecodeError),
6869
/// The parsed message has invalid semantics.
6970
InvalidSemantics(SemanticError),
71+
/// The parsed message has an invalid signature.
72+
InvalidSignature(secp256k1::Error),
7073
}
7174

7275
/// Error when interpreting a TLV stream as a specific type.
7376
#[derive(Debug, PartialEq)]
7477
pub enum SemanticError {
78+
/// The provided chain hash does not correspond to a supported chain.
79+
UnsupportedChain,
7580
/// An amount was expected but was missing.
7681
MissingAmount,
7782
/// An amount exceeded the maximum number of bitcoin.
7883
InvalidAmount,
84+
/// An amount was provided but was not sufficient in value.
85+
InsufficientAmount,
86+
/// A currency was provided that is not supported.
87+
UnsupportedCurrency,
88+
/// A feature was required but is unknown.
89+
UnknownRequiredFeatures,
7990
/// A required description was not provided.
8091
MissingDescription,
8192
/// A node id was not provided.
8293
MissingNodeId,
8394
/// An empty set of blinded paths was provided.
8495
MissingPaths,
96+
/// A quantity was not provided.
97+
MissingQuantity,
8598
/// An unsupported quantity was provided.
8699
InvalidQuantity,
100+
/// A quantity or quantity bounds was provided but was not expected.
101+
UnexpectedQuantity,
102+
/// A payer id was expected but was missing.
103+
MissingPayerId,
87104
}
88105

89106
impl From<bech32::Error> for ParseError {
@@ -103,3 +120,9 @@ impl From<SemanticError> for ParseError {
103120
Self::InvalidSemantics(error)
104121
}
105122
}
123+
124+
impl From<secp256k1::Error> for ParseError {
125+
fn from(error: secp256k1::Error) -> Self {
126+
Self::InvalidSignature(error)
127+
}
128+
}

lightning/src/offers/payer.rs

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,8 @@
99

1010
//! Data structures and encoding for `invoice_request_payer_info` records.
1111
12+
use crate::util::ser::WithoutLength;
13+
1214
use crate::prelude::*;
1315

1416
/// An unpredictable sequence of bytes typically containing information needed to derive
@@ -17,3 +19,7 @@ use crate::prelude::*;
1719
/// [`InvoiceRequestContents::payer_id`]: invoice_request::InvoiceRequestContents::payer_id
1820
#[derive(Clone, Debug)]
1921
pub(crate) struct PayerContents(pub Option<Vec<u8>>);
22+
23+
tlv_stream!(PayerTlvStream, PayerTlvStreamRef, {
24+
(0, metadata: (Vec<u8>, WithoutLength)),
25+
});

0 commit comments

Comments
 (0)