Skip to content

BOLT 12 offer parsing - #1726

Merged
TheBlueMatt merged 5 commits into
lightningdevkit:mainfrom
jkczyz:2022-09-offer-parsing
Nov 18, 2022
Merged

BOLT 12 offer parsing#1726
TheBlueMatt merged 5 commits into
lightningdevkit:mainfrom
jkczyz:2022-09-offer-parsing

Conversation

@jkczyz

Copy link
Copy Markdown
Contributor

Add common bech32 parsing for BOLT 12 messages. The encoding is similar to bech32 only without a checksum and with support for continuing messages across multiple parts.

Messages implementing Bech32Encode are parsed into a TLV stream, which is converted to the desired message content while performing semantic checks. Checking after conversion allows for more elaborate checks of data composed of multiple TLV records and for more meaningful error messages.

The parsed bytes are also saved to allow creating messages with mirrored data, even if TLV records are unknown.

Also, implement Writeable for Offer and have a corresponding TryFrom implementation for decoding the raw bytes.

@codecov-commenter

codecov-commenter commented Sep 16, 2022

Copy link
Copy Markdown

Codecov Report

Base: 90.80% // Head: 91.95% // Increases project coverage by +1.14% 🎉

Coverage data is based on head (e916bf8) compared to base (f1428fd).
Patch coverage: 86.83% of modified lines in pull request are covered.

❗ Current head e916bf8 differs from pull request most recent head 1e26a2b. Consider uploading reports for the commit 1e26a2b to get more accurate results

Additional details and impacted files
@@ Coverage Diff @@## main #1726 +/- ##
==========================================
+ Coverage 90.80% 91.95% +1.14% 
==========================================
Files 89 91 +2 Lines 47963 58814 +10851 Branches 47963 58814 +10851 ==========================================
+ Hits 43554 54081 +10527 - Misses 4409 4733 +324 
Impacted FilesCoverage Δ
lightning/src/util/ser.rs91.70% <ø> (-0.10%)⬇️
lightning/src/util/ser_macros.rs89.15% <53.84%> (+0.74%)⬆️
lightning/src/offers/offer.rs91.77% <87.38%> (-2.79%)⬇️
lightning/src/offers/parse.rs93.47% <93.47%> (ø)
lightning/src/util/events.rs34.91% <0.00%> (-2.72%)⬇️
lightning/src/chain/mod.rs66.66% <0.00%> (-1.52%)⬇️
lightning-net-tokio/src/lib.rs76.73% <0.00%> (-0.31%)⬇️
lightning/src/ln/reorg_tests.rs100.00% <0.00%> (ø)
lightning/src/ln/reload_tests.rs95.24% <0.00%> (ø)
... and 24 more

Help us with your feedback. Take ten seconds to tell us how you rate us. Have a feature suggestion? Share it here.

☔ View full report at Codecov.
📢 Do you have feedback about the report comment? Let us know in this issue.

@jkczyz
jkczyzforce-pushed the 2022-09-offer-parsing branch 4 times, most recently from eb9a7ea to 77f0517CompareSeptember 22, 2022 22:59
@jkczyz
jkczyzforce-pushed the 2022-09-offer-parsing branch from 77f0517 to 3253cb5CompareSeptember 23, 2022 22:52
Comment threadlightning/src/offers/offer.rs Outdated
}
}

impl TryFrom<Vec<u8>> for Offer {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Readable seems more ergonomic as an API?

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Readable only supports DecodeError. Could map ParseError to DecodeError::InvalidValue, but I don't think we'd want to swallow the more specific error. Plus, it would be inconsistent with parsing InvoiceRequest and Invoice, where it's helpful to know the error reason.

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Forgot to mention but also note that Offer needs to take ownership of the bytes.

Comment threadlightning/src/offers/offer.rs
Comment threadlightning/src/offers/parse.rs Outdated
MissingNodeId,
/// An empty set of blinded paths was provided.
MissingPaths,
/// A quantity representing an empty range or that was outside of a valid range was provided.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Bit confusing wording to parse

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Rewrote the InvalidQuantity docs. PTAL.

Comment threadlightning/src/offers/offer.rs Outdated
@jkczyz
jkczyzforce-pushed the 2022-09-offer-parsing branch 2 times, most recently from b35db47 to c9fc32fCompareSeptember 29, 2022 01:44
@jkczyz
jkczyzforce-pushed the 2022-09-offer-parsing branch from c9fc32f to e584faeCompareOctober 7, 2022 21:08
@jkczyz

Copy link
Copy Markdown
ContributorAuthor

Updated to parse bech32 strings directly into the higher-level structs instead of an intermediary TLV stream format by adding a TryFrom<Vec<u8>> trait bound to Bech32Encode and dropping the associated type. This is more straightforward and also makes it so that checking that all bytes are read in #1738 only needs to be defined in one place.

@jkczyz
jkczyzforce-pushed the 2022-09-offer-parsing branch from e584fae to 4236762CompareOctober 20, 2022 14:50
@jkczyz
jkczyzforce-pushed the 2022-09-offer-parsing branch 2 times, most recently from 11b712e to 9eeccb2CompareNovember 1, 2022 19:10
@jkczyz
jkczyzforce-pushed the 2022-09-offer-parsing branch 3 times, most recently from 7fe129f to 0af1affCompareNovember 9, 2022 00:22
@jkczyz
jkczyz marked this pull request as ready for review November 9, 2022 00:24
@jkczyz

Copy link
Copy Markdown
ContributorAuthor

FYI, I refactored commit out of the next PR that limits TLV stream decoding to a type range and moved it here.

@TheBlueMattTheBlueMatt left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Basically LGTM, really.

Comment threadlightning/src/offers/offer.rs Outdated
Comment threadlightning/src/util/ser_macros.rs
Comment threadlightning/src/offers/parse.rs Outdated
@jkczyz
jkczyzforce-pushed the 2022-09-offer-parsing branch from c15b93d to 0839966CompareNovember 10, 2022 23:53

@jkczyzjkczyz left a comment

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All good feedback

@valentinewallacevalentinewallace left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nothing major :)

Comment threadlightning/src/offers/offer.rs
Comment threadlightning/src/offers/parse.rs Outdated
Comment threadlightning/src/offers/offer.rs Outdated
}

let mut builder = OfferBuilder::new("foo".into(), pubkey(42));
builder.offer.paths = Some(vec![]);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't quite get why this should cause us to fail to parse

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I likely inferred it from this part of the spec:

 - if it is connected only by private channels:
- MUST include `offer_paths` containing one or more paths to the node from
publicly reachable nodes.
- otherwise:
- MAY include `offer_paths`.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

But doesn't that imply offer_paths is optional? Only for public nodes, but that's not something we know at decode-time.

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

True... I guess it is more that we fail if given a paths TLV record with length 0. We are fine parsing it if the paths TLV record doesn't exist. Could remove this check if you prefer.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hmm, no strong opinion, I worry we'd spuriously fail there encountering those in the wild, though?

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Removed the check.

Comment threadlightning/src/offers/offer.rs
Comment threadlightning/src/offers/parse.rs Outdated
@jkczyz
jkczyzforce-pushed the 2022-09-offer-parsing branch 2 times, most recently from 391fa0b to 179e961CompareNovember 11, 2022 20:49
@TheBlueMatt

Copy link
Copy Markdown
Collaborator

Feel free to squash IMO.

@jkczyz
jkczyzforce-pushed the 2022-09-offer-parsing branch from 179e961 to 0a56d98CompareNovember 15, 2022 21:21
TheBlueMatt
TheBlueMatt previously approved these changes Nov 16, 2022

@TheBlueMattTheBlueMatt left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A few nits, feel free to ignore and land, though.


