Skip to content
LearnBitcoin

ResearchBitcoin Dev Archive lightning-dev list

Lightning payment format

14 messages, Apr 29 to May 29, 2017. Started by Rusty Russell.

Rusty Russell (8), Olaoluwa Osuntokun (2), Christian Decker (2), Pierre, Fabrice Drouin

Permalink First message in the Wayback Machine

Rusty Russell permalink original

Hi all!

        I threw together this draft format for requesting lightning
payments, and an (incomplete) implementation:
- https://github.com/rustyrussell/lightning-payencode

The representation size ranges from ~181 characters upwards: we could squeeze at least 5 of those out if we cared. Bech32 only guarantees to detect 3 errors at these lengths (beyond 1024 it's only 1), but the signature is the final error detection.

You'll notice one optimization for the common case: we use the 8-byte chanid (stealing 1 bit) to compactly refer to the destination. This is shorter than a full 33-byte pubkey, and relies on the fact that the network topology is well-known. We use these same style of IDs in the channel announcement messages already.

I look forward to both the bikeshed comments, and more substantive feedback :)

Thanks! Rusty.

Olaoluwa Osuntokun in reply to Rusty Russell permalink original

Hi Rusty,

I was thinking of proposing something similar recently, but looks like you beat me to it!

I really like the flexibility of the tag format. Over the past few months, I thought of quite a bit of things application developers can do by utilizing a tag-based payment request format in conjunction with either: the spare bytes of the onion payload or an abuse of the encrypted back errors (in combo with some onion payload bytes).

On the topic of bech32: I'm all for piggybacking on existing emerging standards in the space, but I'm not convinced we really gain anything by using it outside of the initial prefix. The human-readable amount within the prefix is nice for UX as you can eyeball exactly how much one is about to pay/receive. However, these payment requests can get rather long, so I don't envision any user typing them out by hand or reading them to someone over the phone. As a result, I don't think we have much use for bech32 character which has been optimized for manual-entry. Additionally, as this proposal includes a signature that covers the entire payreq, what's the use of the added checksum? Detecting 3 characters out of 1024+ is rather insignificant.

On the topic of signatures: as is proposed now, a user isn't able to verify
the validity of the signature (and thereby authenticity of the payreq and
integrity of the contents) without first having a (direction || chanID) ->
pubKey mapping. In my opinion, the payreqs are already so long that
optimizing for size is a bit of a waste. By replacing the chanID with the
compressed serialized public key, users will be able to immediately verify
the signature without the use of an external mapping.

I think this is a good step in the right direction. However, it utilizes an encoding whose rationale make sense for the Bitcoin address use-case, but in my opinion, doesn't carry over those compelling traits to the LN payreq use-case.

-- Laolu

On Fri, Apr 28, 2017 at 5:57 PM Rusty Russell <rusty at rustcorp.com.au> wrote:

Quoted text (28 lines)
> Hi all!
>
>         I threw together this draft format for requesting lightning
> payments, and an (incomplete) implementation:
>
> - https://github.com/rustyrussell/lightning-payencode
>
> The representation size ranges from ~181 characters upwards: we could
> squeeze at least 5 of those out if we cared.  Bech32 only guarantees to
> detect 3 errors at these lengths (beyond 1024 it's only 1), but the
> signature is the final error detection.
>
> You'll notice one optimization for the common case: we use the 8-byte
> chanid (stealing 1 bit) to compactly refer to the destination.  This is
> shorter than a full 33-byte pubkey, and relies on the fact that the
> network topology is well-known.  We use these same style of IDs in
> the channel announcement messages already.
>
> I look forward to both the bikeshed comments, and more substantive
> feedback :)
>
> Thanks!
> Rusty.
> _______________________________________________
> Lightning-dev mailing list
> Lightning-dev at lists.linuxfoundation.org
> https://www.learnbitcoin.com/archive/lists/lightning-dev
>
Rusty Russell in reply to Olaoluwa Osuntokun permalink original

Olaoluwa Osuntokun <laolu32 at gmail.com> writes:

Quoted text (10 lines)
> Hi Rusty,
>
> I was thinking of proposing something similar recently, but looks like you
> beat me to it!
>
> I really like the flexibility of the tag format. Over the past few months, I
> thought of quite a bit of things application developers can do by utilizing
> a tag-based payment request format in conjunction with either: the spare
> bytes of the onion payload or an abuse of the encrypted back errors (in
> combo with some onion payload bytes).

Yes, I thought about this too, but I'm reluctant to assign those onion bytes as they're a limited resource. Easy to add later, though.

Quoted text (11 lines)
> On the topic of bech32: I'm all for piggybacking on existing emerging
> standards in the space, but I'm not convinced we really gain anything by
> using it outside of the initial prefix. The human-readable amount within the
> prefix is nice for UX as you can eyeball exactly how much one is about to
> pay/receive. However, these payment requests can get rather long, so I don't
> envision any user typing them out by hand or reading them to someone over
> the phone.  As a result, I don't think we have much use for bech32 character
> which has been optimized for manual-entry.  Additionally, as this proposal
> includes a signature that covers the entire payreq, what's the use of the
> added checksum? Detecting 3 characters out of 1024+ is rather
> insignificant.

I kind of agree, but I think the code reuse outweighs other arguments, since codebases are going to have bech32 anyway.

The minimal theoretical size we can do is 20 (payment hash160) + 64 (signature). We'd have to change the protocol to use hash160 instead of sha256 (we already do this onchain). But even that is 135 characters, which is not going to be entered by hand, so I don't think it's worth it.

Quoted text (7 lines)
> On the topic of signatures: as is proposed now, a user isn't able to verify
> the validity of the signature (and thereby authenticity of the payreq and
> integrity of the contents) without first having a (direction || chanID) ->
> pubKey mapping. In my opinion, the payreqs are already so long that
> optimizing for size is a bit of a waste. By replacing the chanID with the
> compressed serialized public key, users will be able to immediately verify
> the signature without the use of an external mapping.

As you pointed out offline, we can do key recovery from the signature[1], so the information is there already in fact :) The chanid is really a courtesy, from this POV.

