Skip to content

Commit 1e1ec45

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 7035f62 commit 1e1ec45

File tree

7 files changed

+249
-7
lines changed

7 files changed

+249
-7
lines changed

lightning/src/offers/invoice_request.rs

Lines changed: 122 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,115 @@ 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+
(Some(Amount::Currency { .. }), _) => return Err(SemanticError::UnsupportedCurrency),
180+
(_, amount_msats) => amount_msats,
181+
};
182+
183+
if let Some(features) = &features {
184+
if features.requires_unknown_bits() {
185+
return Err(SemanticError::UnknownRequiredFeatures);
186+
}
187+
}
188+
189+
let expects_quantity = offer.expects_quantity();
190+
let quantity = match quantity {
191+
None if expects_quantity => return Err(SemanticError::MissingQuantity),
192+
Some(_) if !expects_quantity => return Err(SemanticError::UnexpectedQuantity),
193+
Some(quantity) if !offer.is_valid_quantity(quantity) => {
194+
return Err(SemanticError::InvalidQuantity);
195+
}
196+
quantity => quantity,
197+
};
198+
199+
{
200+
let amount_msats = amount_msats.unwrap_or(offer.amount_msats());
201+
let quantity = quantity.unwrap_or(1);
202+
if amount_msats < offer.expected_invoice_amount_msats(quantity) {
203+
return Err(SemanticError::InsufficientAmount);
204+
}
205+
}
206+
207+
208+
let payer_id = match payer_id {
209+
None => return Err(SemanticError::MissingPayerId),
210+
Some(payer_id) => payer_id,
211+
};
212+
213+
Ok(InvoiceRequestContents {
214+
payer, offer, chain, amount_msats, features, quantity, payer_id, payer_note,
215+
})
216+
}
217+
}

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: 62 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -269,6 +269,11 @@ impl Offer {
269269
self.contents.chains()
270270
}
271271