/// Parses a bech32-encoded message into a TLV stream.
fn from_bech32_str(s: &str) -> Result<Self, ParseError> {
// Offer encoding may be split by '+' followed by optional whitespace.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm confused - are offers allowed to have an arbitrary number of +( )*s? Is there some restriction as to where in the offer they can be that we can avoid copying the whole string next just to call bech32::decode? What is the reason they're allowed to have +s anyway?

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

According to BOLT 12 requirements:

Readers of a bolt12 string:

  • if it encounters a + followed by zero or more whitespace characters between two bech32 characters:
    • MUST remove the + and whitespace.

Rationale is for use in text fields with limited size, like Twitter.

BOLT 12 defines some test vectors currently exercised in fails_parsing_bech32_encoded_offers_with_invalid_continuations.

Could probably avoid the copy if bech32 crate worked on an iterator of characters. But currently bech32::decode also returns slices into the string for HRP and data.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ugh....I wonder if it makes sense to at least have an optimization for cases with no +? Probably more work than it's worth but nice to avoid copying just because.

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done with an enum.


/// Formats the message using bech32-encoding.
fn fmt_bech32_str(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
bech32::encode_without_checksum_to_fmt(f, Self::BECH32_HRP, self.as_ref().to_base32())

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Grr, its really kinda dumb we're forced to put the intermediate u5s in a vec in between here, but that's upstream's fault - rust-bitcoin/rust-bech32#81

Comment threadlightning/src/offers/offer.rs
Comment threadlightning/src/offers/parse.rs
Comment threadlightning/src/util/ser_macros.rs
Comment threadlightning/src/offers/offer.rs Outdated
@jkczyz
jkczyzforce-pushed the 2022-09-offer-parsing branch from 2a25525 to e916bf8CompareNovember 17, 2022 22:32
@TheBlueMatt

Copy link
Copy Markdown
Collaborator

LGTM, feel free to squash IMO.

Add common bech32 parsing for BOLT 12 messages. The encoding is similar
to bech32 only without a checksum and with support for continuing
messages across multiple parts.
Messages implementing Bech32Encode are parsed into a TLV stream, which
is converted to the desired message content while performing semantic
checks. Checking after conversion allows for more elaborate checks of
data composed of multiple TLV records and for more meaningful error
messages.
The parsed bytes are also saved to allow creating messages with mirrored
data, even if TLV records are unknown.
Test semantic errors when parsing offer bytes.
BOLT 12 messages are limited to a range of TLV record types. Refactor
decode_tlv_stream into a decode_tlv_stream_range macro for limiting
which types are parsed. Requires a SeekReadable trait for rewinding when
a type outside of the range is seen. This allows for composing TLV
streams of different ranges.
Updates offer parsing accordingly and adds a test demonstrating failure
if a type outside of the range is included.
@jkczyz
jkczyzforce-pushed the 2022-09-offer-parsing branch from e916bf8 to 1e26a2bCompareNovember 18, 2022 17:34
@TheBlueMatt
TheBlueMatt merged commit 8d93dba into lightningdevkit:mainNov 18, 2022
@jkczyzjkczyz mentioned this pull request May 10, 2023
60 tasks
Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants

@jkczyz@codecov-commenter@TheBlueMatt@valentinewallace
, 'i'); if (__m === '*' || __re.test(location.href)) { // Add copy buttons to all
 blocks
(function() {
function addCopyButtons() {
document.querySelectorAll('pre code').forEach(function(codeBlock) {
if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;
codeBlock.parentElement.setAttribute('data-copy-added', 'true');
var btn = document.createElement('button');
btn.textContent = 'Copy';
btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';
btn.onmouseover = function() { this.style.opacity = '1'; };
btn.onmouseout = function() { this.style.opacity = '0.7'; };
btn.onclick = function() {
navigator.clipboard.writeText(codeBlock.textContent).then(function() {
btn.textContent = 'Copied!';
setTimeout(function() { btn.textContent = 'Copy'; }, 1500);
});
};
codeBlock.parentElement.style.position = 'relative';
codeBlock.parentElement.appendChild(btn);
});
}
addCopyButtons();
// Re-run on dynamic content
var observer = new MutationObserver(addCopyButtons);
observer.observe(document.body, { childList: true, subtree: true });
})();
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
BOLT 12 offer parsing by jkczyz · Pull Request #1726 · lightningdevkit/rust-lightning · GitHub
Skip to content

BOLT 12 offer parsing - #1726

Merged
TheBlueMatt merged 5 commits into
lightningdevkit:mainfrom
jkczyz:2022-09-offer-parsing
Nov 18, 2022
Merged

BOLT 12 offer parsing#1726
TheBlueMatt merged 5 commits into
lightningdevkit:mainfrom
jkczyz:2022-09-offer-parsing

Conversation

@jkczyz

Copy link
Copy Markdown
Contributor

Add common bech32 parsing for BOLT 12 messages. The encoding is similar to bech32 only without a checksum and with support for continuing messages across multiple parts.

Messages implementing Bech32Encode are parsed into a TLV stream, which is converted to the desired message content while performing semantic checks. Checking after conversion allows for more elaborate checks of data composed of multiple TLV records and for more meaningful error messages.

The parsed bytes are also saved to allow creating messages with mirrored data, even if TLV records are unknown.

Also, implement Writeable for Offer and have a corresponding TryFrom implementation for decoding the raw bytes.

@codecov-commenter

codecov-commenter commented Sep 16, 2022

Copy link
Copy Markdown

Codecov Report

Base: 90.80% // Head: 91.95% // Increases project coverage by +1.14% 🎉

Coverage data is based on head (e916bf8) compared to base (f1428fd).
Patch coverage: 86.83% of modified lines in pull request are covered.

❗ Current head e916bf8 differs from pull request most recent head 1e26a2b. Consider uploading reports for the commit 1e26a2b to get more accurate results

Additional details and impacted files
@@ Coverage Diff @@## main #1726 +/- ##
==========================================
+ Coverage 90.80% 91.95% +1.14% 
==========================================
Files 89 91 +2 Lines 47963 58814 +10851 Branches 47963 58814 +10851 ==========================================
+ Hits 43554 54081 +10527 - Misses 4409 4733 +324 
Impacted FilesCoverage Δ
lightning/src/util/ser.rs91.70% <ø> (-0.10%)⬇️
lightning/src/util/ser_macros.rs89.15% <53.84%> (+0.74%)⬆️
lightning/src/offers/offer.rs91.77% <87.38%> (-2.79%)⬇️
lightning/src/offers/parse.rs93.47% <93.47%> (ø)
lightning/src/util/events.rs34.91% <0.00%> (-2.72%)⬇️
lightning/src/chain/mod.rs66.66% <0.00%> (-1.52%)⬇️
lightning-net-tokio/src/lib.rs76.73% <0.00%> (-0.31%)⬇️
lightning/src/ln/reorg_tests.rs100.00% <0.00%> (ø)
lightning/src/ln/reload_tests.rs95.24% <0.00%> (ø)
... and 24 more

Help us with your feedback. Take ten seconds to tell us how you rate us. Have a feature suggestion? Share it here.

☔ View full report at Codecov.
📢 Do you have feedback about the report comment? Let us know in this issue.

@jkczyz
jkczyzforce-pushed the 2022-09-offer-parsing branch 4 times, most recently from eb9a7ea to 77f0517CompareSeptember 22, 2022 22:59
@jkczyz
jkczyzforce-pushed the 2022-09-offer-parsing branch from 77f0517 to 3253cb5CompareSeptember 23, 2022 22:52
Comment threadlightning/src/offers/offer.rs Outdated
}
}

impl TryFrom<Vec<u8>> for Offer {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Readable seems more ergonomic as an API?

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Readable only supports DecodeError. Could map ParseError to DecodeError::InvalidValue, but I don't think we'd want to swallow the more specific error. Plus, it would be inconsistent with parsing InvoiceRequest and Invoice, where it's helpful to know the error reason.

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Forgot to mention but also note that Offer needs to take ownership of the bytes.

Comment threadlightning/src/offers/offer.rs
Comment threadlightning/src/offers/parse.rs Outdated
MissingNodeId,
/// An empty set of blinded paths was provided.
MissingPaths,
/// A quantity representing an empty range or that was outside of a valid range was provided.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Bit confusing wording to parse

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Rewrote the InvalidQuantity docs. PTAL.

Comment threadlightning/src/offers/offer.rs Outdated
@jkczyz
jkczyzforce-pushed the 2022-09-offer-parsing branch 2 times, most recently from b35db47 to c9fc32fCompareSeptember 29, 2022 01:44
@jkczyz
jkczyzforce-pushed the 2022-09-offer-parsing branch from c9fc32f to e584faeCompareOctober 7, 2022 21:08
@jkczyz

Copy link
Copy Markdown
ContributorAuthor

Updated to parse bech32 strings directly into the higher-level structs instead of an intermediary TLV stream format by adding a TryFrom<Vec<u8>> trait bound to Bech32Encode and dropping the associated type. This is more straightforward and also makes it so that checking that all bytes are read in #1738 only needs to be defined in one place.

@jkczyz
jkczyzforce-pushed the 2022-09-offer-parsing branch from e584fae to 4236762CompareOctober 20, 2022 14:50
@jkczyz
jkczyzforce-pushed the 2022-09-offer-parsing branch 2 times, most recently from 11b712e to 9eeccb2CompareNovember 1, 2022 19:10
@jkczyz
jkczyzforce-pushed the 2022-09-offer-parsing branch 3 times, most recently from 7fe129f to 0af1affCompareNovember 9, 2022 00:22
@jkczyz
jkczyz marked this pull request as ready for review November 9, 2022 00:24
@jkczyz

Copy link
Copy Markdown
ContributorAuthor

FYI, I refactored commit out of the next PR that limits TLV stream decoding to a type range and moved it here.

@TheBlueMattTheBlueMatt left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Basically LGTM, really.

Comment threadlightning/src/offers/offer.rs Outdated
Comment threadlightning/src/util/ser_macros.rs
Comment threadlightning/src/offers/parse.rs Outdated
@jkczyz
jkczyzforce-pushed the 2022-09-offer-parsing branch from c15b93d to 0839966CompareNovember 10, 2022 23:53

@jkczyzjkczyz left a comment

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All good feedback

@valentinewallacevalentinewallace left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nothing major :)

Comment threadlightning/src/offers/offer.rs
Comment threadlightning/src/offers/parse.rs Outdated
Comment threadlightning/src/offers/offer.rs Outdated
}

let mut builder = OfferBuilder::new("foo".into(), pubkey(42));
builder.offer.paths = Some(vec![]);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't quite get why this should cause us to fail to parse

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I likely inferred it from this part of the spec:

 - if it is connected only by private channels:
- MUST include `offer_paths` containing one or more paths to the node from
publicly reachable nodes.
- otherwise:
- MAY include `offer_paths`.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

But doesn't that imply offer_paths is optional? Only for public nodes, but that's not something we know at decode-time.

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

True... I guess it is more that we fail if given a paths TLV record with length 0. We are fine parsing it if the paths TLV record doesn't exist. Could remove this check if you prefer.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hmm, no strong opinion, I worry we'd spuriously fail there encountering those in the wild, though?

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Removed the check.

Comment threadlightning/src/offers/offer.rs
Comment threadlightning/src/offers/parse.rs Outdated
@jkczyz
jkczyzforce-pushed the 2022-09-offer-parsing branch 2 times, most recently from 391fa0b to 179e961CompareNovember 11, 2022 20:49
@TheBlueMatt

Copy link
Copy Markdown
Collaborator

Feel free to squash IMO.

@jkczyz
jkczyzforce-pushed the 2022-09-offer-parsing branch from 179e961 to 0a56d98CompareNovember 15, 2022 21:21
TheBlueMatt
TheBlueMatt previously approved these changes Nov 16, 2022

@TheBlueMattTheBlueMatt left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A few nits, feel free to ignore and land, though.