Quoted text (4 lines)
> I think this is a good step in the right direction. However, it utilizes an
> encoding whose rationale make sense for the Bitcoin address use-case, but in
> my opinion, doesn't carry over those compelling traits to the LN payreq
> use-case.
Thanks!
Rusty.
[1]  You also pointed out that we can use the same technique to remove
     node-id and bitcoin-key from the channel announcement.  Which would
     be awesome magic...
Pierre in reply to Rusty Russell permalink original
Quoted text (7 lines)
>> On the topic of signatures: as is proposed now, a user isn't able to verify
>> the validity of the signature (and thereby authenticity of the payreq and
>> integrity of the contents) without first having a (direction || chanID) ->
>> pubKey mapping. In my opinion, the payreqs are already so long that
>> optimizing for size is a bit of a waste. By replacing the chanID with the
>> compressed serialized public key, users will be able to immediately verify
>> the signature without the use of an external mapping.

As much as I pushed for using the short chanID in the onion, I too am a reluctant to use it here. In addition to laolu's arguments, I would say: - making the assumption that the network is well-known doesn't take into account the fact that announcements take time to propagate through the network (typically a few minutes with staggered broadcast every minute); ok it doesn't change often, but now we will need to worry about not using our most recently created/closed channels as reference. - we already know that we won't always be able to have a full view of the network in the future, so I feel like we should rely on it as less as possible - since payment requests are sent out-of-band, optimizing their size is maybe not as important as messages exchanged on the p2p network?

Quoted text (3 lines)
>As you pointed out offline, we can do key recovery from the signature[1],
>so the information is there already in fact :)  The chanid is really a
>courtesy, from this POV.

That is really amazing! Why not completely ditch the chanid then? ;-)

Cheers,

Pierre

2017-05-02 2:40 GMT+02:00 Rusty Russell <rusty at rustcorp.com.au>:

Quoted text (62 lines)
> Olaoluwa Osuntokun <laolu32 at gmail.com> writes:
>> Hi Rusty,
>>
>> I was thinking of proposing something similar recently, but looks like you
>> beat me to it!
>>
>> I really like the flexibility of the tag format. Over the past few months, I
>> thought of quite a bit of things application developers can do by utilizing
>> a tag-based payment request format in conjunction with either: the spare
>> bytes of the onion payload or an abuse of the encrypted back errors (in
>> combo with some onion payload bytes).
>
> Yes, I thought about this too, but I'm reluctant to assign those onion
> bytes as they're a limited resource.  Easy to add later, though.
>
>> On the topic of bech32: I'm all for piggybacking on existing emerging
>> standards in the space, but I'm not convinced we really gain anything by
>> using it outside of the initial prefix. The human-readable amount within the
>> prefix is nice for UX as you can eyeball exactly how much one is about to
>> pay/receive. However, these payment requests can get rather long, so I don't
>> envision any user typing them out by hand or reading them to someone over
>> the phone.  As a result, I don't think we have much use for bech32 character
>> which has been optimized for manual-entry.  Additionally, as this proposal
>> includes a signature that covers the entire payreq, what's the use of the
>> added checksum? Detecting 3 characters out of 1024+ is rather
>> insignificant.
>
> I kind of agree, but I think the code reuse outweighs other arguments,
> since codebases are going to have bech32 anyway.
>
> The minimal theoretical size we can do is 20 (payment hash160) + 64
> (signature).  We'd have to change the protocol to use hash160 instead of
> sha256 (we already do this onchain).  But even that is 135 characters,
> which is not going to be entered by hand, so I don't think it's worth
> it.
>
>> On the topic of signatures: as is proposed now, a user isn't able to verify
>> the validity of the signature (and thereby authenticity of the payreq and
>> integrity of the contents) without first having a (direction || chanID) ->
>> pubKey mapping. In my opinion, the payreqs are already so long that
>> optimizing for size is a bit of a waste. By replacing the chanID with the
>> compressed serialized public key, users will be able to immediately verify
>> the signature without the use of an external mapping.
>
> As you pointed out offline, we can do key recovery from the signature[1],
> so the information is there already in fact :)  The chanid is really a
> courtesy, from this POV.
>
>> I think this is a good step in the right direction. However, it utilizes an
>> encoding whose rationale make sense for the Bitcoin address use-case, but in
>> my opinion, doesn't carry over those compelling traits to the LN payreq
>> use-case.
>
> Thanks!
> Rusty.
> [1]  You also pointed out that we can use the same technique to remove
>      node-id and bitcoin-key from the channel announcement.  Which would
>      be awesome magic...
> _______________________________________________
> Lightning-dev mailing list
> Lightning-dev at lists.linuxfoundation.org
> https://www.learnbitcoin.com/archive/lists/lightning-dev
Fabrice Drouin in reply to Pierre permalink original

Hi Rusty,

Payment requests should also include a timestamp and an expiry date (they could be optional tagged items but I think it makes more sense to make them mandatory) ​ Thanks! Fabrice​

On 2 May 2017 at 18:11, Pierre <pm+lists at acinq.fr> wrote:

Quoted text (125 lines)
> >> On the topic of signatures: as is proposed now, a user isn't able to
> verify
> >> the validity of the signature (and thereby authenticity of the payreq
> and
> >> integrity of the contents) without first having a (direction || chanID)
> ->
> >> pubKey mapping. In my opinion, the payreqs are already so long that
> >> optimizing for size is a bit of a waste. By replacing the chanID with
> the
> >> compressed serialized public key, users will be able to immediately
> verify
> >> the signature without the use of an external mapping.
>
> As much as I pushed for using the short chanID in the onion, I too am
> a reluctant to use
> it here. In addition to laolu's arguments, I would say:
> - making the assumption that the network is well-known doesn't take
> into account the fact
> that announcements take time to propagate through the network
> (typically a few minutes with
> staggered broadcast every minute); ok it doesn't change often, but now
> we will need to worry
> about not using our most recently created/closed channels as reference.
> - we already know that we won't always be able to have a full view of
> the network in
> the future, so I feel like we should rely on it as less as possible
> - since payment requests are sent out-of-band, optimizing their size
> is maybe not as
> important as messages exchanged on the p2p network?
>
> >As you pointed out offline, we can do key recovery from the signature[1],
> >so the information is there already in fact :)  The chanid is really a
> >courtesy, from this POV.
>
> That is really amazing! Why not completely ditch the chanid then? ;-)
>
> Cheers,
>
> Pierre
>
> 2017-05-02 2:40 GMT+02:00 Rusty Russell <rusty at rustcorp.com.au>:
> > Olaoluwa Osuntokun <laolu32 at gmail.com> writes:
> >> Hi Rusty,
> >>
> >> I was thinking of proposing something similar recently, but looks like
> you
> >> beat me to it!
> >>
> >> I really like the flexibility of the tag format. Over the past few
> months, I
> >> thought of quite a bit of things application developers can do by
> utilizing
> >> a tag-based payment request format in conjunction with either: the spare
> >> bytes of the onion payload or an abuse of the encrypted back errors (in
> >> combo with some onion payload bytes).
> >
> > Yes, I thought about this too, but I'm reluctant to assign those onion
> > bytes as they're a limited resource.  Easy to add later, though.
> >
> >> On the topic of bech32: I'm all for piggybacking on existing emerging
> >> standards in the space, but I'm not convinced we really gain anything by
> >> using it outside of the initial prefix. The human-readable amount
> within the
> >> prefix is nice for UX as you can eyeball exactly how much one is about
> to
> >> pay/receive. However, these payment requests can get rather long, so I
> don't
> >> envision any user typing them out by hand or reading them to someone
> over
> >> the phone.  As a result, I don't think we have much use for bech32
> character
> >> which has been optimized for manual-entry.  Additionally, as this
> proposal
> >> includes a signature that covers the entire payreq, what's the use of
> the
> >> added checksum? Detecting 3 characters out of 1024+ is rather
> >> insignificant.
> >
> > I kind of agree, but I think the code reuse outweighs other arguments,
> > since codebases are going to have bech32 anyway.
> >
> > The minimal theoretical size we can do is 20 (payment hash160) + 64
> > (signature).  We'd have to change the protocol to use hash160 instead of
> > sha256 (we already do this onchain).  But even that is 135 characters,
> > which is not going to be entered by hand, so I don't think it's worth
> > it.
> >
> >> On the topic of signatures: as is proposed now, a user isn't able to
> verify
> >> the validity of the signature (and thereby authenticity of the payreq
> and
> >> integrity of the contents) without first having a (direction || chanID)
> ->
> >> pubKey mapping. In my opinion, the payreqs are already so long that
> >> optimizing for size is a bit of a waste. By replacing the chanID with
> the
> >> compressed serialized public key, users will be able to immediately
> verify
> >> the signature without the use of an external mapping.
> >
> > As you pointed out offline, we can do key recovery from the signature[1],
> > so the information is there already in fact :)  The chanid is really a
> > courtesy, from this POV.
> >
> >> I think this is a good step in the right direction. However, it
> utilizes an
> >> encoding whose rationale make sense for the Bitcoin address use-case,
> but in
> >> my opinion, doesn't carry over those compelling traits to the LN payreq
> >> use-case.
> >
> > Thanks!
> > Rusty.
> > [1]  You also pointed out that we can use the same technique to remove
> >      node-id and bitcoin-key from the channel announcement.  Which would
> >      be awesome magic...
> > _______________________________________________
> > Lightning-dev mailing list
> > Lightning-dev at lists.linuxfoundation.org
> > https://www.learnbitcoin.com/archive/lists/lightning-dev
> _______________________________________________
> Lightning-dev mailing list
> Lightning-dev at lists.linuxfoundation.org
> https://www.learnbitcoin.com/archive/lists/lightning-dev
>
Rusty Russell in reply to Fabrice Drouin permalink original

Fabrice Drouin <fabrice.drouin at acinq.fr> writes:

Quoted text (5 lines)
> Hi Rusty,
>
> Payment requests should also include a timestamp and an expiry date (they
> could be optional tagged items but I think it makes more sense to make them
> mandatory)

Excellent point. Provability definitely requires a timestamp, but the duration could be optional.

Here's the patch I just pushed:

Subject: Add timestamp and (optional) expiry.

We take advantage of the variable length encoding for the expiry timestamp, and 32 bits for the offer time (wake me in 2106 to update the spec).

I chose a reasonable default expiry of 1 hour; the intention is that the software should warn if this expiry approaches.

Suggested-by: Fabrice Drouin <fabrice.drouin at acinq.fr> Signed-off-by: Rusty Russell <rusty at rustcorp.com.au>

diff --git a/README.md b/README.md index 3039333..6da4150 100644 --- a/README.md +++ b/README.md @@ -11,6 +11,7 @@ Human readable part:

 And data part:
 1. Version: 0 (5 bits)
