Skip to content

Commit 1ce20f8

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 0404847 commit 1ce20f8

File tree

7 files changed

+249
-8
lines changed

7 files changed

+249
-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
@@ -248,6 +248,11 @@ impl Offer {
248248
self.contents.chains()
249249
}
250250

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

258263
/// The minimum amount required for a successful payment of a single item.
259264
pub fn amount(&self) -> Option<&Amount> {
260-
self.contents.amount.as_ref()
265+
self.contents.amount()
266+
}
267+
268+
/// Returns the minimum amount in msats required for the given quantity.
269+
pub fn expected_invoice_amount_msats(&self, quantity: u64) -> u64 {
270+
self.contents.expected_invoice_amount_msats(quantity)
261271
}
262272

263273
/// A complete description of the purpose of the payment. Intended to be displayed to the user
@@ -307,6 +317,18 @@ impl Offer {
307317
self.contents.supported_quantity()
308318
}
309319

320+
/// Returns whether the given quantity is valid for the offer.
321+
pub fn is_valid_quantity(&self, quantity: u64) -> bool {
322+
self.contents.is_valid_quantity(quantity)
323+
}
324+
325+
/// Returns whether a quantity is expected in an [`InvoiceRequest`] for the offer.
326+
///
327+
/// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
328+
pub fn expects_quantity(&self) -> bool {
329+
self.contents.expects_quantity()
330+
}
331+
310332
/// The public key used by the recipient to sign invoices.
311333
pub fn signing_pubkey(&self) -> PublicKey {
312334
self.contents.signing_pubkey.unwrap()
@@ -333,14 +355,42 @@ impl OfferContents {
333355
ChainHash::using_genesis_block(Network::Bitcoin)
334356
}
335357

358+
pub fn supports_chain(&self, chain: ChainHash) -> bool {
359+
self.chains().contains(&chain)
360+
}
361+
362+
pub fn amount(&self) -> Option<&Amount> {
363+
self.amount.as_ref()
364+
}
365+
336366
pub fn amount_msats(&self) -> u64 {
337-
self.amount.as_ref().map(Amount::as_msats).unwrap_or(0)
367+
self.amount().map(Amount::as_msats).unwrap_or(0)
368+
}
369+
370+
pub fn expected_invoice_amount_msats(&self, quantity: u64) -> u64 {
371+
self.amount_msats() * quantity
338372
}
339373

340374
pub fn supported_quantity(&self) -> Quantity {
341375
self.supported_quantity
342376
}
343377

378+
pub fn is_valid_quantity(&self, quantity: u64) -> bool {
379+
match self.supported_quantity {
380+
Quantity::One => false,
381+
Quantity::Many => quantity > 0,
382+
Quantity::Max(n) => quantity > 0 && quantity <= n.get(),
383+
}
384+
}
385+
386+
pub fn expects_quantity(&self) -> bool {
387+
match self.supported_quantity {
388+
Quantity::One => false,
389+
Quantity::Many => true,
390+
Quantity::Max(_) => true,
391+
}
392+
}
393+
344394
fn as_tlv_stream(&self) -> OfferTlvStreamRef {
345395
let (currency, amount) = match &self.amount {
346396
None => (None, None),
@@ -574,6 +624,7 @@ mod tests {
574624

575625
assert_eq!(offer.bytes, buffer.as_slice());
576626
assert_eq!(offer.chains(), vec![ChainHash::using_genesis_block(Network::Bitcoin)]);
627+
assert!(offer.supports_chain(ChainHash::using_genesis_block(Network::Bitcoin)));
577628
assert_eq!(offer.metadata(), None);
578629
assert_eq!(offer.amount(), None);
579630
assert_eq!(offer.description(), PrintableString("foo"));
@@ -615,6 +666,7 @@ mod tests {
615666
.chain(Network::Bitcoin)
616667
.build()
617668
.unwrap();
669+
assert!(offer.supports_chain(chain));
618670
assert_eq!(offer.chains(), vec![chain]);
619671
assert_eq!(offer.as_tlv_stream().chains, Some(&vec![chain]));
620672

@@ -623,6 +675,7 @@ mod tests {
623675
.chain(Network::Bitcoin)
624676
.build()
625677
.unwrap();
678+
assert!(offer.supports_chain(chain));
626679
assert_eq!(offer.chains(), vec![chain]);
627680
assert_eq!(offer.as_tlv_stream().chains, Some(&vec![chain]));
628681

@@ -631,6 +684,8 @@ mod tests {
631684
.chain(Network::Testnet)
632685
.build()
633686
.unwrap();
687+
assert!(offer.supports_chain(chains[0]));
688+
assert!(offer.supports_chain(chains[1]));
634689
assert_eq!(offer.chains(), chains);
635690
assert_eq!(offer.as_tlv_stream().chains, Some(&chains));
636691
}

lightning/src/offers/parse.rs

Lines changed: 25 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,21 +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,
98+
/// A quantity outside of a valid range was provided.
99+
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,
85104
}
86105

87106
impl From<bech32::Error> for ParseError {
@@ -101,3 +120,9 @@ impl From<SemanticError> for ParseError {
101120
Self::InvalidSemantics(error)
102121
}
103122
}
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)