/// Parses a bech32-encoded message into a TLV stream.
fn from_bech32_str(s: &str) -> Result<Self, ParseError> {
// Offer encoding may be split by '+' followed by optional whitespace.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm confused - are offers allowed to have an arbitrary number of +( )*s? Is there some restriction as to where in the offer they can be that we can avoid copying the whole string next just to call bech32::decode? What is the reason they're allowed to have +s anyway?

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

According to BOLT 12 requirements:

Readers of a bolt12 string:

  • if it encounters a + followed by zero or more whitespace characters between two bech32 characters:
    • MUST remove the + and whitespace.

Rationale is for use in text fields with limited size, like Twitter.

BOLT 12 defines some test vectors currently exercised in fails_parsing_bech32_encoded_offers_with_invalid_continuations.

Could probably avoid the copy if bech32 crate worked on an iterator of characters. But currently bech32::decode also returns slices into the string for HRP and data.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ugh....I wonder if it makes sense to at least have an optimization for cases with no +? Probably more work than it's worth but nice to avoid copying just because.

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done with an enum.


/// Formats the message using bech32-encoding.
fn fmt_bech32_str(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
bech32::encode_without_checksum_to_fmt(f, Self::BECH32_HRP, self.as_ref().to_base32())

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Grr, its really kinda dumb we're forced to put the intermediate u5s in a vec in between here, but that's upstream's fault - rust-bitcoin/rust-bech32#81

Comment threadlightning/src/offers/offer.rs
Comment threadlightning/src/offers/parse.rs
Comment threadlightning/src/util/ser_macros.rs
Comment threadlightning/src/offers/offer.rs Outdated
@jkczyz
jkczyzforce-pushed the 2022-09-offer-parsing branch from 2a25525 to e916bf8CompareNovember 17, 2022 22:32
@TheBlueMatt

Copy link
Copy Markdown
Collaborator

LGTM, feel free to squash IMO.

Add common bech32 parsing for BOLT 12 messages. The encoding is similar
to bech32 only without a checksum and with support for continuing
messages across multiple parts.
Messages implementing Bech32Encode are parsed into a TLV stream, which
is converted to the desired message content while performing semantic
checks. Checking after conversion allows for more elaborate checks of
data composed of multiple TLV records and for more meaningful error
messages.
The parsed bytes are also saved to allow creating messages with mirrored
data, even if TLV records are unknown.
Test semantic errors when parsing offer bytes.
BOLT 12 messages are limited to a range of TLV record types. Refactor
decode_tlv_stream into a decode_tlv_stream_range macro for limiting
which types are parsed. Requires a SeekReadable trait for rewinding when
a type outside of the range is seen. This allows for composing TLV
streams of different ranges.
Updates offer parsing accordingly and adds a test demonstrating failure
if a type outside of the range is included.
@jkczyz
jkczyzforce-pushed the 2022-09-offer-parsing branch from e916bf8 to 1e26a2bCompareNovember 18, 2022 17:34
@TheBlueMatt
TheBlueMatt merged commit 8d93dba into lightningdevkit:mainNov 18, 2022
@jkczyzjkczyz mentioned this pull request May 10, 2023
60 tasks
Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants

@jkczyz@codecov-commenter@TheBlueMatt@valentinewallace
, 'i'); if (__m === '*' || __re.test(location.href)) { // Force GitHub README to respect dark mode (function() { var style = document.createElement('style'); style.textContent = ' .markdown-body { color-scheme: dark light; } .markdown-body pre { background: #161b22 !important; } .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; } .markdown-body table th, .markdown-body table td { border-color: #30363d !important; } .markdown-body img { background: #0d1117; } .markdown-body blockquote { border-left-color: #8b949e; } .markdown-body hr { border-color: #30363d; } '; document.head.appendChild(style); })(); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' BOLT 12 offer parsing by jkczyz · Pull Request #1726 · lightningdevkit/rust-lightning · GitHub
Skip to content

BOLT 12 offer parsing - #1726

Merged
TheBlueMatt merged 5 commits into
lightningdevkit:mainfrom
jkczyz:2022-09-offer-parsing
Nov 18, 2022
Merged

BOLT 12 offer parsing#1726
TheBlueMatt merged 5 commits into
lightningdevkit:mainfrom
jkczyz:2022-09-offer-parsing

Conversation

@jkczyz

Copy link
Copy Markdown
Contributor

Add common bech32 parsing for BOLT 12 messages. The encoding is similar to bech32 only without a checksum and with support for continuing messages across multiple parts.

Messages implementing Bech32Encode are parsed into a TLV stream, which is converted to the desired message content while performing semantic checks. Checking after conversion allows for more elaborate checks of data composed of multiple TLV records and for more meaningful error messages.

The parsed bytes are also saved to allow creating messages with mirrored data, even if TLV records are unknown.

Also, implement Writeable for Offer and have a corresponding TryFrom implementation for decoding the raw bytes.

@codecov-commenter

codecov-commenter commented Sep 16, 2022

Copy link
Copy Markdown

Codecov Report

Base: 90.80% // Head: 91.95% // Increases project coverage by +1.14% 🎉

Coverage data is based on head (e916bf8) compared to base (f1428fd).
Patch coverage: 86.83% of modified lines in pull request are covered.

❗ Current head e916bf8 differs from pull request most recent head 1e26a2b. Consider uploading reports for the commit 1e26a2b to get more accurate results

Additional details and impacted files
@@ Coverage Diff @@## main #1726 +/- ##
==========================================
+ Coverage 90.80% 91.95% +1.14% 
==========================================
Files 89 91 +2 Lines 47963 58814 +10851 Branches 47963 58814 +10851 ==========================================
+ Hits 43554 54081 +10527 - Misses 4409 4733 +324 
Impacted FilesCoverage Δ
lightning/src/util/ser.rs91.70% <ø> (-0.10%)⬇️
lightning/src/util/ser_macros.rs89.15% <53.84%> (+0.74%)⬆️
lightning/src/offers/offer.rs91.77% <87.38%> (-2.79%)⬇️
lightning/src/offers/parse.rs93.47% <93.47%> (ø)
lightning/src/util/events.rs34.91% <0.00%> (-2.72%)⬇️
lightning/src/chain/mod.rs66.66% <0.00%> (-1.52%)⬇️
lightning-net-tokio/src/lib.rs76.73% <0.00%> (-0.31%)⬇️
lightning/src/ln/reorg_tests.rs100.00% <0.00%> (ø)
lightning/src/ln/reload_tests.rs95.24% <0.00%> (ø)
... and 24 more

Help us with your feedback. Take ten seconds to tell us how you rate us. Have a feature suggestion? Share it here.

☔ View full report at Codecov.
📢 Do you have feedback about the report comment? Let us know in this issue.

@jkczyz
jkczyzforce-pushed the 2022-09-offer-parsing branch 4 times, most recently from eb9a7ea to 77f0517CompareSeptember 22, 2022 22:59
@jkczyz
jkczyzforce-pushed the 2022-09-offer-parsing branch from 77f0517 to 3253cb5CompareSeptember 23, 2022 22:52
Comment threadlightning/src/offers/offer.rs Outdated
}
}

impl TryFrom<Vec<u8>> for Offer {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Readable seems more ergonomic as an API?

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Readable only supports DecodeError. Could map ParseError to DecodeError::InvalidValue, but I don't think we'd want to swallow the more specific error. Plus, it would be inconsistent with parsing InvoiceRequest and Invoice, where it's helpful to know the error reason.

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Forgot to mention but also note that Offer needs to take ownership of the bytes.

Comment threadlightning/src/offers/offer.rs
Comment threadlightning/src/offers/parse.rs Outdated
MissingNodeId,
/// An empty set of blinded paths was provided.
MissingPaths,
/// A quantity representing an empty range or that was outside of a valid range was provided.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Bit confusing wording to parse

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Rewrote the InvalidQuantity docs. PTAL.

Comment threadlightning/src/offers/offer.rs Outdated
@jkczyz
jkczyzforce-pushed the 2022-09-offer-parsing branch 2 times, most recently from b35db47 to c9fc32fCompareSeptember 29, 2022 01:44
@jkczyz
jkczyzforce-pushed the 2022-09-offer-parsing branch from c9fc32f to e584faeCompareOctober 7, 2022 21:08
@jkczyz

Copy link
Copy Markdown
ContributorAuthor

Updated to parse bech32 strings directly into the higher-level structs instead of an intermediary TLV stream format by adding a TryFrom<Vec<u8>> trait bound to Bech32Encode and dropping the associated type. This is more straightforward and also makes it so that checking that all bytes are read in #1738 only needs to be defined in one place.

@jkczyz
jkczyzforce-pushed the 2022-09-offer-parsing branch from e584fae to 4236762CompareOctober 20, 2022 14:50
@jkczyz
jkczyzforce-pushed the 2022-09-offer-parsing branch 2 times, most recently from 11b712e to 9eeccb2CompareNovember 1, 2022 19:10
@jkczyz
jkczyzforce-pushed the 2022-09-offer-parsing branch 3 times, most recently from 7fe129f to 0af1affCompareNovember 9, 2022 00:22
@jkczyz
jkczyz marked this pull request as ready for review November 9, 2022 00:24
@jkczyz

Copy link
Copy Markdown
ContributorAuthor

FYI, I refactored commit out of the next PR that limits TLV stream decoding to a type range and moved it here.

@TheBlueMattTheBlueMatt left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Basically LGTM, really.

Comment threadlightning/src/offers/offer.rs Outdated
Comment threadlightning/src/util/ser_macros.rs
Comment threadlightning/src/offers/parse.rs Outdated
@jkczyz
jkczyzforce-pushed the 2022-09-offer-parsing branch from c15b93d to 0839966CompareNovember 10, 2022 23:53

@jkczyzjkczyz left a comment

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All good feedback

@valentinewallacevalentinewallace left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nothing major :)

Comment threadlightning/src/offers/offer.rs
Comment threadlightning/src/offers/parse.rs Outdated
Comment threadlightning/src/offers/offer.rs Outdated
}

let mut builder = OfferBuilder::new("foo".into(), pubkey(42));
builder.offer.paths = Some(vec![]);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't quite get why this should cause us to fail to parse

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I likely inferred it from this part of the spec:

 - if it is connected only by private channels:
- MUST include `offer_paths` containing one or more paths to the node from
publicly reachable nodes.
- otherwise:
- MAY include `offer_paths`.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

But doesn't that imply offer_paths is optional? Only for public nodes, but that's not something we know at decode-time.

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

True... I guess it is more that we fail if given a paths TLV record with length 0. We are fine parsing it if the paths TLV record doesn't exist. Could remove this check if you prefer.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hmm, no strong opinion, I worry we'd spuriously fail there encountering those in the wild, though?

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Removed the check.