+1. UTC timestamp in seconds-since-Unix-epoch (32 bits)
 1. Payment hash (256 bits)
 1. Zero or more tagged parts.
 1. Signature (bitcoin-style, of SHA256(SHA256(), plus recovery byte) of above. (520 bits)
@@ -25,6 +26,7 @@ Currently defined tagged parts are:
 1. h: description of purpose of payment (SHA256).  This is used to commit
    to an associated description which is too long to fit, such as may
    be contained in a web page.
+1. x: expiry time in seconds. Default is 3600 (1 hour) if not specified.
 1. f: fallback onchain-address.  20 bytes == p2pkh.  21 bytes == p2wpkh, 33 bytes == p2wsh.
 1. r: extra routing information.  This should be appended to the route
       to allow routing to non-public nodes; there may be more
diff --git a/examples.sh b/examples.sh
index 78c2be8..f526223 100755
--- a/examples.sh
+++ b/examples.sh
@@ -11,8 +11,8 @@ echo "# Please send 10 satoshi using rhash $RHASH to me @$PUBKEY"
 ./lightning-address.py encode 10000 $RHASH $PRIVKEY
 echo

-echo "# Please send \$3 for a cup of coffee to the same peer" -./lightning-address.py encode --description='1 cup coffee' $((3 * 100000000000 / $CONVERSION_RATE)) $RHASH $PRIVKEY +echo "# Please send \$3 for a cup of coffee to the same peer, within 1 minute" +./lightning-address.py encode --description='1 cup coffee' $((3 * 100000000000 / $CONVERSION_RATE)) --expires=60 $RHASH $PRIVKEY echo

echo "# Now send \$24 for an entire list of things (hashed)" diff --git a/lightning-address.py b/lightning-address.py index c43d020..7b72314 100755 --- a/lightning-address.py +++ b/lightning-address.py @@ -3,6 +3,7 @@ import argparse import hashlib import re import sys +import time # Try 'pip3 install secp256k1' import secp256k1

@@ -138,9 +139,24 @@ def u32list(val):
     assert val < (1 << 32)
     return bytearray([(val >> 24) & 0xff, (val >> 16) & 0xff, (val >> 8) & 0xff, val & 0xff])
+# Represent big-endian number with as many bytes as it takes.
+def varlist(val):
+    b = bytearray()
+    while val != 0:
+        b.append(val & 0xFF)
+        val = val // 256
+    b.reverse()
+    return b
+
 def from_u32list(l):
     return (l[0] << 24) + (l[1] << 16) + (l[2] << 8) + l[3]
+def from_varlist(l):
+    total = 0
+    for v in l:
+        total = total * 256 + v
+    return total
+
 def tagged(char, l):
     bits=convertbits(l, 8, 5)
     assert len(bits) < (1 << 10)
@@ -169,9 +185,12 @@ def lnencode(options):
     hrp = 'ln' + options.currency + amount
-    # version + paymenthash
-    data = [0] + convertbits(bytearray.fromhex(options.paymenthash), 8, 5)
+    # version + timestamp + paymenthash
+    now = int(time.time())
+    assert len(u32list(now) + bytearray.fromhex(options.paymenthash)) == 4 + 32
+    data = [0] + convertbits(u32list(now) + bytearray.fromhex(options.paymenthash), 8, 5)
+
     for r in options.route:
         pubkey,channel,fee,cltv = r.split('/')
         route = bytearray.fromhex(pubkey) + bytearray.fromhex(channel) + u32list(int(fee)) + u32list(int(cltv))
@@ -183,7 +202,10 @@ def lnencode(options):
     if options.description:
         data = data + tagged('d', [ord(c) for c in options.description])
-
+
+    if options.expires:
+        data = data + tagged('x', varlist(options.expires))
+
     if options.description_hashed:
         data = data + tagged('h', hashlib.sha256(options.description_hashed.encode('utf-8')).digest())
@@ -239,14 +261,16 @@ def lndecode(options):
     if options.rate:
         print("(Conversion: {})".format(amount / 10**11 * float(options.rate)))
-    # 32 bytes turns into 52 bytes when base32 encoded.
-    if len(data) < 52:
-        sys.exit("Not long enough to contain payment hash")
+    # 4 + 32 bytes turns into 58 bytes when base32 encoded.
+    if len(data) < 58:
+        sys.exit("Not long enough to contain timestamp and payment hash")
-    decoded = convertbits(data[:52], 5, 8, False)
-    data = data[52:]
-    assert len(decoded) == 32
-    print("Payment hash: {}".format(bytearray(decoded).hex()))
+    decoded = convertbits(data[:58], 5, 8, False)
+    data = data[58:]
+    assert len(decoded) == 4 + 32
+    tstamp = from_u32list(decoded[0:4])
+    print("Timestamp: {} ({})".format(tstamp, time.ctime(tstamp)))
+    print("Payment hash: {}".format(bytearray(decoded[4:]).hex()))
     while len(data) > 0:
         tag,tagdata,data = pull_tagged(data)
@@ -265,6 +289,8 @@ def lndecode(options):
             print("Description: {}".format(''.join(chr(c) for c in tagdata)))
         elif tag == 'h':
             print("Description hash: {}".format(bytearray(tagdata).hex()))
+        elif tag == 'x':
+            print("Expiry (seconds): {}".format(from_varlist(tagdata)))
         else:
             print("UNKNOWN TAG {}: {}".format(tag, bytearray(tagdata).hex()))
@@ -286,6 +312,8 @@ parser_enc.add_argument('--description',
                         help='What is being purchased')
 parser_enc.add_argument('--description-hashed',
                         help='What is being purchased (for hashing)')
+parser_enc.add_argument('--expires', type=int,
+                        help='Seconds before offer expires')
 parser_enc.add_argument('amount', type=int, help='Amount in millisatoshi')
 parser_enc.add_argument('paymenthash', help='Payment hash (in hex)')
 parser_enc.add_argument('privkey', help='Private key (in hex)')
Rusty Russell in reply to Pierre permalink original

Pierre <pm+lists at acinq.fr> writes:

Quoted text (30 lines)
>>> On the topic of signatures: as is proposed now, a user isn't able to verify
>>> the validity of the signature (and thereby authenticity of the payreq and
>>> integrity of the contents) without first having a (direction || chanID) ->
>>> pubKey mapping. In my opinion, the payreqs are already so long that
>>> optimizing for size is a bit of a waste. By replacing the chanID with the
>>> compressed serialized public key, users will be able to immediately verify
>>> the signature without the use of an external mapping.
>
> As much as I pushed for using the short chanID in the onion, I too am
> a reluctant to use
> it here. In addition to laolu's arguments, I would say:
> - making the assumption that the network is well-known doesn't take
> into account the fact
> that announcements take time to propagate through the network
> (typically a few minutes with
> staggered broadcast every minute); ok it doesn't change often, but now
> we will need to worry
> about not using our most recently created/closed channels as reference.
> - we already know that we won't always be able to have a full view of
> the network in
> the future, so I feel like we should rely on it as less as possible
> - since payment requests are sent out-of-band, optimizing their size
> is maybe not as
> important as messages exchanged on the p2p network?
>
>>As you pointed out offline, we can do key recovery from the signature[1],
>>so the information is there already in fact :)  The chanid is really a
>>courtesy, from this POV.
>
> That is really amazing! Why not completely ditch the chanid then? ;-)

OK, I have done this. I added another byte which you need to figure out which key to recover as there may be multiples.

I will add a dependency on the python libsecp256k1 so I can update the tool.

Note: we will lose this ability when we switch to Schnorr, apparently. But then we'll have more data on actual usage by which to decide on tradeoffs.

I've pushed this change. Here's the patch:

Subject: Drop channel ID in favor of key recovery.

As suggested by roasbeef (Olaoluwa Osuntokun). We add a byte to the signature, even though we only need 1 or 2 bits for recovery ID.