272+
/// Returns whether the given chain is supported by the offer.
273+
pub fn supports_chain(&self, chain: ChainHash) -> bool {
274+
self.contents.supports_chain(chain)
275+
}
276+
272277
// TODO: Link to corresponding method in `InvoiceRequest`.
273278
/// Opaque bytes set by the originator. Useful for authentication and validating fields since it
274279
/// is reflected in `invoice_request` messages along with all the other fields from the `offer`.
@@ -278,7 +283,7 @@ impl Offer {
278283

279284
/// The minimum amount required for a successful payment of a single item.
280285
pub fn amount(&self) -> Option<&Amount> {
281-
self.contents.amount.as_ref()
286+
self.contents.amount()
282287
}
283288

284289
/// A complete description of the purpose of the payment. Intended to be displayed to the user
@@ -328,6 +333,18 @@ impl Offer {
328333
self.contents.supported_quantity()
329334
}
330335

336+
/// Returns whether the given quantity is valid for the offer.
337+
pub fn is_valid_quantity(&self, quantity: u64) -> bool {
338+
self.contents.is_valid_quantity(quantity)
339+
}
340+
341+
/// Returns whether a quantity is expected in an [`InvoiceRequest`] for the offer.
342+
///
343+
/// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
344+
pub fn expects_quantity(&self) -> bool {
345+
self.contents.expects_quantity()
346+
}
347+
331348
/// The public key used by the recipient to sign invoices.
332349
pub fn signing_pubkey(&self) -> PublicKey {
333350
self.contents.signing_pubkey.unwrap()
@@ -354,10 +371,48 @@ impl OfferContents {
354371
ChainHash::using_genesis_block(Network::Bitcoin)
355372
}
356373

374+
pub fn supports_chain(&self, chain: ChainHash) -> bool {
375+
self.chains().contains(&chain)
376+
}
377+
378+
pub fn amount(&self) -> Option<&Amount> {
379+
self.amount.as_ref()
380+
}
381+
382+
pub fn amount_msats(&self) -> u64 {
383+
match self.amount() {
384+
None => 0,
385+
Some(&Amount::Bitcoin { amount_msats }) => amount_msats,
386+
Some(&Amount::Currency { .. }) => unreachable!(),
387+
}
388+
}
389+
390+
pub fn expected_invoice_amount_msats(&self, quantity: u64) -> u64 {
391+
self.amount_msats() * quantity
392+
}
393+
357394
pub fn supported_quantity(&self) -> Quantity {
358395
self.supported_quantity
359396
}
360397

398+
pub fn is_valid_quantity(&self, quantity: u64) -> bool {
399+
match self.supported_quantity {
400+
Quantity::Bounded(n) => {
401+
let n = n.get();
402+
if n == 1 { false }
403+
else { quantity > 0 && quantity <= n }
404+
},
405+
Quantity::Unbounded => quantity > 0,
406+
}
407+
}
408+
409+
pub fn expects_quantity(&self) -> bool {
410+
match self.supported_quantity {
411+
Quantity::Bounded(n) => n.get() != 1,
412+
Quantity::Unbounded => true,
413+
}
414+
}
415+
361416
fn as_tlv_stream(&self) -> OfferTlvStreamRef {
362417
let (currency, amount) = match &self.amount {
363418
None => (None, None),
@@ -589,6 +644,7 @@ mod tests {
589644

590645
assert_eq!(offer.bytes, buffer.as_slice());
591646
assert_eq!(offer.chains(), vec![ChainHash::using_genesis_block(Network::Bitcoin)]);
647+
assert!(offer.supports_chain(ChainHash::using_genesis_block(Network::Bitcoin)));
592648
assert_eq!(offer.metadata(), None);
593649
assert_eq!(offer.amount(), None);
594650
assert_eq!(offer.description(), PrintableString("foo"));
@@ -627,13 +683,15 @@ mod tests {
627683
.chain(Network::Bitcoin)
628684
.build()
629685
.unwrap();
686+
assert!(offer.supports_chain(mainnet));
630687
assert_eq!(offer.chains(), vec![mainnet]);
631688
assert_eq!(offer.as_tlv_stream().chains, None);
632689

633690
let offer = OfferBuilder::new("foo".into(), pubkey(42))
634691
.chain(Network::Testnet)
635692
.build()
636693
.unwrap();
694+
assert!(offer.supports_chain(testnet));
637695
assert_eq!(offer.chains(), vec![testnet]);
638696
assert_eq!(offer.as_tlv_stream().chains, Some(&vec![testnet]));
639697

@@ -642,6 +700,7 @@ mod tests {
642700
.chain(Network::Testnet)
643701
.build()
644702
.unwrap();
703+
assert!(offer.supports_chain(testnet));
645704
assert_eq!(offer.chains(), vec![testnet]);
646705
assert_eq!(offer.as_tlv_stream().chains, Some(&vec![testnet]));
647706

@@ -650,6 +709,8 @@ mod tests {
650709
.chain(Network::Testnet)
651710
.build()
652711
.unwrap();
712+
assert!(offer.supports_chain(mainnet));
713+
assert!(offer.supports_chain(testnet));
653714
assert_eq!(offer.chains(), vec![mainnet, testnet]);
654715
assert_eq!(offer.as_tlv_stream().chains, Some(&vec![mainnet, testnet]));
655716
}

lightning/src/offers/parse.rs

Lines changed: 21 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,25 +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,
7986
/// A currency was provided that is not supported.
8087
UnsupportedCurrency,
88+
/// A feature was required but is unknown.
89+
UnknownRequiredFeatures,
8190
/// A required description was not provided.
8291
MissingDescription,
8392
/// A node id was not provided.
8493
MissingNodeId,
8594
/// An empty set of blinded paths was provided.
8695
MissingPaths,
96+
/// A quantity was not provided.
97+
MissingQuantity,
8798
/// An unsupported quantity was provided.
8899
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,
89104
}
90105

91106
impl From<bech32::Error> for ParseError {
@@ -105,3 +120,9 @@ impl From<SemanticError> for ParseError {
105120
Self::InvalidSemantics(error)
106121
}
107122
}
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)