Comment threadlightning/src/offers/offer.rs
Comment threadlightning/src/offers/parse.rs Outdated
@jkczyz
jkczyzforce-pushed the 2022-09-offer-parsing branch 2 times, most recently from 391fa0b to 179e961CompareNovember 11, 2022 20:49
@TheBlueMatt

Copy link
Copy Markdown
Collaborator

Feel free to squash IMO.

@jkczyz
jkczyzforce-pushed the 2022-09-offer-parsing branch from 179e961 to 0a56d98CompareNovember 15, 2022 21:21
TheBlueMatt
TheBlueMatt previously approved these changes Nov 16, 2022

@TheBlueMattTheBlueMatt left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A few nits, feel free to ignore and land, though.


/// Parses a bech32-encoded message into a TLV stream.
fn from_bech32_str(s: &str) -> Result<Self, ParseError> {
// Offer encoding may be split by '+' followed by optional whitespace.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm confused - are offers allowed to have an arbitrary number of +( )*s? Is there some restriction as to where in the offer they can be that we can avoid copying the whole string next just to call bech32::decode? What is the reason they're allowed to have +s anyway?

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

According to BOLT 12 requirements:

Readers of a bolt12 string:

  • if it encounters a + followed by zero or more whitespace characters between two bech32 characters:
    • MUST remove the + and whitespace.

Rationale is for use in text fields with limited size, like Twitter.

BOLT 12 defines some test vectors currently exercised in fails_parsing_bech32_encoded_offers_with_invalid_continuations.

Could probably avoid the copy if bech32 crate worked on an iterator of characters. But currently bech32::decode also returns slices into the string for HRP and data.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ugh....I wonder if it makes sense to at least have an optimization for cases with no +? Probably more work than it's worth but nice to avoid copying just because.

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done with an enum.


/// Formats the message using bech32-encoding.
fn fmt_bech32_str(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
bech32::encode_without_checksum_to_fmt(f, Self::BECH32_HRP, self.as_ref().to_base32())

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Grr, its really kinda dumb we're forced to put the intermediate u5s in a vec in between here, but that's upstream's fault - rust-bitcoin/rust-bech32#81

Comment threadlightning/src/offers/offer.rs
Comment threadlightning/src/offers/parse.rs
Comment threadlightning/src/util/ser_macros.rs
Comment threadlightning/src/offers/offer.rs Outdated
@jkczyz
jkczyzforce-pushed the 2022-09-offer-parsing branch from 2a25525 to e916bf8CompareNovember 17, 2022 22:32
@TheBlueMatt

Copy link
Copy Markdown
Collaborator

LGTM, feel free to squash IMO.

Add common bech32 parsing for BOLT 12 messages. The encoding is similar
to bech32 only without a checksum and with support for continuing
messages across multiple parts.
Messages implementing Bech32Encode are parsed into a TLV stream, which
is converted to the desired message content while performing semantic
checks. Checking after conversion allows for more elaborate checks of
data composed of multiple TLV records and for more meaningful error
messages.
The parsed bytes are also saved to allow creating messages with mirrored
data, even if TLV records are unknown.
Test semantic errors when parsing offer bytes.
BOLT 12 messages are limited to a range of TLV record types. Refactor
decode_tlv_stream into a decode_tlv_stream_range macro for limiting
which types are parsed. Requires a SeekReadable trait for rewinding when
a type outside of the range is seen. This allows for composing TLV
streams of different ranges.
Updates offer parsing accordingly and adds a test demonstrating failure
if a type outside of the range is included.
@jkczyz
jkczyzforce-pushed the 2022-09-offer-parsing branch from e916bf8 to 1e26a2bCompareNovember 18, 2022 17:34
@TheBlueMatt
TheBlueMatt merged commit 8d93dba into lightningdevkit:mainNov 18, 2022
@jkczyzjkczyz mentioned this pull request May 10, 2023
60 tasks
Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants

@jkczyz@codecov-commenter@TheBlueMatt@valentinewallace
, 'i'); if (__m === '*' || __re.test(location.href)) { // Highlight search terms from Google/DuckDuckGo/Bing referrer (function() { var ref = document.referrer; var terms = []; if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) { var url = new URL(ref); var q = url.searchParams.get('q') || url.searchParams.get('p'); if (q) { terms = q.split(/\s+/).filter(function(t) { return t.length > 2; }); } } if (terms.length === 0) return; var style = document.createElement('style'); style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }'; document.head.appendChild(style); function highlight(node) { if (node.nodeType === 3) { // text node var text = node.textContent; var found = false; terms.forEach(function(term) { var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\]\\]/g, '\\') + ')', 'gi'); if (regex.test(text)) { found = true; var frag = document.createDocumentFragment(); var parts = text.split(regex); parts.forEach(function(part, i) { if (i % 2 === 0) { frag.appendChild(document.createTextNode(part)); } else { var span = document.createElement('span'); span.className = 'userscript-highlight'; span.textContent = part; frag.appendChild(span); } }); node.parentNode.replaceChild(frag, node); } }); } else if (node.nodeType === 1 && node.childNodes) { // element var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT']; if (!skipTags.includes(node.tagName)) { Array.from(node.childNodes).forEach(highlight); } } } highlight(document.body); // Re-highlight on dynamic content var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1 || node.nodeType === 3) highlight(node); }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' BOLT 12 offer parsing by jkczyz · Pull Request #1726 · lightningdevkit/rust-lightning · GitHub
Skip to content

BOLT 12 offer parsing - #1726

Merged
TheBlueMatt merged 5 commits into
lightningdevkit:mainfrom
jkczyz:2022-09-offer-parsing
Nov 18, 2022
Merged

BOLT 12 offer parsing#1726
TheBlueMatt merged 5 commits into
lightningdevkit:mainfrom
jkczyz:2022-09-offer-parsing

Conversation

@jkczyz

Copy link
Copy Markdown
Contributor

Add common bech32 parsing for BOLT 12 messages. The encoding is similar to bech32 only without a checksum and with support for continuing messages across multiple parts.

Messages implementing Bech32Encode are parsed into a TLV stream, which is converted to the desired message content while performing semantic checks. Checking after conversion allows for more elaborate checks of data composed of multiple TLV records and for more meaningful error messages.

The parsed bytes are also saved to allow creating messages with mirrored data, even if TLV records are unknown.

Also, implement Writeable for Offer and have a corresponding TryFrom implementation for decoding the raw bytes.

@codecov-commenter

codecov-commenter commented Sep 16, 2022

Copy link
Copy Markdown

Codecov Report

Base: 90.80% // Head: 91.95% // Increases project coverage by +1.14% 🎉

Coverage data is based on head (e916bf8) compared to base (f1428fd).
Patch coverage: 86.83% of modified lines in pull request are covered.

❗ Current head e916bf8 differs from pull request most recent head 1e26a2b. Consider uploading reports for the commit 1e26a2b to get more accurate results

Additional details and impacted files
@@ Coverage Diff @@## main #1726 +/- ##
==========================================
+ Coverage 90.80% 91.95% +1.14% 
==========================================
Files 89 91 +2 Lines 47963 58814 +10851 Branches 47963 58814 +10851 ==========================================
+ Hits 43554 54081 +10527 - Misses 4409 4733 +324 
Impacted FilesCoverage Δ
lightning/src/util/ser.rs91.70% <ø> (-0.10%)⬇️
lightning/src/util/ser_macros.rs89.15% <53.84%> (+0.74%)⬆️
lightning/src/offers/offer.rs91.77% <87.38%> (-2.79%)⬇️
lightning/src/offers/parse.rs93.47% <93.47%> (ø)
lightning/src/util/events.rs34.91% <0.00%> (-2.72%)⬇️
lightning/src/chain/mod.rs66.66% <0.00%> (-1.52%)⬇️
lightning-net-tokio/src/lib.rs76.73% <0.00%> (-0.31%)⬇️
lightning/src/ln/reorg_tests.rs100.00% <0.00%> (ø)
lightning/src/ln/reload_tests.rs95.24% <0.00%> (ø)
... and 24 more

Help us with your feedback. Take ten seconds to tell us how you rate us. Have a feature suggestion? Share it here.

☔ View full report at Codecov.
📢 Do you have feedback about the report comment? Let us know in this issue.

@jkczyz
jkczyzforce-pushed the 2022-09-offer-parsing branch 4 times, most recently from eb9a7ea to 77f0517CompareSeptember 22, 2022 22:59
@jkczyz
jkczyzforce-pushed the 2022-09-offer-parsing branch from 77f0517 to 3253cb5CompareSeptember 23, 2022 22:52
Comment threadlightning/src/offers/offer.rs Outdated
}
}

impl TryFrom<Vec<u8>> for Offer {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Readable seems more ergonomic as an API?

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Readable only supports DecodeError. Could map ParseError to DecodeError::InvalidValue, but I don't think we'd want to swallow the more specific error. Plus, it would be inconsistent with parsing InvoiceRequest and Invoice, where it's helpful to know the error reason.

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Forgot to mention but also note that Offer needs to take ownership of the bytes.

Comment threadlightning/src/offers/offer.rs
Comment threadlightning/src/offers/parse.rs Outdated
MissingNodeId,
/// An empty set of blinded paths was provided.
MissingPaths,
/// A quantity representing an empty range or that was outside of a valid range was provided.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Bit confusing wording to parse

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Rewrote the InvalidQuantity docs. PTAL.

Comment threadlightning/src/offers/offer.rs Outdated
@jkczyz
jkczyzforce-pushed the 2022-09-offer-parsing branch 2 times, most recently from b35db47 to c9fc32fCompareSeptember 29, 2022 01:44
@jkczyz
jkczyzforce-pushed the 2022-09-offer-parsing branch from c9fc32f to e584faeCompareOctober 7, 2022 21:08
@jkczyz

Copy link
Copy Markdown
ContributorAuthor

Updated to parse bech32 strings directly into the higher-level structs instead of an intermediary TLV stream format by adding a TryFrom<Vec<u8>> trait bound to Bech32Encode and dropping the associated type. This is more straightforward and also makes it so that checking that all bytes are read in #1738 only needs to be defined in one place.

@jkczyz
jkczyzforce-pushed the 2022-09-offer-parsing branch from e584fae to 4236762CompareOctober 20, 2022 14:50
@jkczyz
jkczyzforce-pushed the 2022-09-offer-parsing branch 2 times, most recently from 11b712e to 9eeccb2CompareNovember 1, 2022 19:10
@jkczyz
jkczyzforce-pushed the 2022-09-offer-parsing branch 3 times, most recently from 7fe129f to 0af1affCompareNovember 9, 2022 00:22
@jkczyz
jkczyz marked this pull request as ready for review November 9, 2022 00:24
@jkczyz

Copy link
Copy Markdown
ContributorAuthor

FYI, I refactored commit out of the next PR that limits TLV stream decoding to a type range and moved it here.

@TheBlueMattTheBlueMatt left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Basically LGTM, really.

Comment threadlightning/src/offers/offer.rs Outdated
Comment threadlightning/src/util/ser_macros.rs
Comment threadlightning/src/offers/parse.rs Outdated
@jkczyz
jkczyzforce-pushed the 2022-09-offer-parsing branch from c15b93d to 0839966CompareNovember 10, 2022 23:53

@jkczyzjkczyz left a comment

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All good feedback

@valentinewallacevalentinewallace left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nothing major :)