The signature is actually over human readable part and data in 5-bit bytes, for simplicity of implementation (all current bech32 encoders work this way).

Signed-off-by: Rusty Russell <rusty at rustcorp.com.au>

diff --git a/README.md b/README.md index b6ac088..3039333 100644 --- a/README.md +++ b/README.md @@ -12,9 +12,8 @@ Human readable part: And data part: 1. Version: 0 (5 bits) 1. Payment hash (256 bits) -1. Dest channel id (high bit == which end) (64 bits) 1. Zero or more tagged parts. -1. Signature (bitcoin-style, of SHA256(SHA256()) of above. (256 bits) +1. Signature (bitcoin-style, of SHA256(SHA256(), plus recovery byte) of above. (520 bits)

Tagged parts are of format: 1. type (5 bits) diff --git a/examples.sh b/examples.sh index 3da33ab..78c2be8 100755 --- a/examples.sh +++ b/examples.sh @@ -2,28 +2,27 @@

# Dummy placeholder values RHASH=0001020304050607080900010203040506070809000102030405060708090102 -CHANID=1122334455667788 CONVERSION_RATE=1200 # Random keypair for testing. PRIVKEY=e126f68f7eafcc8b74f54d269fe206be715000f94dac067d1c04a8ca3b2db734 PUBKEY=03e7156ae33b0a208d0744199163177e909e80176e55d97a2f221ede0f934dd9ad

-echo '# Please send 10 satoshi using rhash $RHASH to node at channel $CHANID (numerically-lesser end of those peers).' -./lightning-address.py encode 10000 $RHASH $CHANID $PRIVKEY +echo "# Please send 10 satoshi using rhash $RHASH to me @$PUBKEY" +./lightning-address.py encode 10000 $RHASH $PRIVKEY echo

-echo '# Please send $3 for a cup of coffee to the same peer' -./lightning-address.py encode --description='1 cup coffee' $((3 * 100000000000 / $CONVERSION_RATE)) $RHASH $CHANID $PRIVKEY +echo "# Please send \$3 for a cup of coffee to the same peer" +./lightning-address.py encode --description='1 cup coffee' $((3 * 100000000000 / $CONVERSION_RATE)) $RHASH $PRIVKEY echo

-echo '# Now send $24 for an entire list of things (hashed)' -./lightning-address.py encode --description-hashed='One piece of chocolate cake, one icecream cone, one pickle, one slice of swiss cheese, one slice of salami, one lollypop, one piece of cherry pie, one sausage, one cupcake, and one slice of watermelon' $((24 * 100000000000 / $CONVERSION_RATE)) $RHASH $CHANID $PRIVKEY +echo "# Now send \$24 for an entire list of things (hashed)" +./lightning-address.py encode --description-hashed='One piece of chocolate cake, one icecream cone, one pickle, one slice of swiss cheese, one slice of salami, one lollypop, one piece of cherry pie, one sausage, one cupcake, and one slice of watermelon' $((24 * 100000000000 / $CONVERSION_RATE)) $RHASH $PRIVKEY echo

# NOTE: Does not implement real fallback format yet! echo '# The same, with a fallback address mk2QpYatsKicvFVuTAQLBryyccRXMUaGHP' -./lightning-address.py encode --fallback=mk2QpYatsKicvFVuTAQLBryyccRXMUaGHP --description-hashed='One piece of chocolate cake, one icecream cone, one pickle, one slice of swiss cheese, one slice of salami, one lollypop, one piece of cherry pie, one sausage, one cupcake, and one slice of watermelon' $((24 * 100000000000 / $CONVERSION_RATE)) $RHASH $CHANID $PRIVKEY +./lightning-address.py encode --fallback=mk2QpYatsKicvFVuTAQLBryyccRXMUaGHP --description-hashed='One piece of chocolate cake, one icecream cone, one pickle, one slice of swiss cheese, one slice of salami, one lollypop, one piece of cherry pie, one sausage, one cupcake, and one slice of watermelon' $((24 * 100000000000 / $CONVERSION_RATE)) $RHASH $PRIVKEY echo

echo '# The same, with extra routing info to get to node 029e03a901b85534ff1e92c43c74431f7ce72046060fcf7a95c37e148f78c77255' -./lightning-address.py encode --route=029e03a901b85534ff1e92c43c74431f7ce72046060fcf7a95c37e148f78c77255/0102030405060708/20/3 --fallback=mk2QpYatsKicvFVuTAQLBryyccRXMUaGHP --description-hashed='One piece of chocolate cake, one icecream cone, one pickle, one slice of swiss cheese, one slice of salami, one lollypop, one piece of cherry pie, one sausage, one cupcake, and one slice of watermelon' $((24 * 100000000000 / $CONVERSION_RATE)) $RHASH $CHANID $PRIVKEY +./lightning-address.py encode --route=029e03a901b85534ff1e92c43c74431f7ce72046060fcf7a95c37e148f78c77255/0102030405060708/20/3 --fallback=mk2QpYatsKicvFVuTAQLBryyccRXMUaGHP --description-hashed='One piece of chocolate cake, one icecream cone, one pickle, one slice of swiss cheese, one slice of salami, one lollypop, one piece of cherry pie, one sausage, one cupcake, and one slice of watermelon' $((24 * 100000000000 / $CONVERSION_RATE)) $RHASH $PRIVKEY diff --git a/lightning-address.py b/lightning-address.py index 1a3f670..c43d020 100755 --- a/lightning-address.py +++ b/lightning-address.py @@ -169,8 +169,8 @@ def lnencode(options):

     hrp = 'ln' + options.currency + amount
-    # version + paymenthash + channelid
-    data = [0] + convertbits(bytearray.fromhex(options.paymenthash) + bytearray.fromhex(options.channelid), 8, 5)
+    # version + paymenthash
+    data = [0] + convertbits(bytearray.fromhex(options.paymenthash), 8, 5)
     for r in options.route:
         pubkey,channel,fee,cltv = r.split('/')
@@ -189,9 +189,10 @@ def lnencode(options):
     # We actually sign the hrp, then the array of 5-bit values as bytes.
     privkey = secp256k1.PrivateKey(bytes(bytearray.fromhex(options.privkey)))
-    sig = privkey.ecdsa_serialize_compact(privkey.ecdsa_sign(
-        bytearray([ord(c) for c in hrp] + data)))
-    data = data + convertbits(sig, 8, 5)
+    sig = privkey.ecdsa_sign_recoverable(bytearray([ord(c) for c in hrp] + data))
+    # This doesn't actually serialize, but returns a pair of values :(
+    sig,recid = privkey.ecdsa_recoverable_serialize(sig)
+    data = data + convertbits(bytes(sig) + bytes([recid]), 8, 5)
     print(bech32_encode(hrp, data))

@@ -205,27 +206,19 @@ def lndecode(options):

     if data[0] != 0:
         sys.exit("Unknown version {}".format(data[0]))
+    data = data[1:]
-    # Final signature takes 103 bytes (64 bytes base32 encoded)
+    # Final signature takes 104 bytes (65 bytes base32 encoded)
     if len(data) < 103:
         sys.exit("Too short to contain signature")
-    sigdecoded = convertbits(data[-103:], 5, 8, False)
-    data = data[:-103]
-
-    if options.pubkey:
-        pubkey = secp256k1.PublicKey()
-        pubkey.deserialize(bytes(bytearray.fromhex(options.pubkey)))
-        sig = pubkey.ecdsa_deserialize_compact(sigdecoded)
-        if not pubkey.ecdsa_verify(bytearray([ord(c) for c in hrp] + data), sig):
-            sys.exit("Bad signature")
-        print("Signature: OK")
-    else:
-        print("Signature: Unknown")
-
-    # Preserve original data for signature check.
-    origdata = data
-    data = data[1:]
+    sigdecoded = convertbits(data[-104:], 5, 8, False)
+    data = data[:-104]
+    pubkey = secp256k1.PublicKey(flags=secp256k1.ALL_FLAGS)
+    sig = pubkey.ecdsa_recoverable_deserialize(sigdecoded[0:64], sigdecoded[64])
+    pubkey.public_key = pubkey.ecdsa_recover(bytearray([ord(c) for c in hrp] + data), sig)
+    print("Signed with public key: {}".format(bytearray(pubkey.serialize()).hex()))
+
     m = re.search("\d+", hrp)
     if not m:
         sys.exit("Does not contain amount")
@@ -246,15 +239,14 @@ def lndecode(options):
     if options.rate:
         print("(Conversion: {})".format(amount / 10**11 * float(options.rate)))
-    # (32 + 8) bytes turns into 64 bytes when base32 encoded.
-    if len(data) < 64:
-        sys.exit("Not long enough ton contain payment hash and channel id")
+    # 32 bytes turns into 52 bytes when base32 encoded.
+    if len(data) < 52:
+        sys.exit("Not long enough to contain payment hash")
-    decoded = convertbits(data[:64], 5, 8, False)
-    data = data[64:]
-    assert len(decoded) == 32 + 8
-    print("Payment hash: {}".format(bytearray(decoded[0:32]).hex()))
-    print("Channel id: {}".format(bytearray(decoded[32:40]).hex()))
+    decoded = convertbits(data[:52], 5, 8, False)
+    data = data[52:]
+    assert len(decoded) == 32
+    print("Payment hash: {}".format(bytearray(decoded).hex()))
     while len(data) > 0:
         tag,tagdata,data = pull_tagged(data)
@@ -297,7 +288,6 @@ parser_enc.add_argument('--description-hashed',
                         help='What is being purchased (for hashing)')
 parser_enc.add_argument('amount', type=int, help='Amount in millisatoshi')
 parser_enc.add_argument('paymenthash', help='Payment hash (in hex)')
-parser_enc.add_argument('channelid', help='Channel id (in hex)')
 parser_enc.add_argument('privkey', help='Private key (in hex)')
 parser_enc.set_defaults(func=lnencode)
Rusty Russell in reply to Olaoluwa Osuntokun permalink original

Olaoluwa Osuntokun <laolu32 at gmail.com> writes:

Quoted text (4 lines)
> However, it utilizes an
> encoding whose rationale make sense for the Bitcoin address use-case, but in
> my opinion, doesn't carry over those compelling traits to the LN payreq
> use-case.

I agree, but it's nice for QR codes too, and denser than hex. And now we're using your key recovery idea, having a checksum is not *completely* pointless.

I've implemented and pushed fallback addresses in the example encoder/decoder, and tweaked the format slightly: the first 5-bit value is the witness version, or 17 for p2pkh, 18 for p2sh. It's now complete.

In some places the encoding is a little awkward (trying to get on 5 bit boundaries), ideas welcome.

<Feedback please! Rusty.

Christian Decker in reply to Rusty Russell permalink original

I mentioned some things off-list before but let me add them here for completeness.

My biggest concern was the use of `short_channel_id` as an alias for the endpoint, it just felt wrong having to perform that lookup to get a space saving. This is all the more strange since the remainder of the spec is very generous with space, allowing arbitrary (up to 1024 byte) string descriptions and similar. So good job at removing it, even if it was only as a fallback or hint.

I also don't like the amount shorthands (k/m/g/...), that's purely a UI/UX concern and since these invoices are not user-readable I don't see the point. Even if they were user-readable, we'd be forcing people to do the conversion BTC -> SAT on their own, since we would not support amount in bitcoin units (BTC, mBTC, ...). I'd say either get rid of the shorthands or add the BTC shorthands as well.

Other than that, I really like the proposal, it's clean and extensible, and it supports testnet ;-) I also like using bech32 as a serialization format, if people also support the DNS bootstrapping and node lookup they can simply reuse that dependency, and it is a bit shorter than hex. We might consider also supporting a different, human readable, encoding though (without changing the signature serialization). And finally we could directly derive a URI scheme from the bech32 encoded string by replacing the '1' with a ':', but we can spin that discussion off in another thread ^^

Cheers, Christian

On Sat, May 06, 2017 at 01:38:47PM +0930, Rusty Russell wrote:

Quoted text (24 lines)
> Olaoluwa Osuntokun <laolu32 at gmail.com> writes:
> > However, it utilizes an
> > encoding whose rationale make sense for the Bitcoin address use-case, but in
> > my opinion, doesn't carry over those compelling traits to the LN payreq
> > use-case.
>
> I agree, but it's nice for QR codes too, and denser than hex.  And now
> we're using your key recovery idea, having a checksum is not
> *completely* pointless.
>
> I've implemented and pushed fallback addresses in the example
> encoder/decoder, and tweaked the format slightly: the first 5-bit value
> is the witness version, or 17 for p2pkh, 18 for p2sh.  It's now
> complete.
>
> In some places the encoding is a little awkward (trying to get on 5 bit
> boundaries), ideas welcome.
>
> <Feedback please!
> Rusty.
> _______________________________________________
> Lightning-dev mailing list
> Lightning-dev at lists.linuxfoundation.org
> https://www.learnbitcoin.com/archive/lists/lightning-dev
Rusty Russell in reply to Christian Decker permalink original

Christian Decker <decker.christian at gmail.com> writes:

Quoted text (6 lines)
> I also don't like the amount shorthands (k/m/g/...), that's purely a
> UI/UX concern and since these invoices are not user-readable I don't
> see the point. Even if they were user-readable, we'd be forcing people
> to do the conversion BTC -> SAT on their own, since we would not
> support amount in bitcoin units (BTC, mBTC, ...). I'd say either get
> rid of the shorthands or add the BTC shorthands as well.

Hey, invoices are totally human readable, for some humans :)

But a good point. So let's use BTC with m (milli), u (micro), n (nano) and p (pico). In theory we could allow . in that part, but I think it's too distracting.

At $1600/BTC:

        0.01c = 62500p
        1c = 6250n
        $1 = 625u
        $1000 = 625m
Quoted text (9 lines)
> Other than that, I really like the proposal, it's clean and
> extensible, and it supports testnet ;-) I also like using bech32 as a
> serialization format, if people also support the DNS bootstrapping and
> node lookup they can simply reuse that dependency, and it is a bit
> shorter than hex. We might consider also supporting a different, human
> readable, encoding though (without changing the signature
> serialization). And finally we could directly derive a URI scheme from
> the bech32 encoded string by replacing the '1' with a ':', but we can
> spin that discussion off in another thread ^^

OK, if people like this change, I think we can move start turning this into BOLT 10?

Thanks! Rusty.

Christian Decker in reply to Rusty Russell permalink original

On Tue, May 09, 2017 at 11:07:28AM +0930, Rusty Russell wrote:

Quoted text (2 lines)
> Hey, invoices are totally human readable, for some humans :)
>

I know Pieter can decode bech32 on the fly :-)

Quoted text (10 lines)
> But a good point.  So let's use BTC with m (milli), u (micro), n (nano)
> and p (pico).  In theory we could allow . in that part, but I think it's
> too distracting.
>
> At $1600/BTC:
>
>         0.01c = 62500p
>         1c = 6250n
>         $1 = 625u
>         $1000 = 625m

Perfect, even though your price is already outdated, and it currently is $1700/BTC. I mention the conversion confusion because I often run into that problem myself (and keep typing 0s until the client complains).

Quoted text (12 lines)
> > Other than that, I really like the proposal, it's clean and
> > extensible, and it supports testnet ;-) I also like using bech32 as a
> > serialization format, if people also support the DNS bootstrapping and
> > node lookup they can simply reuse that dependency, and it is a bit
> > shorter than hex. We might consider also supporting a different, human
> > readable, encoding though (without changing the signature
> > serialization). And finally we could directly derive a URI scheme from
> > the bech32 encoded string by replacing the '1' with a ':', but we can
> > spin that discussion off in another thread ^^
>
> OK, if people like this change, I think we can move start turning this
> into BOLT 10?