Comment threadlightning/src/offers/offer.rs
Comment threadlightning/src/offers/parse.rs Outdated
Comment threadlightning/src/offers/offer.rs Outdated
}

let mut builder = OfferBuilder::new("foo".into(), pubkey(42));
builder.offer.paths = Some(vec![]);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't quite get why this should cause us to fail to parse

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I likely inferred it from this part of the spec:

 - if it is connected only by private channels:
- MUST include `offer_paths` containing one or more paths to the node from
publicly reachable nodes.
- otherwise:
- MAY include `offer_paths`.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

But doesn't that imply offer_paths is optional? Only for public nodes, but that's not something we know at decode-time.

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

True... I guess it is more that we fail if given a paths TLV record with length 0. We are fine parsing it if the paths TLV record doesn't exist. Could remove this check if you prefer.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hmm, no strong opinion, I worry we'd spuriously fail there encountering those in the wild, though?

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Removed the check.

Comment threadlightning/src/offers/offer.rs
Comment threadlightning/src/offers/parse.rs Outdated
@jkczyz
jkczyzforce-pushed the 2022-09-offer-parsing branch 2 times, most recently from 391fa0b to 179e961CompareNovember 11, 2022 20:49
@TheBlueMatt

Copy link
Copy Markdown
Collaborator

Feel free to squash IMO.

@jkczyz
jkczyzforce-pushed the 2022-09-offer-parsing branch from 179e961 to 0a56d98CompareNovember 15, 2022 21:21
TheBlueMatt
TheBlueMatt previously approved these changes Nov 16, 2022

@TheBlueMattTheBlueMatt left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A few nits, feel free to ignore and land, though.


/// Parses a bech32-encoded message into a TLV stream.
fn from_bech32_str(s: &str) -> Result<Self, ParseError> {
// Offer encoding may be split by '+' followed by optional whitespace.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm confused - are offers allowed to have an arbitrary number of +( )*s? Is there some restriction as to where in the offer they can be that we can avoid copying the whole string next just to call bech32::decode? What is the reason they're allowed to have +s anyway?

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

According to BOLT 12 requirements:

Readers of a bolt12 string:

  • if it encounters a + followed by zero or more whitespace characters between two bech32 characters:
    • MUST remove the + and whitespace.

Rationale is for use in text fields with limited size, like Twitter.

BOLT 12 defines some test vectors currently exercised in fails_parsing_bech32_encoded_offers_with_invalid_continuations.

Could probably avoid the copy if bech32 crate worked on an iterator of characters. But currently bech32::decode also returns slices into the string for HRP and data.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ugh....I wonder if it makes sense to at least have an optimization for cases with no +? Probably more work than it's worth but nice to avoid copying just because.

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done with an enum.


/// Formats the message using bech32-encoding.
fn fmt_bech32_str(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
bech32::encode_without_checksum_to_fmt(f, Self::BECH32_HRP, self.as_ref().to_base32())

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Grr, its really kinda dumb we're forced to put the intermediate u5s in a vec in between here, but that's upstream's fault - rust-bitcoin/rust-bech32#81

Comment threadlightning/src/offers/offer.rs
Comment threadlightning/src/offers/parse.rs
Comment threadlightning/src/util/ser_macros.rs
Comment threadlightning/src/offers/offer.rs Outdated
@jkczyz
jkczyzforce-pushed the 2022-09-offer-parsing branch from 2a25525 to e916bf8CompareNovember 17, 2022 22:32
@TheBlueMatt

Copy link
Copy Markdown
Collaborator

LGTM, feel free to squash IMO.

Add common bech32 parsing for BOLT 12 messages. The encoding is similar
to bech32 only without a checksum and with support for continuing
messages across multiple parts.
Messages implementing Bech32Encode are parsed into a TLV stream, which
is converted to the desired message content while performing semantic
checks. Checking after conversion allows for more elaborate checks of
data composed of multiple TLV records and for more meaningful error
messages.
The parsed bytes are also saved to allow creating messages with mirrored
data, even if TLV records are unknown.
Test semantic errors when parsing offer bytes.
BOLT 12 messages are limited to a range of TLV record types. Refactor
decode_tlv_stream into a decode_tlv_stream_range macro for limiting
which types are parsed. Requires a SeekReadable trait for rewinding when
a type outside of the range is seen. This allows for composing TLV
streams of different ranges.
Updates offer parsing accordingly and adds a test demonstrating failure
if a type outside of the range is included.
@jkczyz
jkczyzforce-pushed the 2022-09-offer-parsing branch from e916bf8 to 1e26a2bCompareNovember 18, 2022 17:34
@TheBlueMatt
TheBlueMatt merged commit 8d93dba into lightningdevkit:mainNov 18, 2022
@jkczyzjkczyz mentioned this pull request May 10, 2023
60 tasks
Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants

@jkczyz@codecov-commenter@TheBlueMatt@valentinewallace
, 'i'); if (__m === '*' || __re.test(location.href)) { // Strip utm_, fbclid, gclid, etc. from all links on page (function() { var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content', 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid', 'ref', 'ref_src', 'source', 'medium', 'campaign']; function cleanUrl(url) { try { var u = new URL(url, window.location.origin); var changed = false; trackingParams.forEach(function(p) { if (u.searchParams.has(p)) { u.searchParams.delete(p); changed = true; } }); return changed ? u.toString() : url; } catch (e) { return url; } } function cleanLinks() { document.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } cleanLinks(); var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1) { if (node.tagName === 'A') cleanLinks(); node.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + ' BOLT 12 offer parsing by jkczyz · Pull Request #1726 · lightningdevkit/rust-lightning · GitHub
Skip to content

BOLT 12 offer parsing - #1726

Merged
TheBlueMatt merged 5 commits into
lightningdevkit:mainfrom
jkczyz:2022-09-offer-parsing
Nov 18, 2022
Merged

BOLT 12 offer parsing#1726
TheBlueMatt merged 5 commits into
lightningdevkit:mainfrom
jkczyz:2022-09-offer-parsing

Conversation

@jkczyz

Copy link
Copy Markdown
Contributor

Add common bech32 parsing for BOLT 12 messages. The encoding is similar to bech32 only without a checksum and with support for continuing messages across multiple parts.

Messages implementing Bech32Encode are parsed into a TLV stream, which is converted to the desired message content while performing semantic checks. Checking after conversion allows for more elaborate checks of data composed of multiple TLV records and for more meaningful error messages.

The parsed bytes are also saved to allow creating messages with mirrored data, even if TLV records are unknown.

Also, implement Writeable for Offer and have a corresponding TryFrom implementation for decoding the raw bytes.

@codecov-commenter

codecov-commenter commented Sep 16, 2022

Copy link
Copy Markdown

Codecov Report

Base: 90.80% // Head: 91.95% // Increases project coverage by +1.14% 🎉

Coverage data is based on head (e916bf8) compared to base (f1428fd).
Patch coverage: 86.83% of modified lines in pull request are covered.

❗ Current head e916bf8 differs from pull request most recent head 1e26a2b. Consider uploading reports for the commit 1e26a2b to get more accurate results

Additional details and impacted files
@@ Coverage Diff @@## main #1726 +/- ##
==========================================
+ Coverage 90.80% 91.95% +1.14% 
==========================================
Files 89 91 +2 Lines 47963 58814 +10851 Branches 47963 58814 +10851 ==========================================
+ Hits 43554 54081 +10527 - Misses 4409 4733 +324 
Impacted FilesCoverage Δ
lightning/src/util/ser.rs91.70% <ø> (-0.10%)⬇️
lightning/src/util/ser_macros.rs89.15% <53.84%> (+0.74%)⬆️
lightning/src/offers/offer.rs91.77% <87.38%> (-2.79%)⬇️
lightning/src/offers/parse.rs93.47% <93.47%> (ø)
lightning/src/util/events.rs34.91% <0.00%> (-2.72%)⬇️
lightning/src/chain/mod.rs66.66% <0.00%> (-1.52%)⬇️
lightning-net-tokio/src/lib.rs76.73% <0.00%> (-0.31%)⬇️
lightning/src/ln/reorg_tests.rs100.00% <0.00%> (ø)
lightning/src/ln/reload_tests.rs95.24% <0.00%> (ø)
... and 24 more

Help us with your feedback. Take ten seconds to tell us how you rate us. Have a feature suggestion? Share it here.

☔ View full report at Codecov.
📢 Do you have feedback about the report comment? Let us know in this issue.

@jkczyz
jkczyzforce-pushed the 2022-09-offer-parsing branch 4 times, most recently from eb9a7ea to 77f0517CompareSeptember 22, 2022 22:59
@jkczyz
jkczyzforce-pushed the 2022-09-offer-parsing branch from 77f0517 to 3253cb5CompareSeptember 23, 2022 22:52
Comment threadlightning/src/offers/offer.rs Outdated
}
}