Oops, I think I did what Luke hates, and sort of self assigned a proposal number... I can of course assign the DNS bootstrap BOLT another number.

Cheers, Christian

Rusty Russell in reply to Christian Decker permalink original

Christian Decker <decker.christian at gmail.com> writes:

Quoted text (4 lines)
> On Tue, May 09, 2017 at 11:07:28AM +0930, Rusty Russell wrote:
>> Hey, invoices are totally human readable, for some humans :)
>>
> I know Pieter can decode bech32 on the fly :-)

Well, Pieter can pronounce them too apparently:

        http://pieterwuillefacts.com/?43
Quoted text (15 lines)
>> But a good point.  So let's use BTC with m (milli), u (micro), n (nano)
>> and p (pico).  In theory we could allow . in that part, but I think it's
>> too distracting.
>>
>> At $1600/BTC:
>>
>>         0.01c = 62500p
>>         1c = 6250n
>>         $1 = 625u
>>         $1000 = 625m
>
> Perfect, even though your price is already outdated, and it currently
> is $1700/BTC. I mention the conversion confusion because I often run
> into that problem myself (and keep typing 0s until the client
> complains).

I considered using the m/u/n modifier as the decimal point, eg:

         0.0001c = 0n62
         0.01c = 62n5
         1c = 6u25
         $1 = 625u
         $1000 = 625m

Unfortunately, it's horrible to write the code to encode/decode (I just spend an hour on it and I'm not happy with the result).

Quoted text (6 lines)
>> OK, if people like this change, I think we can move start turning this
>> into BOLT 10?
>
> Oops, I think I did what Luke hates, and sort of self assigned a
> proposal number... I can of course assign the DNS bootstrap BOLT
> another number.

Huh? I just did exactly the same thing! So I'll take BOLT 11.

Cheers, Rusty.

Olaoluwa Osuntokun in reply to Rusty Russell permalink original

Rusty wrote:

Quoted text (2 lines)
> Yes, I thought about this too, but I'm reluctant to assign those onion
> bytes as they're a limited resource.  Easy to add later, though.

If y'all recall, the initial version of the Sphinx derived onion format included an end-to-end payload. In the first revision, removed this payload as at the time it was very large (1KB iirc), an at the time, we didn't see nay clear use case for such a payload (and also due to MTU constraints?). In my opinion, we should re-introduce this payload so we aren't put into a corner where we need to shave bytes off of the per-hop payload in order to accommodate application level schemes/apps.