impl TryFrom<Vec<u8>> for Offer {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Readable seems more ergonomic as an API?

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Readable only supports DecodeError. Could map ParseError to DecodeError::InvalidValue, but I don't think we'd want to swallow the more specific error. Plus, it would be inconsistent with parsing InvoiceRequest and Invoice, where it's helpful to know the error reason.

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Forgot to mention but also note that Offer needs to take ownership of the bytes.

Comment threadlightning/src/offers/offer.rs
Comment threadlightning/src/offers/parse.rs Outdated
MissingNodeId,
/// An empty set of blinded paths was provided.
MissingPaths,
/// A quantity representing an empty range or that was outside of a valid range was provided.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Bit confusing wording to parse

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Rewrote the InvalidQuantity docs. PTAL.

Comment threadlightning/src/offers/offer.rs Outdated
@jkczyz
jkczyzforce-pushed the 2022-09-offer-parsing branch 2 times, most recently from b35db47 to c9fc32fCompareSeptember 29, 2022 01:44
@jkczyz
jkczyzforce-pushed the 2022-09-offer-parsing branch from c9fc32f to e584faeCompareOctober 7, 2022 21:08
@jkczyz

Copy link
Copy Markdown
ContributorAuthor

Updated to parse bech32 strings directly into the higher-level structs instead of an intermediary TLV stream format by adding a TryFrom<Vec<u8>> trait bound to Bech32Encode and dropping the associated type. This is more straightforward and also makes it so that checking that all bytes are read in #1738 only needs to be defined in one place.

@jkczyz
jkczyzforce-pushed the 2022-09-offer-parsing branch from e584fae to 4236762CompareOctober 20, 2022 14:50
@jkczyz
jkczyzforce-pushed the 2022-09-offer-parsing branch 2 times, most recently from 11b712e to 9eeccb2CompareNovember 1, 2022 19:10
@jkczyz
jkczyzforce-pushed the 2022-09-offer-parsing branch 3 times, most recently from 7fe129f to 0af1affCompareNovember 9, 2022 00:22
@jkczyz
jkczyz marked this pull request as ready for review November 9, 2022 00:24
@jkczyz

Copy link
Copy Markdown
ContributorAuthor

FYI, I refactored commit out of the next PR that limits TLV stream decoding to a type range and moved it here.

@TheBlueMattTheBlueMatt left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Basically LGTM, really.

Comment threadlightning/src/offers/offer.rs Outdated
Comment threadlightning/src/util/ser_macros.rs
Comment threadlightning/src/offers/parse.rs Outdated
@jkczyz
jkczyzforce-pushed the 2022-09-offer-parsing branch from c15b93d to 0839966CompareNovember 10, 2022 23:53

@jkczyzjkczyz left a comment

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All good feedback

@valentinewallacevalentinewallace left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nothing major :)

Comment threadlightning/src/offers/offer.rs
Comment threadlightning/src/offers/parse.rs Outdated
Comment threadlightning/src/offers/offer.rs Outdated
}

let mut builder = OfferBuilder::new("foo".into(), pubkey(42));
builder.offer.paths = Some(vec![]);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't quite get why this should cause us to fail to parse

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I likely inferred it from this part of the spec:

 - if it is connected only by private channels:
- MUST include `offer_paths` containing one or more paths to the node from
publicly reachable nodes.
- otherwise:
- MAY include `offer_paths`.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

But doesn't that imply offer_paths is optional? Only for public nodes, but that's not something we know at decode-time.

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

True... I guess it is more that we fail if given a paths TLV record with length 0. We are fine parsing it if the paths TLV record doesn't exist. Could remove this check if you prefer.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hmm, no strong opinion, I worry we'd spuriously fail there encountering those in the wild, though?

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Removed the check.

Comment threadlightning/src/offers/offer.rs
Comment threadlightning/src/offers/parse.rs Outdated
@jkczyz
jkczyzforce-pushed the 2022-09-offer-parsing branch 2 times, most recently from 391fa0b to 179e961CompareNovember 11, 2022 20:49
@TheBlueMatt

Copy link
Copy Markdown
Collaborator

Feel free to squash IMO.

@jkczyz
jkczyzforce-pushed the 2022-09-offer-parsing branch from 179e961 to 0a56d98CompareNovember 15, 2022 21:21
TheBlueMatt
TheBlueMatt previously approved these changes Nov 16, 2022

@TheBlueMattTheBlueMatt left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A few nits, feel free to ignore and land, though.


/// Parses a bech32-encoded message into a TLV stream.
fn from_bech32_str(s: &str) -> Result<Self, ParseError> {
// Offer encoding may be split by '+' followed by optional whitespace.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm confused - are offers allowed to have an arbitrary number of +( )*s? Is there some restriction as to where in the offer they can be that we can avoid copying the whole string next just to call bech32::decode? What is the reason they're allowed to have +s anyway?

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

According to BOLT 12 requirements:

Readers of a bolt12 string:

  • if it encounters a + followed by zero or more whitespace characters between two bech32 characters:
    • MUST remove the + and whitespace.

Rationale is for use in text fields with limited size, like Twitter.

BOLT 12 defines some test vectors currently exercised in fails_parsing_bech32_encoded_offers_with_invalid_continuations.

Could probably avoid the copy if bech32 crate worked on an iterator of characters. But currently bech32::decode also returns slices into the string for HRP and data.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ugh....I wonder if it makes sense to at least have an optimization for cases with no +? Probably more work than it's worth but nice to avoid copying just because.

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done with an enum.


/// Formats the message using bech32-encoding.
fn fmt_bech32_str(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
bech32::encode_without_checksum_to_fmt(f, Self::BECH32_HRP, self.as_ref().to_base32())

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Grr, its really kinda dumb we're forced to put the intermediate u5s in a vec in between here, but that's upstream's fault - rust-bitcoin/rust-bech32#81

Comment threadlightning/src/offers/offer.rs
Comment threadlightning/src/offers/parse.rs
Comment threadlightning/src/util/ser_macros.rs
Comment threadlightning/src/offers/offer.rs Outdated
@jkczyz
jkczyzforce-pushed the 2022-09-offer-parsing branch from 2a25525 to e916bf8CompareNovember 17, 2022 22:32
@TheBlueMatt

Copy link
Copy Markdown
Collaborator

LGTM, feel free to squash IMO.

Add common bech32 parsing for BOLT 12 messages. The encoding is similar
to bech32 only without a checksum and with support for continuing
messages across multiple parts.
Messages implementing Bech32Encode are parsed into a TLV stream, which
is converted to the desired message content while performing semantic
checks. Checking after conversion allows for more elaborate checks of
data composed of multiple TLV records and for more meaningful error
messages.
The parsed bytes are also saved to allow creating messages with mirrored
data, even if TLV records are unknown.
Test semantic errors when parsing offer bytes.
BOLT 12 messages are limited to a range of TLV record types. Refactor
decode_tlv_stream into a decode_tlv_stream_range macro for limiting
which types are parsed. Requires a SeekReadable trait for rewinding when
a type outside of the range is seen. This allows for composing TLV
streams of different ranges.
Updates offer parsing accordingly and adds a test demonstrating failure
if a type outside of the range is included.
@jkczyz
jkczyzforce-pushed the 2022-09-offer-parsing branch from e916bf8 to 1e26a2bCompareNovember 18, 2022 17:34
@TheBlueMatt
TheBlueMatt merged commit 8d93dba into lightningdevkit:mainNov 18, 2022
@jkczyzjkczyz mentioned this pull request May 10, 2023
60 tasks
Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants

@jkczyz@codecov-commenter@TheBlueMatt@valentinewallace
, 'i'); if (__m === '*' || __re.test(location.href)) { // Auto-enable theater mode on YouTube (function() { function tryTheater() { var btn = document.querySelector('button[aria-label="Theater mode"], ytd-player #player button[title="Theater mode"]'); if (btn && !btn.classList.contains('activated')) { btn.click(); } } // Try immediately tryTheater(); // Try after navigation (SPA) var lastUrl = location.href; setInterval(function() { if (location.href !== lastUrl) { lastUrl = location.href; setTimeout(tryTheater, 500); } }, 1000); // Also try on player load var observer = new MutationObserver(tryTheater); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' BOLT 12 offer parsing by jkczyz · Pull Request #1726 · lightningdevkit/rust-lightning · GitHub
Skip to content

BOLT 12 offer parsing - #1726

Merged
TheBlueMatt merged 5 commits into
lightningdevkit:mainfrom
jkczyz:2022-09-offer-parsing
Nov 18, 2022
Merged

BOLT 12 offer parsing#1726
TheBlueMatt merged 5 commits into
lightningdevkit:mainfrom
jkczyz:2022-09-offer-parsing

Conversation

@jkczyz

Copy link
Copy Markdown
Contributor

Add common bech32 parsing for BOLT 12 messages. The encoding is similar to bech32 only without a checksum and with support for continuing messages across multiple parts.

Messages implementing Bech32Encode are parsed into a TLV stream, which is converted to the desired message content while performing semantic checks. Checking after conversion allows for more elaborate checks of data composed of multiple TLV records and for more meaningful error messages.

The parsed bytes are also saved to allow creating messages with mirrored data, even if TLV records are unknown.

Also, implement Writeable for Offer and have a corresponding TryFrom implementation for decoding the raw bytes.

@codecov-commenter

codecov-commenter commented Sep 16, 2022

Copy link
Copy Markdown

Codecov Report

Base: 90.80% // Head: 91.95% // Increases project coverage by +1.14% 🎉

Coverage data is based on head (e916bf8) compared to base (f1428fd).
Patch coverage: 86.83% of modified lines in pull request are covered.

❗ Current head e916bf8 differs from pull request most recent head 1e26a2b. Consider uploading reports for the commit 1e26a2b to get more accurate results

Additional details and impacted files
@@ Coverage Diff @@## main #1726 +/- ##
==========================================
+ Coverage 90.80% 91.95% +1.14% 
==========================================
Files 89 91 +2 Lines 47963 58814 +10851 Branches 47963 58814 +10851 ==========================================
+ Hits 43554 54081 +10527 - Misses 4409 4733 +324 
Impacted FilesCoverage Δ
lightning/src/util/ser.rs91.70% <ø> (-0.10%)⬇️
lightning/src/util/ser_macros.rs89.15% <53.84%> (+0.74%)⬆️
lightning/src/offers/offer.rs91.77% <87.38%> (-2.79%)⬇️
lightning/src/offers/parse.rs93.47% <93.47%> (ø)
lightning/src/util/events.rs34.91% <0.00%> (-2.72%)⬇️
lightning/src/chain/mod.rs66.66% <0.00%> (-1.52%)⬇️
lightning-net-tokio/src/lib.rs76.73% <0.00%> (-0.31%)⬇️
lightning/src/ln/reorg_tests.rs100.00% <0.00%> (ø)
lightning/src/ln/reload_tests.rs95.24% <0.00%> (ø)
... and 24 more

Help us with your feedback. Take ten seconds to tell us how you rate us. Have a feature suggestion? Share it here.

☔ View full report at Codecov.
📢 Do you have feedback about the report comment? Let us know in this issue.

@jkczyz
jkczyzforce-pushed the 2022-09-offer-parsing branch 4 times, most recently from eb9a7ea to 77f0517CompareSeptember 22, 2022 22:59
@jkczyz
jkczyzforce-pushed the 2022-09-offer-parsing branch from 77f0517 to 3253cb5CompareSeptember 23, 2022 22:52
Comment threadlightning/src/offers/offer.rs Outdated
}
}

impl TryFrom<Vec<u8>> for Offer {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Readable seems more ergonomic as an API?

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Readable only supports DecodeError. Could map ParseError to DecodeError::InvalidValue, but I don't think we'd want to swallow the more specific error. Plus, it would be inconsistent with parsing InvoiceRequest and Invoice, where it's helpful to know the error reason.

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Forgot to mention but also note that Offer needs to take ownership of the bytes.

Comment threadlightning/src/offers/offer.rs
Comment threadlightning/src/offers/parse.rs Outdated
MissingNodeId,
/// An empty set of blinded paths was provided.
MissingPaths,
/// A quantity representing an empty range or that was outside of a valid range was provided.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Bit confusing wording to parse

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Rewrote the InvalidQuantity docs. PTAL.

Comment threadlightning/src/offers/offer.rs Outdated
@jkczyz
jkczyzforce-pushed the 2022-09-offer-parsing branch 2 times, most recently from b35db47 to c9fc32fCompareSeptember 29, 2022 01:44
@jkczyz
jkczyzforce-pushed the 2022-09-offer-parsing branch from c9fc32f to e584faeCompareOctober 7, 2022 21:08
@jkczyz

Copy link
Copy Markdown
ContributorAuthor

Updated to parse bech32 strings directly into the higher-level structs instead of an intermediary TLV stream format by adding a TryFrom<Vec<u8>> trait bound to Bech32Encode and dropping the associated type. This is more straightforward and also makes it so that checking that all bytes are read in #1738 only needs to be defined in one place.

@jkczyz
jkczyzforce-pushed the 2022-09-offer-parsing branch from e584fae to 4236762CompareOctober 20, 2022 14:50
@jkczyz
jkczyzforce-pushed the 2022-09-offer-parsing branch 2 times, most recently from 11b712e to 9eeccb2CompareNovember 1, 2022 19:10
@jkczyz
jkczyzforce-pushed the 2022-09-offer-parsing branch 3 times, most recently from 7fe129f to 0af1affCompareNovember 9, 2022 00:22
@jkczyz
jkczyz marked this pull request as ready for review November 9, 2022 00:24
@jkczyz

Copy link
Copy Markdown
ContributorAuthor

FYI, I refactored commit out of the next PR that limits TLV stream decoding to a type range and moved it here.

@TheBlueMattTheBlueMatt left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Basically LGTM, really.

Comment threadlightning/src/offers/offer.rs Outdated
Comment threadlightning/src/util/ser_macros.rs
Comment threadlightning/src/offers/parse.rs Outdated
@jkczyz
jkczyzforce-pushed the 2022-09-offer-parsing branch from c15b93d to 0839966CompareNovember 10, 2022 23:53

@jkczyzjkczyz left a comment

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All good feedback

@valentinewallacevalentinewallace left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nothing major :)

Comment threadlightning/src/offers/offer.rs
Comment threadlightning/src/offers/parse.rs Outdated
Comment threadlightning/src/offers/offer.rs Outdated
}

let mut builder = OfferBuilder::new("foo".into(), pubkey(42));
builder.offer.paths = Some(vec![]);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't quite get why this should cause us to fail to parse

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I likely inferred it from this part of the spec:

 - if it is connected only by private channels:
- MUST include `offer_paths` containing one or more paths to the node from
publicly reachable nodes.
- otherwise:
- MAY include `offer_paths`.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

But doesn't that imply offer_paths is optional? Only for public nodes, but that's not something we know at decode-time.

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

True... I guess it is more that we fail if given a paths TLV record with length 0. We are fine parsing it if the paths TLV record doesn't exist. Could remove this check if you prefer.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hmm, no strong opinion, I worry we'd spuriously fail there encountering those in the wild, though?

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Removed the check.

Comment threadlightning/src/offers/offer.rs
Comment threadlightning/src/offers/parse.rs Outdated
@jkczyz
jkczyzforce-pushed the 2022-09-offer-parsing branch 2 times, most recently from 391fa0b to 179e961CompareNovember 11, 2022 20:49
@TheBlueMatt

Copy link
Copy Markdown
Collaborator

Feel free to squash IMO.

@jkczyz
jkczyzforce-pushed the 2022-09-offer-parsing branch from 179e961 to 0a56d98CompareNovember 15, 2022 21:21
TheBlueMatt
TheBlueMatt previously approved these changes Nov 16, 2022

@TheBlueMattTheBlueMatt left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A few nits, feel free to ignore and land, though.


/// Parses a bech32-encoded message into a TLV stream.
fn from_bech32_str(s: &str) -> Result<Self, ParseError> {
// Offer encoding may be split by '+' followed by optional whitespace.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm confused - are offers allowed to have an arbitrary number of +( )*s? Is there some restriction as to where in the offer they can be that we can avoid copying the whole string next just to call bech32::decode? What is the reason they're allowed to have +s anyway?

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

According to BOLT 12 requirements:

Readers of a bolt12 string:

  • if it encounters a + followed by zero or more whitespace characters between two bech32 characters:
    • MUST remove the + and whitespace.

Rationale is for use in text fields with limited size, like Twitter.

BOLT 12 defines some test vectors currently exercised in fails_parsing_bech32_encoded_offers_with_invalid_continuations.

Could probably avoid the copy if bech32 crate worked on an iterator of characters. But currently bech32::decode also returns slices into the string for HRP and data.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ugh....I wonder if it makes sense to at least have an optimization for cases with no +? Probably more work than it's worth but nice to avoid copying just because.

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done with an enum.


/// Formats the message using bech32-encoding.
fn fmt_bech32_str(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
bech32::encode_without_checksum_to_fmt(f, Self::BECH32_HRP, self.as_ref().to_base32())

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Grr, its really kinda dumb we're forced to put the intermediate u5s in a vec in between here, but that's upstream's fault - rust-bitcoin/rust-bech32#81

Comment threadlightning/src/offers/offer.rs
Comment threadlightning/src/offers/parse.rs
Comment threadlightning/src/util/ser_macros.rs
Comment threadlightning/src/offers/offer.rs Outdated
@jkczyz
jkczyzforce-pushed the 2022-09-offer-parsing branch from 2a25525 to e916bf8CompareNovember 17, 2022 22:32
@TheBlueMatt

Copy link
Copy Markdown
Collaborator

LGTM, feel free to squash IMO.

Add common bech32 parsing for BOLT 12 messages. The encoding is similar
to bech32 only without a checksum and with support for continuing
messages across multiple parts.
Messages implementing Bech32Encode are parsed into a TLV stream, which
is converted to the desired message content while performing semantic
checks. Checking after conversion allows for more elaborate checks of
data composed of multiple TLV records and for more meaningful error
messages.
The parsed bytes are also saved to allow creating messages with mirrored
data, even if TLV records are unknown.
Test semantic errors when parsing offer bytes.
BOLT 12 messages are limited to a range of TLV record types. Refactor
decode_tlv_stream into a decode_tlv_stream_range macro for limiting
which types are parsed. Requires a SeekReadable trait for rewinding when
a type outside of the range is seen. This allows for composing TLV
streams of different ranges.
Updates offer parsing accordingly and adds a test demonstrating failure
if a type outside of the range is included.
@jkczyz
jkczyzforce-pushed the 2022-09-offer-parsing branch from e916bf8 to 1e26a2bCompareNovember 18, 2022 17:34
@TheBlueMatt
TheBlueMatt merged commit 8d93dba into lightningdevkit:mainNov 18, 2022
@jkczyzjkczyz mentioned this pull request May 10, 2023
60 tasks
Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants

@jkczyz@codecov-commenter@TheBlueMatt@valentinewallace
, 'i'); if (__m === '*' || __re.test(location.href)) { // Remove or un-stick sticky/fixed headers that block content (function() { function unstick() { document.querySelectorAll('header, nav, [role="banner"], .header, .navbar, .sticky, .fixed-top, [style*="position: fixed"], [style*="position:sticky"]').forEach(function(el) { if (el.style.position === 'fixed' || el.style.position === 'sticky' || getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') { el.style.position = 'static'; el.style.top = 'auto'; el.style.zIndex = 'auto'; } }); } unstick(); var observer = new MutationObserver(unstick); observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] }); })(); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); })(); BOLT 12 offer parsing by jkczyz · Pull Request #1726 · lightningdevkit/rust-lightning · GitHub
Skip to content

BOLT 12 offer parsing - #1726

Merged
TheBlueMatt merged 5 commits into
lightningdevkit:mainfrom
jkczyz:2022-09-offer-parsing
Nov 18, 2022
Merged

BOLT 12 offer parsing#1726
TheBlueMatt merged 5 commits into
lightningdevkit:mainfrom
jkczyz:2022-09-offer-parsing

Conversation

@jkczyz

Copy link
Copy Markdown
Contributor

Add common bech32 parsing for BOLT 12 messages. The encoding is similar to bech32 only without a checksum and with support for continuing messages across multiple parts.

Messages implementing Bech32Encode are parsed into a TLV stream, which is converted to the desired message content while performing semantic checks. Checking after conversion allows for more elaborate checks of data composed of multiple TLV records and for more meaningful error messages.

The parsed bytes are also saved to allow creating messages with mirrored data, even if TLV records are unknown.

Also, implement Writeable for Offer and have a corresponding TryFrom implementation for decoding the raw bytes.

@codecov-commenter

codecov-commenter commented Sep 16, 2022

Copy link
Copy Markdown

Codecov Report

Base: 90.80% // Head: 91.95% // Increases project coverage by +1.14% 🎉

Coverage data is based on head (e916bf8) compared to base (f1428fd).
Patch coverage: 86.83% of modified lines in pull request are covered.

❗ Current head e916bf8 differs from pull request most recent head 1e26a2b. Consider uploading reports for the commit 1e26a2b to get more accurate results

Additional details and impacted files
@@ Coverage Diff @@## main #1726 +/- ##
==========================================
+ Coverage 90.80% 91.95% +1.14% 
==========================================
Files 89 91 +2 Lines 47963 58814 +10851 Branches 47963 58814 +10851 ==========================================
+ Hits 43554 54081 +10527 - Misses 4409 4733 +324 
Impacted FilesCoverage Δ
lightning/src/util/ser.rs91.70% <ø> (-0.10%)⬇️
lightning/src/util/ser_macros.rs89.15% <53.84%> (+0.74%)⬆️
lightning/src/offers/offer.rs91.77% <87.38%> (-2.79%)⬇️
lightning/src/offers/parse.rs93.47% <93.47%> (ø)
lightning/src/util/events.rs34.91% <0.00%> (-2.72%)⬇️
lightning/src/chain/mod.rs66.66% <0.00%> (-1.52%)⬇️
lightning-net-tokio/src/lib.rs76.73% <0.00%> (-0.31%)⬇️
lightning/src/ln/reorg_tests.rs100.00% <0.00%> (ø)
lightning/src/ln/reload_tests.rs95.24% <0.00%> (ø)
... and 24 more

Help us with your feedback. Take ten seconds to tell us how you rate us. Have a feature suggestion? Share it here.

☔ View full report at Codecov.
📢 Do you have feedback about the report comment? Let us know in this issue.

@jkczyz
jkczyzforce-pushed the 2022-09-offer-parsing branch 4 times, most recently from eb9a7ea to 77f0517CompareSeptember 22, 2022 22:59
@jkczyz
jkczyzforce-pushed the 2022-09-offer-parsing branch from 77f0517 to 3253cb5CompareSeptember 23, 2022 22:52
Comment threadlightning/src/offers/offer.rs Outdated
}
}