Re-introducing the e2e payload would allow us to define a strict separation of layers: h2h payload is reserved for _forwarding_ critical information, while the e2e payload is reserved for _applications_ to place relevant data which is also onion encrypted + authenticated. IMO, the e2e payload doesn't need to be any where as large at it was previously (which doubled the size of the onion packet). I'd proposed re-introducing it with a size of somewhere around 200 bytes. With this, I could send you something to tweet once the payment has been extended :p.

Fabrice wrote:

Quoted text (3 lines)
> Payment requests should also include a timestamp and an expiry date (they
> could be optional tagged items but I think it makes more sense to make
> them mandatory)

Agreed that that would make for a really useful tag. I had a user which was making a store on lnd request such a feature as his use-case depended on users only having a particular time window to make the payment. This could of course be enforced server side, but allow senders to enforce it at the origin of the payment saves them from extending an HTLC all together. Also in the world of pre-paying for HTLC's, you'd only want to extend an HTLC is you had a high degree of certainty that it'll be claimed, otherwise you've just wasted your precious mSAT :(.

Rusty wrote:

Quoted text (1 line)
> Note: we will lose this ability when we switch to Schnorr, apparently.

AFAIK, this isn't the case. With Schnorr signatures (that include the entire point, instead of the hash), we actually won't need to include a recovery ID at all.

Rusty wrote:

Quoted text (2 lines)
> OK, if people like this change, I think we can move start turning this
> into BOLT 10?

Let's do it (BOLT 11)! As were all getting pretty close to the stage of cross-implementation interoperability tests, having a shared payment request format will be super useful.

Christian wrote:

Quoted text (2 lines)
> Perfect, even though your price is already outdated, and it currently
> is $1700/BTC

Perfect, even through your price is already outdated, and it currently is $2200/BTC :p.

-- Laolu

On Tue, May 9, 2017 at 10:18 PM Rusty Russell <rusty at rustcorp.com.au> wrote:

Quoted text (53 lines)
> Christian Decker <decker.christian at gmail.com> writes:
> > On Tue, May 09, 2017 at 11:07:28AM +0930, Rusty Russell wrote:
> >> Hey, invoices are totally human readable, for some humans :)
> >>
> > I know Pieter can decode bech32 on the fly :-)
>
> Well, Pieter can pronounce them too apparently:
>
>         http://pieterwuillefacts.com/?43
>
> >> But a good point.  So let's use BTC with m (milli), u (micro), n (nano)
> >> and p (pico).  In theory we could allow . in that part, but I think it's
> >> too distracting.
> >>
> >> At $1600/BTC:
> >>
> >>         0.01c = 62500p
> >>         1c = 6250n
> >>         $1 = 625u
> >>         $1000 = 625m
> >
> > Perfect, even though your price is already outdated, and it currently
> > is $1700/BTC. I mention the conversion confusion because I often run
> > into that problem myself (and keep typing 0s until the client
> > complains).
>
> I considered using the m/u/n modifier as the decimal point, eg:
>
>          0.0001c = 0n62
>          0.01c = 62n5
>          1c = 6u25
>          $1 = 625u
>          $1000 = 625m
>
> Unfortunately, it's horrible to write the code to encode/decode (I just
> spend an hour on it and I'm not happy with the result).
>
> >> OK, if people like this change, I think we can move start turning this
> >> into BOLT 10?
> >
> > Oops, I think I did what Luke hates, and sort of self assigned a
> > proposal number... I can of course assign the DNS bootstrap BOLT
> > another number.
>
> Huh?  I just did exactly the same thing!  So I'll take BOLT 11.
>
> Cheers,
> Rusty.
> _______________________________________________
> Lightning-dev mailing list
> Lightning-dev at lists.linuxfoundation.org
> https://www.learnbitcoin.com/archive/lists/lightning-dev
>
Rusty Russell in reply to Olaoluwa Osuntokun permalink original

Olaoluwa Osuntokun <laolu32 at gmail.com> writes:

Quoted text (11 lines)
> Rusty wrote:
>> Yes, I thought about this too, but I'm reluctant to assign those onion
>> bytes as they're a limited resource.  Easy to add later, though.
>
> If y'all recall, the initial version of the Sphinx derived onion format
> included an end-to-end payload. In the first revision, removed this
> payload as at the time it was very large (1KB iirc), an at the time, we
> didn't see nay clear use case for such a payload (and also due to MTU
> constraints?). In my opinion, we should re-introduce this payload so we
> aren't put into a corner where we need to shave bytes off of the per-hop
> payload in order to accommodate application level schemes/apps.

Unfortunately people want this for mid-points, too, to do weird crazy shit. But it's trivial for us to extend to a "multi-cell" format in future, so I'm tempted by the default of "no change"?

Quoted text (11 lines)
> Fabrice wrote:
>> Payment requests should also include a timestamp and an expiry date (they
>> could be optional tagged items but I think it makes more sense to make
>> them mandatory)
>
> Agreed that that would make for a really useful tag. I had a user which
> was making a store on lnd request such a feature as his use-case depended
> on users only having a particular time window to make the payment. This
> could of course be enforced server side, but allow senders to enforce it
> at the origin of the payment saves them from extending an HTLC all
> together.

Agreed. Latest version has a UTC timestamp, and expiry time (defaults to 1 hour if not specified). As you say, must be server-enforced too, but it's nice to make it clear to the user (and it's signed in case of dispute).

Quoted text (6 lines)
> Rusty wrote:
>> Note: we will lose this ability when we switch to Schnorr, apparently.
>
> AFAIK, this isn't the case. With Schnorr signatures (that include the
> entire point, instead of the hash), we actually won't need to include a
> recovery ID at all.

Quoting a private conversation with Pieter Wuille, when I asked him about it:

        You can't.
        At least, if you follow modern practices (which make the signature hash
        commit to the public key), you can't do pubkey recovery.
        It *is* possible (and safe, I think) to commit to the pubkeyhash
        rather than the pubkey directly, in which case you can verify a
        (signature, pubkeyhash, msg) triplet.
        I think you can use a 128-bit pubkey hash, actually.
Quoted text (7 lines)
> Rusty wrote:
>> OK, if people like this change, I think we can move start turning this
>> into BOLT 10?
>
> Let's do it (BOLT 11)! As were all getting pretty close to the stage of
> cross-implementation interoperability tests, having a shared payment
> request format will be super useful.

OK, I'll start typing...

Thanks! Rusty.