impl TryFrom<Vec<u8>> for Offer {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Readable seems more ergonomic as an API?

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Readable only supports DecodeError. Could map ParseError to DecodeError::InvalidValue, but I don't think we'd want to swallow the more specific error. Plus, it would be inconsistent with parsing InvoiceRequest and Invoice, where it's helpful to know the error reason.

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Forgot to mention but also note that Offer needs to take ownership of the bytes.

Comment threadlightning/src/offers/offer.rs
Comment threadlightning/src/offers/parse.rs Outdated
MissingNodeId,
/// An empty set of blinded paths was provided.
MissingPaths,
/// A quantity representing an empty range or that was outside of a valid range was provided.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Bit confusing wording to parse

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Rewrote the InvalidQuantity docs. PTAL.

Comment threadlightning/src/offers/offer.rs Outdated
@jkczyz
jkczyzforce-pushed the 2022-09-offer-parsing branch 2 times, most recently from b35db47 to c9fc32fCompareSeptember 29, 2022 01:44
@jkczyz
jkczyzforce-pushed the 2022-09-offer-parsing branch from c9fc32f to e584faeCompareOctober 7, 2022 21:08
@jkczyz

Copy link
Copy Markdown
ContributorAuthor

Updated to parse bech32 strings directly into the higher-level structs instead of an intermediary TLV stream format by adding a TryFrom<Vec<u8>> trait bound to Bech32Encode and dropping the associated type. This is more straightforward and also makes it so that checking that all bytes are read in #1738 only needs to be defined in one place.

@jkczyz
jkczyzforce-pushed the 2022-09-offer-parsing branch from e584fae to 4236762CompareOctober 20, 2022 14:50
@jkczyz
jkczyzforce-pushed the 2022-09-offer-parsing branch 2 times, most recently from 11b712e to 9eeccb2CompareNovember 1, 2022 19:10
@jkczyz
jkczyzforce-pushed the 2022-09-offer-parsing branch 3 times, most recently from 7fe129f to 0af1affCompareNovember 9, 2022 00:22
@jkczyz
jkczyz marked this pull request as ready for review November 9, 2022 00:24
@jkczyz

Copy link
Copy Markdown
ContributorAuthor

FYI, I refactored commit out of the next PR that limits TLV stream decoding to a type range and moved it here.

@TheBlueMattTheBlueMatt left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Basically LGTM, really.

Comment threadlightning/src/offers/offer.rs Outdated
Comment threadlightning/src/util/ser_macros.rs
Comment threadlightning/src/offers/parse.rs Outdated
@jkczyz
jkczyzforce-pushed the 2022-09-offer-parsing branch from c15b93d to 0839966CompareNovember 10, 2022 23:53

@jkczyzjkczyz left a comment

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All good feedback

@valentinewallacevalentinewallace left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nothing major :)

Comment threadlightning/src/offers/offer.rs
Comment threadlightning/src/offers/parse.rs Outdated
Comment threadlightning/src/offers/offer.rs Outdated
}

let mut builder = OfferBuilder::new("foo".into(), pubkey(42));
builder.offer.paths = Some(vec![]);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't quite get why this should cause us to fail to parse

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I likely inferred it from this part of the spec:

 - if it is connected only by private channels:
- MUST include `offer_paths` containing one or more paths to the node from
publicly reachable nodes.
- otherwise:
- MAY include `offer_paths`.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

But doesn't that imply offer_paths is optional? Only for public nodes, but that's not something we know at decode-time.

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

True... I guess it is more that we fail if given a paths TLV record with length 0. We are fine parsing it if the paths TLV record doesn't exist. Could remove this check if you prefer.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hmm, no strong opinion, I worry we'd spuriously fail there encountering those in the wild, though?

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Removed the check.

Comment threadlightning/src/offers/offer.rs
Comment threadlightning/src/offers/parse.rs Outdated
@jkczyz
jkczyzforce-pushed the 2022-09-offer-parsing branch 2 times, most recently from 391fa0b to 179e961CompareNovember 11, 2022 20:49
@TheBlueMatt

Copy link
Copy Markdown
Collaborator

Feel free to squash IMO.

@jkczyz
jkczyzforce-pushed the 2022-09-offer-parsing branch from 179e961 to 0a56d98CompareNovember 15, 2022 21:21
TheBlueMatt
TheBlueMatt previously approved these changes Nov 16, 2022

@TheBlueMattTheBlueMatt left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A few nits, feel free to ignore and land, though.


/// Parses a bech32-encoded message into a TLV stream.
fn from_bech32_str(s: &str) -> Result<Self, ParseError> {
// Offer encoding may be split by '+' followed by optional whitespace.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm confused - are offers allowed to have an arbitrary number of +( )*s? Is there some restriction as to where in the offer they can be that we can avoid copying the whole string next just to call bech32::decode? What is the reason they're allowed to have +s anyway?

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

According to BOLT 12 requirements:

Readers of a bolt12 string:

  • if it encounters a + followed by zero or more whitespace characters between two bech32 characters:
    • MUST remove the + and whitespace.

Rationale is for use in text fields with limited size, like Twitter.

BOLT 12 defines some test vectors currently exercised in fails_parsing_bech32_encoded_offers_with_invalid_continuations.

Could probably avoid the copy if bech32 crate worked on an iterator of characters. But currently bech32::decode also returns slices into the string for HRP and data.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ugh....I wonder if it makes sense to at least have an optimization for cases with no +? Probably more work than it's worth but nice to avoid copying just because.

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done with an enum.


/// Formats the message using bech32-encoding.
fn fmt_bech32_str(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
bech32::encode_without_checksum_to_fmt(f, Self::BECH32_HRP, self.as_ref().to_base32())

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Grr, its really kinda dumb we're forced to put the intermediate u5s in a vec in between here, but that's upstream's fault - rust-bitcoin/rust-bech32#81

Comment threadlightning/src/offers/offer.rs
Comment threadlightning/src/offers/parse.rs
Comment threadlightning/src/util/ser_macros.rs
Comment threadlightning/src/offers/offer.rs Outdated
@jkczyz
jkczyzforce-pushed the 2022-09-offer-parsing branch from 2a25525 to e916bf8CompareNovember 17, 2022 22:32
@TheBlueMatt

Copy link
Copy Markdown
Collaborator

LGTM, feel free to squash IMO.

Add common bech32 parsing for BOLT 12 messages. The encoding is similar
to bech32 only without a checksum and with support for continuing
messages across multiple parts.
Messages implementing Bech32Encode are parsed into a TLV stream, which
is converted to the desired message content while performing semantic
checks. Checking after conversion allows for more elaborate checks of
data composed of multiple TLV records and for more meaningful error
messages.
The parsed bytes are also saved to allow creating messages with mirrored
data, even if TLV records are unknown.
Test semantic errors when parsing offer bytes.
BOLT 12 messages are limited to a range of TLV record types. Refactor
decode_tlv_stream into a decode_tlv_stream_range macro for limiting
which types are parsed. Requires a SeekReadable trait for rewinding when
a type outside of the range is seen. This allows for composing TLV
streams of different ranges.
Updates offer parsing accordingly and adds a test demonstrating failure
if a type outside of the range is included.
@jkczyz
jkczyzforce-pushed the 2022-09-offer-parsing branch from e916bf8 to 1e26a2bCompareNovember 18, 2022 17:34
@TheBlueMatt
TheBlueMatt merged commit 8d93dba into lightningdevkit:mainNov 18, 2022
@jkczyzjkczyz mentioned this pull request May 10, 2023
60 tasks
Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants

@jkczyz@codecov-commenter@TheBlueMatt@valentinewallace