Skip to content
LearnBitcoin

ResearchBitcoin Dev Archive lightning-dev list

Laundry list of inter-peer wire protocol changes

19 messages, Jan 27 to Apr 12, 2016. Started by Rusty Russell.

Rusty Russell (10), CJP (5), Anthony Towns (2), Mats Jerratsch, Fabrice Drouin

Permalink First message in the Wayback Machine

Rusty Russell permalink original

Hi all!

        As more code emerges, I'd like to try to nail down a "1.0"
version of the inter-node protocol as much as possible.  Since I'm most
familiar with my own code (c-lightning[1]), I'll use that as a basis and
discuss differences (esp. vs lnd[2]).

For this email I'll simply list the changes or proposals I'm aware of, then we can dissect and comment on each one: defer, accept or close.

Direct wire format stuff ------------------------

- Protobufs vs open-coded structures
  - lnd open-coded their own protocol; I haven't finished reading their
    code though.
  - protobufs are easy to extend with new fields; with an open-coded
    proto we simply need a rule that too-long packets are valid.
  - protobufs are annoying for fixed-length blobs which we use a lot
    (keys, signatures, hashes).
  - The protocol is currently simple with very few variable-length fields.
- Length prefix for initial key exchange
  - Both lnd and c-lightning begin by exchanging a 33-byte EC key for DH.
  - We should prefix with a length word, so we can extend this later
    (eg. for new crypto)
- Length prefix for other packets
  - lightning-c sends an 8 byte prefix indicating the offset of the end of
    the current packet: this effectively encodes both length and ordering.
  - lnd uses a 4 byte network ID, 4 byte type, 4 byte length.
- HTLC pipelining
  - lnd's protocol supports multiple in-flight HTLC negotiations; this
    would allow much greater throughput, with some complexity.
  - lightning-c uses a simple one-at-a-time scheme, with alternating
    priority in case of simultaneous sends.
- HTLC abort stage
  - Setting up a new HTLC involves both sides accepting, then revocation
    message exchange.  Currently there's no way to abort this process.
  - Allow the initator to abort any time before the revocation exchange,
    for weird corner cases such as timeouts.
- Version bits
  - If we use an open-coded protocol, initial handshake after key setup
    should exchange two sets of version bits: one for compulsory
    features, one for optional features.  You hang up if there's a
    compulsory feature you don't grok.
Wire protocol crypto
--------------------
- Crypto AES/HMAC-SHA256 or Chacha20/Poly1305
  - AES has the word Standard in the name, but chacha20 is faster w/o
    accel (ie. ARM) and almost as widely supported.
- Use separate encoding stream for packet lengths
  - Laolu's suggestion; encode the packet lengths as well which makes
    traffic analysis a bit harder.
  - Makes it a bit harder to detect re-transmissions (required on node
    restart), but probably not enough to kill the idea?
Misc
----
- shachain vs elkrem
  - We use this to generate the revocation secrets, to minimize storage
    and computation for a huge number of old commitment txs.
  - They're actually very similar, but elkrem is much easier to grok.[6]
- Anchor tx renegotiation
  - We should allow re-anchoring of channels, to add or remove funds.
      - This would allow easy payment from lightning channel to normal
        bitcoin addresses, for example.
  - During transition, signatures for both commit txs must be exchanged.
- R value vs keypair
  - Using a simple secret "redeemhash" allows easy tracing of
    transactions through the network.
  - Mats Jeratsch proposed a keypair scheme which decorrelates them[3],
    Greg Maxwell optimized it slightly, and Anthony Towns[4] and Andrew
    Poelstra independently came up with a way to do it without any
    bitcoin mods.
- Multi-sig txs
  - Joseph pointed out that by simply allowing more than one signature on
    commit txs[5], we can enable escrow-style services (including things
    like GreenAddress.it which does this for normal wallets).

I'm sure I've missed things; what are they?

Thanks! Rusty.

[1] https://github.com/ElementsProject/lightning
[2] https://github.com/LightningNetwork/lnd
[3] https://www.learnbitcoin.com/archive/lists/lightning-dev/t/2015/better-privacy-with-snarks#m-195e00d3
[4] https://www.learnbitcoin.com/archive/lists/lightning-dev/t/2015/better-privacy-with-snarks#m-b54ec279
[5] https://www.learnbitcoin.com/archive/lists/lightning-dev/t/2016/2-of-3-instant-escrow-or-how-to-do-2-of-3-multisig-contract-equivalent-on#m-75503a0b
[6] https://github.com/LightningNetwork/lnd/blob/master/elkrem/elkrem.go
Mats Jerratsch in reply to Rusty Russell permalink original

Great point Rusty, given how many implementations are emerging, we should press more for compatibility.

Before making comments, just a quick reminder that everyone is invited in cloning

https://github.com/lightning-core/lightning

and writing up their specifications so others do not have to search through code, plus separating code from design is good practice. It will also be easier to commit to them once the discussion is done.

Quoted text (3 lines)
> For this email I'll simply list the changes or proposals I'm aware
> of, then we can dissect and comment on each one: defer, accept or
> close.

I am so free and add changes from TN :)

Quoted text (11 lines)
>
> Direct wire format stuff ------------------------
>
> - Protobufs vs open-coded structures - lnd open-coded their own
> protocol; I haven't finished reading their code though. - protobufs
> are easy to extend with new fields; with an open-coded proto we
> simply need a rule that too-long packets are valid. - protobufs are
> annoying for fixed-length blobs which we use a lot (keys,
> signatures, hashes). - The protocol is currently simple with very
> few variable-length
fields.

- - TN currently is using JSON encoded objects. It is by no standard efficient, but allows for easy integration of other systems and it's easy to extend/modify.

Right now I think the open-coded messaging is a bit too much. You don't get the efficiency of protobufs, nor the readibility of JSON, but still have to manually code each serialisation/deserialisation, and each change to the messages has to be carefully inserted into these functions.

I still don't think JSON is a bad choice for the beginning. If it actually turns out to be a bottleneck it is a very low-hanging fruit.

I would rather adapt something like protobufs if it comes to it. (I heard there are other *bufs, maybe some of these serve us better?)

Quoted text (5 lines)
> - Length prefix for initial key exchange - Both lnd and c-lightning
> begin by exchanging a 33-byte EC key
for DH.
> - We should prefix with a length word, so we can extend this later
> (eg. for new crypto)

Agree, same on TN.

Won't new crypto be non-compatibily anyways?

Quoted text (6 lines)
> - Length prefix for other packets - lightning-c sends an 8 byte
> prefix indicating the offset of the
end of
> the current packet: this effectively encodes both length and
ordering.
> - lnd uses a 4 byte network ID, 4 byte type, 4 byte length.

- - TN uses 4 byte length, type is JSON encoded (message types are completely taken care of of GSON)

I agree that a network ID prefix might make sense. Probably worth designing for an equivalent of testnet (and they should not just differ by the standard port they run on... )

Quoted text (5 lines)
>
> - HTLC pipelining - lnd's protocol supports multiple in-flight HTLC
> negotiations; this would allow much greater throughput, with some
> complexity. - lightning-c uses a simple one-at-a-time scheme, with
> alternating priority in case of simultaneous sends.

- - TN allows for adding / settling / refunding arbitrary amount of HTLCs at the same time.

Agree with lnd here, the complexity is worth it IMO.

Quoted text (5 lines)
> - HTLC abort stage - Setting up a new HTLC involves both sides
> accepting, then revocation message exchange.  Currently there's no
> way to abort this process. - Allow the initator to abort any time
> before the revocation exchange, for weird corner cases such as
> timeouts.

- - TN allows for any party to start a new exchange to abort the current one. I adapted the dice-rolling from CJP, in case both initiate at the same time. - - It is important be careful with revocation hashes when aborting. You don't want the other party to hold on to an unrevoked tx...

Quoted text (5 lines)
>
> - Version bits - If we use an open-coded protocol, initial
> handshake after key setup should exchange two sets of version bits:
> one for compulsory features, one for optional features.  You hang
> up if there's a compulsory feature you don't grok.

Good point, agree here.

Quoted text (15 lines)
> Wire protocol crypto -------------------- - Crypto AES/HMAC-SHA256
> or Chacha20/Poly1305 - AES has the word Standard in the name, but
> chacha20 is faster w/o accel (ie. ARM) and almost as widely
> supported.
>
> - Use separate encoding stream for packet lengths - Laolu's
> suggestion; encode the packet lengths as well which makes traffic
> analysis a bit harder. - Makes it a bit harder to detect
> re-transmissions (required on node restart), but probably not
> enough to kill the idea?
>
> Misc ---- - shachain vs elkrem - We use this to generate the
> revocation secrets, to minimize storage and computation for a huge
> number of old commitment txs. - They're actually very similar, but
> elkrem is much easier to grok.[6]

TBD on TN, they both sound solid, I agree with elkrem being easier to implement.

Quoted text (6 lines)
>
> - Anchor tx renegotiation - We should allow re-anchoring of
> channels, to add or remove funds. - This would allow easy payment
> from lightning channel to normal bitcoin addresses, for example. -
> During transition, signatures for both commit txs must be
> exchanged.

This sounds like a 1.1 feature. Agree that we should allow it, but does not seem urgent right now.

Quoted text (6 lines)
> - R value vs keypair - Using a simple secret "redeemhash" allows
> easy tracing of transactions through the network. - Mats Jeratsch
> proposed a keypair scheme which decorrelates them[3], Greg Maxwell
> optimized it slightly, and Anthony Towns[4] and Andrew Poelstra
> independently came up with a way to do it without any bitcoin
> mods.

Currently I am using R value, I am still a bit afraid of the lengthy scripts when doing it without bitcoin mods. Might make sense to just design the system in a way that it's easy to change later than to implement it already.

Quoted text (7 lines)
> - Multi-sig txs - Joseph pointed out that by simply allowing more
> than one
signature on
> commit txs[5], we can enable escrow-style services (including
> things like GreenAddress.it which does this for normal wallets).
>
> I'm sure I've missed things; what are they?

Would be great to discuss connection/node failures. TN currently does not support 'picking up' a lost connection again. I feel like anything that MUST be finished on resume should rather be saved on hard disk in advance, designing for various node failure modes. Restarting a fresh connection seems to be much cleaner for me?

Cheers - -- Mats Jerratsch Backend Engineer, Blockchain e: mats.jerratsch at blockchain.com PGP: https://pgp.mit.edu/pks/lookup?op=get&search=0x7F3EC6CA

Anthony Towns in reply to Rusty Russell permalink original

On Wed, Jan 27, 2016 at 01:37:04PM +1030, Rusty Russell wrote:

Quoted text (6 lines)
> Misc
> ----
> - shachain vs elkrem
>   - We use this to generate the revocation secrets, to minimize storage
>     and computation for a huge number of old commitment txs.
>   - They're actually very similar, but elkrem is much easier to grok.[6]

Hmm, I was going to say I like it, but I'm not sure I do...

The comments in the code don't quite make sense to me, for instance, the given examples:

0b0000: L(L(L(L(seed)))) 0b0001: R(L(L(L(seed)))) 0b1000: L(L(L(seed)))

should be 0, 1 and 2, I think, not 0, 1 and 8; and with four hash operations, you've got 31 nodes not 15, and 16 leaves, not 8?

I think the pattern is:

0b0000: LLL (ie L(L(L(seed))) 0b0001: RLL (ie R(L(L(seed))) 0b0010: LL -> (0, 1) 0b0011: LRL 0b0100: RRL 0b0101: RL -> (3, 4) 0b0110: L -> (0, 1, 2, 3, 4, 5) 0b0111: LLR 0b1000: RLR 0b1001: LR -> (7, 8) 0b1010: LRR 0b1011: RRR 0b1100: RR -> (10, 11) 0b1101: R -> (7, 8, 9, 10, 11, 12) 0b1110: seed -> (0,..,13)

(Running the code translated into python gives those results too)

I don't the code is quite right either (though I may have translated something wrong); eg if I try calling:

  descend(6, 13, 2, R(seed))

I get

  L(L(R(seed)))

instead of an error (since the right answer would be L(seed), which can't be derived from R(seed)).

Personally, I think both this and shachain have the indexing backwards; I think i=0 should match the seed, and the first hash transmitted across the wire should be i=2^64-1, then counting down from there. This matches the numbering used in https://en.wikipedia.org/wiki/Hash_chain fwiw.

With shachain, that gives the nice property that the only parameter you need is the seed, you can work out the hash for any given index directly from that, up to any arbitrary index, until you run out of integer precision, or bits of security in your hash function.

With elkrem you can build an arbitrarily deep tree given a seed at the conceptual level without any further parameters, but when you start mapping that to indexes you need to know the desired height first. This is, in essence, because L(seed) (eg) gets sent at different places depending on the "height"; with a height of 1 it's the first value (or third from last), with a height of 2 it's the third value (or fifth from last), with a height of 3 it's the seventh value (or ninth from last), etc.

Probably doesn't really matter, but I think it leads me to prefer Rusty's construction. Might be good to have an explanation with it diagrammed as an n-way tree structure though, in a similar way to how you visualise the elkrem tree...

Quoted text (7 lines)
> - R value vs keypair
>   - Using a simple secret "redeemhash" allows easy tracing of
>     transactions through the network.
>   - Mats Jeratsch proposed a keypair scheme which decorrelates them[3],
>     Greg Maxwell optimized it slightly, and Anthony Towns[4] and Andrew
>     Poelstra independently came up with a way to do it without any
>     bitcoin mods.

FWIW I think this should still be considered an R&D idea rather than trying to release it in v1.0.

Quoted text (4 lines)
> - Multi-sig txs
>   - Joseph pointed out that by simply allowing more than one signature on
>     commit txs[5], we can enable escrow-style services (including things
>     like GreenAddress.it which does this for normal wallets).

It's "more than one hash" not more than one /signature/, isn't it? (The proposal was also to support 2-of-3 hashes, slightly more complicated than just multiple hashes)

Cheers, aj

CJP in reply to Rusty Russell permalink original
Quoted text (1 line)
> I'm sure I've missed things; what are they?

The lazy answer is to tell you to read the Amiko Pay protocol description.[1] :-P Note that it is (of course) already outdated. To give you some of the concept choices in there:

* Transport layer: TCP. We don't need its retransmission features (since it's not good enough and we'll re-implement it in a higher layer), but unlike UDP it works well over TOR. * Serialization: JSON, with some conventions added on top of it, e.g. for more efficient transfer of binary data. It is bloated, but easily debuggable and easily extensible. Good for prototypes, maybe not so good for high-performance production code. * Message confirmation: this is done manually (instead of relying on TCP), so that a node knows which messages were received / need to be re-transmitted, even after a crash + restart. * There is not only two-way communication between linked peers, but also between payer and payee. This is necessary for Amiko Pay's bi-directional routing, but also useful e.g. for transmitting meta-data that doesn't fit in a QR code. Amiko Pay transmits an arbitrary-contents "receipt" from payee to payer; in the future, this might be digitally signed by the payee, as a "proof of transfer of ownership" of non-cryptographic goods. * Bi-directional routing: both payer and payee route towards a "meeting point". This way, neither payer nor payee has to have a routable address on the network. This is good for both payer and payee privacy; also, in case of a semi-centralized network with a couple of large hubs, this allows the network to grow without the large hubs noticing it, both in payer and in payee direction. * Multiple channels per link: useful to be able to route transactions the usual way while one of the channels is (temporarily) closed. It's also the easy way of adding more funds to an existing link, or funds from both sides. * Different channel classes: the micro-transaction design, and its implications on what info needs to be transferred in which situations, is a separate, higher-level protocol layer on top of a more generic protocol that takes care of routing. * Reserving before locking: this is an optimization, to reduce the risk of locking funds in payment channels on a part of the route, and then having to undo the locking when it turns out that the remaining part of the route doesn't exist (anymore). Reserving is an informal(*), temporary locking of funds for use in the transaction, and can be done and undone very fast, without any channel operations. It is done together with route searching + establishment.

CJP

PS. Don't trust a protocol spec that doesn't have an implementation, since it's probably missing a couple of essential things. Don't use an implementation that doesn't have a protocol spec, since you're likely to run into future compatibility issues.

(*)informal = without cryptographic commitment, and without actual channel update.

[1]https://github.com/cornwarecjp/lightning/tree/cornwarecjp/communications

CJP in reply to Rusty Russell permalink original

There are a couple of subjects where new concepts are being worked out, or where alternative concepts exist; these things are likely to continue to evolve after you finish the first version of the protocol.

It would be great if concept changes in one subject can be made more or less independently from concept changes in another subject. In order to make this possible, I suggest to de-couple certain things, and let each subject have its own sub-protocol, with version number / protocol identifier.

The way I see it, the following subjects have ongoing design / alternative concepts, more or less independently from each other:

* Micro-transaction channel design: e.g. several variations on the Lightning channel design, and Amiko Pay's escrow-based HTLC emulation and IOU semi-channel. * Commit conditions: traditional definition consists of a hash value and a time-out. For practical purposes, Amiko Pay also adds a "start time", and there is an alternative concept of using keypairs instead of hash values to de-correlate a transaction in different links. * Routing: how to exchange routing info. For source routing: informing each other about Lightning nodes that exist. For source and non-source routing: informing each other about availability of routes, expected capacity and fees. The type of routing info depends on the routing algorithm in use by a node.

In Amiko Pay, the micro-transaction channel design is already separated from the rest of the protocol; commit conditions are not (yet), and exchange of routing info doesn't really exist yet, since it's still doing "dumb" non-source routing (trying every possible route).

CJP

Rusty Russell schreef op wo 27-01-2016 om 13:37 [+1030]:

Quoted text (103 lines)
> Hi all!
>
>         As more code emerges, I'd like to try to nail down a "1.0"
> version of the inter-node protocol as much as possible.  Since I'm most
> familiar with my own code (c-lightning[1]), I'll use that as a basis and
> discuss differences (esp. vs lnd[2]).
>
> For this email I'll simply list the changes or proposals I'm aware of,
> then we can dissect and comment on each one: defer, accept or close.
>
> Direct wire format stuff
> ------------------------
>
> - Protobufs vs open-coded structures
>   - lnd open-coded their own protocol; I haven't finished reading their
>     code though.
>   - protobufs are easy to extend with new fields; with an open-coded
>     proto we simply need a rule that too-long packets are valid.
>   - protobufs are annoying for fixed-length blobs which we use a lot
>     (keys, signatures, hashes).
>   - The protocol is currently simple with very few variable-length fields.
>
> - Length prefix for initial key exchange
>   - Both lnd and c-lightning begin by exchanging a 33-byte EC key for DH.
>   - We should prefix with a length word, so we can extend this later
>     (eg. for new crypto)
>
> - Length prefix for other packets
>   - lightning-c sends an 8 byte prefix indicating the offset of the end of
>     the current packet: this effectively encodes both length and ordering.
>   - lnd uses a 4 byte network ID, 4 byte type, 4 byte length.
>
> - HTLC pipelining
>   - lnd's protocol supports multiple in-flight HTLC negotiations; this
>     would allow much greater throughput, with some complexity.
>   - lightning-c uses a simple one-at-a-time scheme, with alternating
>     priority in case of simultaneous sends.
>
> - HTLC abort stage
>   - Setting up a new HTLC involves both sides accepting, then revocation
>     message exchange.  Currently there's no way to abort this process.
>   - Allow the initator to abort any time before the revocation exchange,
>     for weird corner cases such as timeouts.
>
> - Version bits
>   - If we use an open-coded protocol, initial handshake after key setup
>     should exchange two sets of version bits: one for compulsory
>     features, one for optional features.  You hang up if there's a
>     compulsory feature you don't grok.
>
> Wire protocol crypto
> --------------------
> - Crypto AES/HMAC-SHA256 or Chacha20/Poly1305
>   - AES has the word Standard in the name, but chacha20 is faster w/o
>     accel (ie. ARM) and almost as widely supported.
>
> - Use separate encoding stream for packet lengths
>   - Laolu's suggestion; encode the packet lengths as well which makes
>     traffic analysis a bit harder.
>   - Makes it a bit harder to detect re-transmissions (required on node
>     restart), but probably not enough to kill the idea?
>
> Misc
> ----
> - shachain vs elkrem
>   - We use this to generate the revocation secrets, to minimize storage
>     and computation for a huge number of old commitment txs.
>   - They're actually very similar, but elkrem is much easier to grok.[6]
>
> - Anchor tx renegotiation
>   - We should allow re-anchoring of channels, to add or remove funds.
>       - This would allow easy payment from lightning channel to normal
>         bitcoin addresses, for example.
>   - During transition, signatures for both commit txs must be exchanged.
>
> - R value vs keypair
>   - Using a simple secret "redeemhash" allows easy tracing of
>     transactions through the network.
>   - Mats Jeratsch proposed a keypair scheme which decorrelates them[3],
>     Greg Maxwell optimized it slightly, and Anthony Towns[4] and Andrew
>     Poelstra independently came up with a way to do it without any
>     bitcoin mods.
>
> - Multi-sig txs
>   - Joseph pointed out that by simply allowing more than one signature on
>     commit txs[5], we can enable escrow-style services (including things
>     like GreenAddress.it which does this for normal wallets).
>
> I'm sure I've missed things; what are they?
>
> Thanks!
> Rusty.
>
> [1] https://github.com/ElementsProject/lightning
> [2] https://github.com/LightningNetwork/lnd
> [3] https://www.learnbitcoin.com/archive/lists/lightning-dev/t/2015/better-privacy-with-snarks#m-195e00d3
> [4] https://www.learnbitcoin.com/archive/lists/lightning-dev/t/2015/better-privacy-with-snarks#m-b54ec279
> [5] https://www.learnbitcoin.com/archive/lists/lightning-dev/t/2016/2-of-3-instant-escrow-or-how-to-do-2-of-3-multisig-contract-equivalent-on#m-75503a0b
> [6] https://github.com/LightningNetwork/lnd/blob/master/elkrem/elkrem.go
> _______________________________________________
> Lightning-dev mailing list
> Lightning-dev at lists.linuxfoundation.org
> https://www.learnbitcoin.com/archive/lists/lightning-dev
Rusty Russell in reply to Mats Jerratsch permalink original

Mats Jerratsch <mats.jerratsch at blockchain.com> writes:

Quoted text (5 lines)
> https://github.com/lightning-core/lightning
>
> and writing up their specifications so others do not have to search
> through code, plus separating code from design is good practice. It
> will also be easier to commit to them once the discussion is done.

ACK.

Quoted text (4 lines)
>> For this email I'll simply list the changes or proposals I'm aware
>> of, then we can dissect and comment on each one: defer, accept or
>> close.
> I am so free and add changes from TN :)

Fantastic, thanks.

Quoted text (19 lines)
>> Direct wire format stuff ------------------------
>>
>> - Protobufs vs open-coded structures - lnd open-coded their own
>> protocol; I haven't finished reading their code though. - protobufs
>> are easy to extend with new fields; with an open-coded proto we
>> simply need a rule that too-long packets are valid. - protobufs are
>> annoying for fixed-length blobs which we use a lot (keys,
>> signatures, hashes). - The protocol is currently simple with very
>> few variable-length
> fields.
> - - TN currently is using JSON encoded objects. It is by no standard
> efficient, but allows for easy integration of other systems and
> it's easy to extend/modify.
>
> Right now I think the open-coded messaging is a bit too much. You
> don't get the efficiency of protobufs, nor the readibility of JSON,
> but still have to manually code each serialisation/deserialisation,
> and each change to the messages has to be carefully inserted into
> these functions.

I'm extremely reluctant to use JSON for wire formats beyond prototyping; I really prefer formats where there is only one possible representation of any given message, and where parsing is as trivial as possible.

I would be generating my serialization code anyway, ideally from some spec document directly.

I'll hack up a binary protocol and see if it lines up into nice, neatly packed structs. I can write you a JSON translation layer if you want :)

Quoted text (5 lines)
> I still don't think JSON is a bad choice for the beginning. If it
> actually turns out to be a bottleneck it is a very low-hanging fruit.
>
> I would rather adapt something like protobufs if it comes to it. (I
> heard there are other *bufs, maybe some of these serve us better?)

Unfortunately the other contender (Capnproto) doesn't fix our worst pain point either, which is fixed-size blobs.

Quoted text (8 lines)
>> - Length prefix for initial key exchange - Both lnd and c-lightning
>> begin by exchanging a 33-byte EC key
> for DH.
>> - We should prefix with a length word, so we can extend this later
>> (eg. for new crypto)
> Agree, same on TN.
>
> Won't new crypto be non-compatibily anyways?

The length word makes it backwards compatible. If you see extra data, you know they're using crypto v2, and ignore the old key.

Quoted text (12 lines)
>> - Length prefix for other packets - lightning-c sends an 8 byte
>> prefix indicating the offset of the
> end of
>> the current packet: this effectively encodes both length and
> ordering.
>> - lnd uses a 4 byte network ID, 4 byte type, 4 byte length.
> - - TN uses 4 byte length, type is JSON encoded (message types are
> completely taken care of of GSON)
>
> I agree that a network ID prefix might make sense. Probably worth
> designing for an equivalent of testnet (and they should not just
> differ by the standard port they run on... )

Definitely in the original handshake, but on every packet seems a bit extreme?

Quoted text (8 lines)
>> - HTLC pipelining - lnd's protocol supports multiple in-flight HTLC
>> negotiations; this would allow much greater throughput, with some
>> complexity. - lightning-c uses a simple one-at-a-time scheme, with
>> alternating priority in case of simultaneous sends.
> - - TN allows for adding / settling / refunding arbitrary amount of
> HTLCs at the same time.
>
> Agree with lnd here, the complexity is worth it IMO.

OK. There are a few ways of doing it. Any change is a 4-step process, "offer, accept, sig+oldrevocation, sig+oldrevocation" (though my protocol put the last sig in the accept, that is ugly and wrong, see below).

So simplest is to tag each one with what HTLC it's talking about: lnd introduces 64 bit HTLCs ids to optimize this. IIUC for clarity, one party uses even ids, the other odd, counting in order.

If you want to batch signing as well, so you can say "I include everything up to change #N, here's the signature", we'd skip the HTLC id and use an incrementing offer id. But I think this step is overkill?

Quoted text (8 lines)
>> - HTLC abort stage - Setting up a new HTLC involves both sides
>> accepting, then revocation message exchange.  Currently there's no
>> way to abort this process. - Allow the initator to abort any time
>> before the revocation exchange, for weird corner cases such as
>> timeouts.
> - - TN allows for any party to start a new exchange to abort the
> current one. I adapted the dice-rolling from CJP, in case both
> initiate at the same time.

If we allow parallel negotiation, we don't need a priority scheme I think? But we do need an explicit abort.

Quoted text (2 lines)
> - - It is important be careful with revocation hashes when aborting.
> You don't want the other party to hold on to an unrevoked tx...

I think you really want to send the old revocation hash and the sig for the new tx together. At that point, aborting is no longer possible and you have to cancel through normal means...

ie. You can send "add this please", and then "abort that".

Quoted text (6 lines)
>> - Version bits - If we use an open-coded protocol, initial
>> handshake after key setup should exchange two sets of version bits:
>> one for compulsory features, one for optional features.  You hang
>> up if there's a compulsory feature you don't grok.
>
> Good point, agree here.

OK, I'll add.

Quoted text (8 lines)
>> - Anchor tx renegotiation - We should allow re-anchoring of
>> channels, to add or remove funds. - This would allow easy payment
>> from lightning channel to normal bitcoin addresses, for example. -
>> During transition, signatures for both commit txs must be
>> exchanged.
>
> This sounds like a 1.1 feature. Agree that we should allow it, but
> does not seem urgent right now.

Agreed; stuff we can defer is good....

Quoted text (11 lines)
>> - R value vs keypair - Using a simple secret "redeemhash" allows
>> easy tracing of transactions through the network. - Mats Jeratsch
>> proposed a keypair scheme which decorrelates them[3], Greg Maxwell
>> optimized it slightly, and Anthony Towns[4] and Andrew Poelstra
>> independently came up with a way to do it without any bitcoin
>> mods.
>
> Currently I am using R value, I am still a bit afraid of the lengthy
> scripts when doing it without bitcoin mods. Might make sense to just
> design the system in a way that it's easy to change later than to
> implement it already.

Yes, everyone is on R AFAIK. This might be worth deferring, if only because it raises the interesting question on how we would do the upgrade (every node on your path needs to understand the new version).

Quoted text (13 lines)
>> - Multi-sig txs - Joseph pointed out that by simply allowing more
>> than one
> signature on
>> commit txs[5], we can enable escrow-style services (including
>> things like GreenAddress.it which does this for normal wallets).
>>
>> I'm sure I've missed things; what are they?
>
> Would be great to discuss connection/node failures. TN currently does
> not support 'picking up' a lost connection again. I feel like anything
> that MUST be finished on resume should rather be saved on hard disk in
> advance, designing for various node failure modes.
> Restarting a fresh connection seems to be much cleaner for me?

Yes, TBA for me too.

There should be a new crypto handshake, then the conversation should continue as before.

This means you need to save state, and also tolerate limited amount of identical re-transmission. My plan for c-lightning was to hand this at a layer between the state machine and cryptopkt: if we see a retransmission we replay our previous responses. My current state machine could theoretically send out 4 packets in a row after receiving one (decline, propose new, close, error), but this would be more if we allow multiple parallel change negotiations.

Cheers, Rusty.

Rusty Russell in reply to Anthony Towns permalink original

Anthony Towns <aj at erisian.com.au> writes:

Quoted text (4 lines)
> Personally, I think both this and shachain have the indexing backwards;
> I think i=0 should match the seed, and the first hash transmitted across
> the wire should be i=2^64-1, then counting down from there. This matches
> the numbering used in https://en.wikipedia.org/wiki/Hash_chain fwiw.

OK.

Quoted text (8 lines)
> With shachain, that gives the nice property that the only parameter
> you need is the seed, you can work out the hash for any given index
> directly from that, up to any arbitrary index, until you run out of
> integer precision, or bits of security in your hash function.
>
> With elkrem you can build an arbitrarily deep tree given a seed at the
> conceptual level without any further parameters, but when you start
> mapping that to indexes you need to know the desired height first.

We can just say "64 bits is enough for everyone", and be done.

Quoted text (10 lines)
> This is, in essence, because L(seed) (eg) gets sent at different places
> depending on the "height"; with a height of 1 it's the first value (or
> third from last), with a height of 2 it's the third value (or fifth
> from last), with a height of 3 it's the seventh value (or ninth from
> last), etc.
>
> Probably doesn't really matter, but I think it leads me to prefer Rusty's
> construction. Might be good to have an explanation with it diagrammed
> as an n-way tree structure though, in a similar way to how you visualise
> the elkrem tree...

Definitely; a 64-deep binary tree is a 64-dimensional 1x1...x1 hypercube, but the former is less brainhurty.

Quoted text (19 lines)
>> - R value vs keypair
>>   - Using a simple secret "redeemhash" allows easy tracing of
>>     transactions through the network.
>>   - Mats Jeratsch proposed a keypair scheme which decorrelates them[3],
>>     Greg Maxwell optimized it slightly, and Anthony Towns[4] and Andrew
>>     Poelstra independently came up with a way to do it without any
>>     bitcoin mods.
>
> FWIW I think this should still be considered an R&D idea rather than
> trying to release it in v1.0.
>
>> - Multi-sig txs
>>   - Joseph pointed out that by simply allowing more than one signature on
>>     commit txs[5], we can enable escrow-style services (including things
>>     like GreenAddress.it which does this for normal wallets).
>
> It's "more than one hash" not more than one /signature/, isn't it? (The
> proposal was also to support 2-of-3 hashes, slightly more complicated
> than just multiple hashes)

You're right, it's multiple hashes. Which gives me an idea I'll post separately.

Thanks! Rusty.

Rusty Russell in reply to CJP permalink original

CJP <cjp at ultimatestunts.nl> writes:

Quoted text (9 lines)
>> I'm sure I've missed things; what are they?
>
> The lazy answer is to tell you to read the Amiko Pay protocol
> description.[1] :-P Note that it is (of course) already outdated. To
> give you some of the concept choices in there:
>
> * Transport layer: TCP. We don't need its retransmission features (since
> it's not good enough and we'll re-implement it in a higher layer), but
> unlike UDP it works well over TOR.

Agreed. I've implemented TCP for the moment, but am not making any assumptions about it for protocol design.

Quoted text (4 lines)
> * Serialization: JSON, with some conventions added on top of it, e.g.
> for more efficient transfer of binary data. It is bloated, but easily
> debuggable and easily extensible. Good for prototypes, maybe not so good
> for high-performance production code.

Agreed. I think I'd like something better for a protocol definition, but it's nice for prototyping.

Quoted text (3 lines)
> * Message confirmation: this is done manually (instead of relying on
> TCP), so that a node knows which messages were received / need to be
> re-transmitted, even after a crash + restart.

I think the protocol itself needs to be robust against retransmissions. There's no way to know if the other side received your acknowledgement before a crash, so you will always need to handle duplication on re-establishment.

Quoted text (7 lines)
> * There is not only two-way communication between linked peers, but also
> between payer and payee. This is necessary for Amiko Pay's
> bi-directional routing, but also useful e.g. for transmitting meta-data
> that doesn't fit in a QR code. Amiko Pay transmits an arbitrary-contents
> "receipt" from payee to payer; in the future, this might be digitally
> signed by the payee, as a "proof of transfer of ownership" of
> non-cryptographic goods.

I agree. There's room in the initial onion design for payer -> payee messages, but we don't have a channel for responses.

I can't see an easy way to implement the payee --> payer comms reliably: to be reliable it would have to be published on-chain in the commit tx. (Which we could do by constructing HTLCs such that they require a blob signed by the payee, but that's tracable ...).

Mats and Laolu wanted to add an arbitrary comms protocol layer, but I think that's something we can defer.

Quoted text (6 lines)
> * Bi-directional routing: both payer and payee route towards a "meeting
> point". This way, neither payer nor payee has to have a routable address
> on the network. This is good for both payer and payee privacy; also, in
> case of a semi-centralized network with a couple of large hubs, this
> allows the network to grow without the large hubs noticing it, both in
> payer and in payee direction.

Yes, I've totally punted on routing and fees. This idea merges well with the idea of randomly selecting a handful of "beacons", which I've toyed with in the past.

Quoted text (4 lines)
> * Multiple channels per link: useful to be able to route transactions
> the usual way while one of the channels is (temporarily) closed. It's
> also the easy way of adding more funds to an existing link, or funds
> from both sides.

For the moment this is done with separate connections, though it would be fairly trivial to multiplex over a single transport.

Quoted text (4 lines)
> * Different channel classes: the micro-transaction design, and its
> implications on what info needs to be transferred in which situations,
> is a separate, higher-level protocol layer on top of a more generic
> protocol that takes care of routing.

Yes, and we can't really finalize the lower-level implementation until we have the upper parts anyway...

Quoted text (7 lines)
> * Reserving before locking: this is an optimization, to reduce the risk
> of locking funds in payment channels on a part of the route, and then
> having to undo the locking when it turns out that the remaining part of
> the route doesn't exist (anymore). Reserving is an informal(*),
> temporary locking of funds for use in the transaction, and can be done
> and undone very fast, without any channel operations. It is done
> together with route searching + establishment.

I think that trades one DoS for another, though. It saves cryptographic constructs, but latency is the real cost, and this increases it.

Of course, we'll have to revisit that if the network in practice proves subject to these problems...

Quoted text (4 lines)
> PS. Don't trust a protocol spec that doesn't have an implementation,
> since it's probably missing a couple of essential things. Don't use an
> implementation that doesn't have a protocol spec, since you're likely to
> run into future compatibility issues.

Rough consensus and running code, indeed.

Thanks, Rusty.

Anthony Towns in reply to Rusty Russell permalink original

On Fri, Jan 29, 2016 at 12:05:35PM +1030, Rusty Russell wrote:

Quoted text (6 lines)
> > Probably doesn't really matter, but I think it leads me to prefer Rusty's
> > construction. Might be good to have an explanation with it diagrammed
> > as an n-way tree structure though, in a similar way to how you visualise
> > the elkrem tree...
> Definitely; a 64-deep binary tree is a 64-dimensional 1x1...x1
> hypercube, but the former is less brainhurty.

Nono, you don't need hypercubes to describe shachain, just a tree. Voila:

[attached]

(Okay, so technically it's a spanning tree for a hypercube, fine, whatever. I guess you can kind-of see the outline of the 4d hypercube in the picture if you look hard enough...)

In the notation I'm using, H(p||x) means "flip the xth bit from the
parent hash/seed then hash" [0]. So to get to the hash for 10 you do:
   SHA256( SHA256( seed with bit 3 flipped ) with bit 1 flipped )
The subtrees are all very self-similar, and extending past 2**n just means
adding a new branch off from 0. Because it's so self-similar adding the
branch is just literally copying the existing tree, adding 2**n to all the
node values, and then adding a H(p||n) step from 0 to keep it connected.

Python code for generating the graph also attached, for whatever that's worth. Layout gets a bit painful when you add an additional dimension to get up to 32 nodes.

Cheers, aj

[0] Or, alternatively and IMO preferably, append the number "x" and
    hash.
Rusty Russell in reply to CJP permalink original

CJP <cjp at ultimatestunts.nl> writes:

Quoted text (12 lines)
> There are a couple of subjects where new concepts are being worked out,
> or where alternative concepts exist; these things are likely to continue
> to evolve after you finish the first version of the protocol.
>
> It would be great if concept changes in one subject can be made more or
> less independently from concept changes in another subject. In order to
> make this possible, I suggest to de-couple certain things, and let each
> subject have its own sub-protocol, with version number / protocol
> identifier.
>
> The way I see it, the following subjects have ongoing design /
> alternative concepts, more or less independently from each other:

Indeed!

Quoted text (3 lines)
> * Micro-transaction channel design: e.g. several variations on the
> Lightning channel design, and Amiko Pay's escrow-based HTLC emulation
> and IOU semi-channel.

Yes, for lightning I would further split this into wire crypto, wire protocol, anchoring and fee design, and commit transaction design.

Quoted text (4 lines)
> * Commit conditions: traditional definition consists of a hash value and
> a time-out. For practical purposes, Amiko Pay also adds a "start time",
> and there is an alternative concept of using keypairs instead of hash
> values to de-correlate a transaction in different links.

Good point. I think of this as a sub-part of transaction design, but it's logically a separable issue.

Quoted text (5 lines)
> * Routing: how to exchange routing info. For source routing: informing
> each other about Lightning nodes that exist. For source and non-source
> routing: informing each other about availability of routes, expected
> capacity and fees. The type of routing info depends on the routing
> algorithm in use by a node.

There are several topology issues:

1) Source-routing format (aka. onion design).
2) Route and fee broadcast and finding (eg. How do I find a route to X
   where all nodes support keypair commitments?).
3) Initial node finding (how do I find a node to create channels to?)
Quoted text (4 lines)
> In Amiko Pay, the micro-transaction channel design is already separated
> from the rest of the protocol; commit conditions are not (yet), and
> exchange of routing info doesn't really exist yet, since it's still
> doing "dumb" non-source routing (trying every possible route).

In c-lightning, routing is separate because it doesn't exist yet :)

Cheers, Rusty.

Fabrice Drouin in reply to Rusty Russell permalink original

On 27 January 2016 at 04:07, Rusty Russell <rusty at rustcorp.com.au> wrote:

Quoted text (22 lines)
>
> Hi all!
>
>         As more code emerges, I'd like to try to nail down a "1.0"
> version of the inter-node protocol as much as possible.  Since I'm most
> familiar with my own code (c-lightning[1]), I'll use that as a basis and
> discuss differences (esp. vs lnd[2]).
>
> For this email I'll simply list the changes or proposals I'm aware of,
> then we can dissect and comment on each one: defer, accept or close.
>
> Direct wire format stuff
> ------------------------
>
> - Protobufs vs open-coded structures
>   - lnd open-coded their own protocol; I haven't finished reading their
>     code though.
>   - protobufs are easy to extend with new fields; with an open-coded
>     proto we simply need a rule that too-long packets are valid.
>   - protobufs are annoying for fixed-length blobs which we use a lot
>     (keys, signatures, hashes).
>   - The protocol is currently simple with very few variable-length fields.

Hello,

We (Pierre and I, the guys who work on the scala thingy :-) would rather use a "standard" binary format and protobuf seems to be a very good choice. Since incoming messages are encrypted, text based formats (JSON, ...) would not help that much for debugging and are not imho a good fit for binary protocols.

Quoted text (4 lines)
> - Length prefix for initial key exchange
>   - Both lnd and c-lightning begin by exchanging a 33-byte EC key for DH.
>   - We should prefix with a length word, so we can extend this later
>     (eg. for new crypto)

Agreed.

Quoted text (5 lines)
> - HTLC pipelining
>   - lnd's protocol supports multiple in-flight HTLC negotiations; this
>     would allow much greater throughput, with some complexity.
>   - lightning-c uses a simple one-at-a-time scheme, with alternating
>     priority in case of simultaneous sends.

Just to be sure that we understand this, you mean grouping HTLCs and sending them with one message (so just one signature will be exchanged). It becomes more complex for clients because they will have to buffer and group incoming HTLCs but the protocol and the transitions remain pretty much the same ?

Quoted text (6 lines)
> Misc
> ----
> - shachain vs elkrem
>   - We use this to generate the revocation secrets, to minimize storage
>     and computation for a huge number of old commitment txs.
>   - They're actually very similar, but elkrem is much easier to grok.[6]

I like both, they're easy to implement and elkrem was indeed much easier to understand. I don't know precisely why yet but I would choose shachain though.

Cheers, Fabrice

Rusty Russell in reply to Fabrice Drouin permalink original

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

Quoted text (8 lines)
> On 27 January 2016 at 04:07, Rusty Russell <rusty at rustcorp.com.au> wrote:
> Hello,
>
> We (Pierre and I, the guys who work on the scala thingy :-) would
> rather use a "standard" binary format and protobuf seems to be a very
> good choice. Since incoming messages are encrypted, text based formats
> (JSON, ...) would not help that much for debugging and are not imho a
> good fit for binary protocols.

Well, I'm thinking of providing a binary which will do the crypto and provide a (generated) JSON interface. That will keep the JSON people happy, separate out the crypto and wire-protocol issues, and generally give one less thing to worry about. I can also keep it up to date as we debate formats...

Quoted text (17 lines)
>> - Length prefix for initial key exchange
>>   - Both lnd and c-lightning begin by exchanging a 33-byte EC key for DH.
>>   - We should prefix with a length word, so we can extend this later
>>     (eg. for new crypto)
> Agreed.
>
>> - HTLC pipelining
>>   - lnd's protocol supports multiple in-flight HTLC negotiations; this
>>     would allow much greater throughput, with some complexity.
>>   - lightning-c uses a simple one-at-a-time scheme, with alternating
>>     priority in case of simultaneous sends.
>
> Just to be sure that we understand this, you mean grouping HTLCs and
> sending them with one message (so just one signature will be
> exchanged). It becomes more complex for clients because they will have
> to buffer and group incoming HTLCs but the protocol and the
> transitions remain pretty much the same ?

I haven't got a description of lnd's protocol, but I've been thinking about it. We can certainly be more optimal than the 4 trips per change we have now (amortized).

See the other thread "Protocol for multiple in-flight updates.".

Quoted text (9 lines)
>> Misc
>> ----
>> - shachain vs elkrem
>>   - We use this to generate the revocation secrets, to minimize storage
>>     and computation for a huge number of old commitment txs.
>>   - They're actually very similar, but elkrem is much easier to grok.[6]
> I like both, they're easy to implement and elkrem was indeed much
> easier to understand. I don't know precisely why yet but I would
> choose shachain though.

I have to write up a better explanation of shachain. And as AJ points out, it should be defined in the other direction to be more like chains in the literature, so seed is index 0, first value is index 2^64-1...

Cheers, Rusty.

CJP in reply to Rusty Russell permalink original
Quoted text (8 lines)
> > * Message confirmation: this is done manually (instead of relying on
> > TCP), so that a node knows which messages were received / need to be
> > re-transmitted, even after a crash + restart.
>
> I think the protocol itself needs to be robust against retransmissions.
> There's no way to know if the other side received your acknowledgement
> before a crash, so you will always need to handle duplication on
> re-establishment.

Yes. Amiko Pay does that: It assigns a number to every message, and the receiving side can confirm "I've received up to this number". Not-yet-confirmed messages will be retransmitted, and the receiving sides will ignore duplicates (except it will send a confirmation again, in case the previous confirmation was lost).

Quoted text (18 lines)
> > * There is not only two-way communication between linked peers, but also
> > between payer and payee. This is necessary for Amiko Pay's
> > bi-directional routing, but also useful e.g. for transmitting meta-data
> > that doesn't fit in a QR code. Amiko Pay transmits an arbitrary-contents
> > "receipt" from payee to payer; in the future, this might be digitally
> > signed by the payee, as a "proof of transfer of ownership" of
> > non-cryptographic goods.
>
> I agree.  There's room in the initial onion design for payer -> payee
> messages, but we don't have a channel for responses.
>
> I can't see an easy way to implement the payee --> payer comms reliably:
> to be reliable it would have to be published on-chain in the commit tx.
> (Which we could do by constructing HTLCs such that they require a blob
> signed by the payee, but that's tracable ...).
>
> Mats and Laolu wanted to add an arbitrary comms protocol layer, but I
> think that's something we can defer.

In Amiko Pay, payer <-> payee communication is done on a direct TCP stream between them. Note that this also reduces latency: once transaction locking reaches the payee, the payee knows (s)he's capable of claiming the money, and can tell the payer that the payment is completed. If reduced latency is in the interest of the payee, this is likely to happen.

Quoted text (13 lines)
> > * Reserving before locking: this is an optimization, to reduce the risk
> > of locking funds in payment channels on a part of the route, and then
> > having to undo the locking when it turns out that the remaining part of
> > the route doesn't exist (anymore). Reserving is an informal(*),
> > temporary locking of funds for use in the transaction, and can be done
> > and undone very fast, without any channel operations. It is done
> > together with route searching + establishment.
>
> I think that trades one DoS for another, though.  It saves cryptographic
> constructs, but latency is the real cost, and this increases it.
>
> Of course, we'll have to revisit that if the network in practice proves
> subject to these problems...

For one category of channel designs, reserving is absolutely essential: channels where bi-directional payments are made possible with a decrementing lock time. There, you want to make sure that failed routing attempts don't cause lock time decrements, since that would reduce the channel lifetime more than necessary. I'd have to check whether there is still any use case for this channel design, and whether the reserving step is important for some other reason.

Note that reserving is necessary for bi-directional routing: on the payee side of the meeting point, routing happens in the payee -> meeting point direction, but locking has to happen in the meeting point -> payee direction. So, they have to be different steps.

On latency: what latency do you think is needed for different use cases, and what can we reach? Does this extra step really make a difference?

My estimate is that we'll typically have 10 hops ("six degrees of separation" theory), and 100ms to transmit a message(*) over one hop.

Without reserving, you need to traverse all hops once(**) (the locking operation) before payer(***)+payee know that the transaction has succeeded. Actual settlement on the channels happens afterwards, but is no longer critical for the latency as seen by payer+payee.

With reserving, you need to traverse all hops three times(**), in the worst case that the meeting point is on one of the end points of the route: once for making the route and reserving funds, once for confirming that the route has been established and once for locking.

So, instead of one second, a transaction might take three seconds. Is that a game changer? Maybe it is for e.g. public transport access gates, where passenger throughput is essential. But then, people could reduce latency a lot by having a direct channel with the public transport operator.

For some use cases, e.g. high-frequency trading, people might of course manually optimize their network and physical location to get better figures than this.

CJP

(*) Not counting sending the confirmation back: a node that receives a message can immediately forward a message on the next hop; message confirmation on the receiving side can occur in parallel.

(**) Not counting failed routing attempts

(***) Assuming the payee tells the payer directly about the payment succes, over a low-latency connection

Rusty Russell in reply to CJP permalink original

CJP <cjp at ultimatestunts.nl> writes:

Quoted text (14 lines)
>> > * Message confirmation: this is done manually (instead of relying on
>> > TCP), so that a node knows which messages were received / need to be
>> > re-transmitted, even after a crash + restart.
>>
>> I think the protocol itself needs to be robust against retransmissions.
>> There's no way to know if the other side received your acknowledgement
>> before a crash, so you will always need to handle duplication on
>> re-establishment.
>
> Yes. Amiko Pay does that: It assigns a number to every message, and the
> receiving side can confirm "I've received up to this number".
> Not-yet-confirmed messages will be retransmitted, and the receiving
> sides will ignore duplicates (except it will send a confirmation again,
> in case the previous confirmation was lost).

Yes, I think packet numbers make sense. I encoded the packet length and order in one single value (ie. byte counter at the end of this packet), but it's too weird for too little gain IMHO.

Quoted text (25 lines)
>> > * There is not only two-way communication between linked peers, but also
>> > between payer and payee. This is necessary for Amiko Pay's
>> > bi-directional routing, but also useful e.g. for transmitting meta-data
>> > that doesn't fit in a QR code. Amiko Pay transmits an arbitrary-contents
>> > "receipt" from payee to payer; in the future, this might be digitally
>> > signed by the payee, as a "proof of transfer of ownership" of
>> > non-cryptographic goods.
>>
>> I agree.  There's room in the initial onion design for payer -> payee
>> messages, but we don't have a channel for responses.
>>
>> I can't see an easy way to implement the payee --> payer comms reliably:
>> to be reliable it would have to be published on-chain in the commit tx.
>> (Which we could do by constructing HTLCs such that they require a blob
>> signed by the payee, but that's tracable ...).
>>
>> Mats and Laolu wanted to add an arbitrary comms protocol layer, but I
>> think that's something we can defer.
>
> In Amiko Pay, payer <-> payee communication is done on a direct TCP
> stream between them. Note that this also reduces latency: once
> transaction locking reaches the payee, the payee knows (s)he's capable
> of claiming the money, and can tell the payer that the payment is
> completed. If reduced latency is in the interest of the payee, this is
> likely to happen.

I think for v1.0 of the protocol we'll be assuming such a channel for simplicity; that somehow the R hash and route is known by the payer.

Quoted text (5 lines)
> On latency: what latency do you think is needed for different use cases,
> and what can we reach? Does this extra step really make a difference?
>
> My estimate is that we'll typically have 10 hops ("six degrees of
> separation" theory), and 100ms to transmit a message(*) over one hop.

...

Quoted text (3 lines)
> (*) Not counting sending the confirmation back: a node that receives a
> message can immediately forward a message on the next hop; message
> confirmation on the receiving side can occur in parallel.

That's a good point; you can offer the next hop and abort if the prior hop fails to deliver a signature. Nice, my estimates were double yours...

Quoted text (15 lines)
> Without reserving, you need to traverse all hops once(**) (the locking
> operation) before payer(***)+payee know that the transaction has
> succeeded. Actual settlement on the channels happens afterwards, but is
> no longer critical for the latency as seen by payer+payee.
>
> With reserving, you need to traverse all hops three times(**), in the
> worst case that the meeting point is on one of the end points of the
> route: once for making the route and reserving funds, once for
> confirming that the route has been established and once for locking.
>
> So, instead of one second, a transaction might take three seconds. Is
> that a game changer? Maybe it is for e.g. public transport access gates,
> where passenger throughput is essential. But then, people could reduce
> latency a lot by having a direct channel with the public transport
> operator.

I worry that higher latency is a centralization pressure, and encourages people to sacrifice privacy. I don't know where the threshold is, though, so currently I'm more nervous about complexity :)

Cheers, Rusty.

CJP in reply to Rusty Russell permalink original

Hi,

I've had another look at C-Lightning protocol description[1], in the hope to make a sort of match between your message types and the message types in Amiko Pay. In the best case, there would be a near-perfect match; in the worst case, the entire sequence would be different (unlikely, since we try to accomplish similar things).

The result was a bit unexpected: there was hardly any match at all, but this was not due to solving things in different ways, but because of implementing nearly opposite subsets of the functionality of Lightning.

In Amiko Pay, the core protocol is mostly concerned with multiplexing multiple channels of potentially different types, opening/closing channels, doing a little bit of routing and following the payment sequences (reserving/route finding, route canceling, fund locking, fund releasing etc.). Channel implementation details, such as what messages to exchange in case of opening/closing a channel, or in the different steps of a transaction, depend on the different channel types, and no Lightning-style channel type has yet been implemented.

On the other hand, the C-Lightning protocol description basically *only* deals with the channel implementation details (what data is exchanged in case of opening/closing a channel, or in the different steps of a transaction). I don't see much about routing, for instance. The C-lightning message structures would be perfect to put inside Amiko Pay's ChannelMessage messages, and together they would make a more complete protocol.

To make a (pretty weak) analogy: maybe you can see C-Lightning's protocol as a fundamental building block of Lightning networks, in the same way as you can see bi-directional byte streams as a fundamental building block of computer networks. Then, the 'raw' protocol used by C-lightning would be a bit like a serial point-to-point connection, and C-lightning inside Amiko Pay would be a bit like a TCP/IP connection. They deliver the same core functionality on application level, but TCP/IP, being more layered, provides more versatility. It adds multiplexing of different streams, and alternative communication concepts (e.g. UDP).

For me, this was a bit of an eye-opener, though I should have expected it, from what I know about C-Lightning. C-Lightning's protocol description will be a nice guide for developing a true Lightning style channel in Amiko Pay. Judging the development time and lines of code in C-lightning, I guess the part that is implemented in C-lightning has quite a bit of complexity, so I hope to build on Rusty's experience and expertise, to do things a bit faster in Amiko Pay. I'd like to use some C-lightning code as well, but I doubt it will be easy to integrate (Amiko Pay is quite a restrictive framework for channel implementations, and we have a language barrier between C and Python). Maybe we could start with a 'dirty hack'-style of gluing things together, for a proof of concept.

CJP

[1] https://github.com/ElementsProject/lightning/blob/master/lightning.proto

Rusty Russell in reply to CJP permalink original

CJP <cjp at ultimatestunts.nl> writes:

Quoted text (11 lines)
> Hi,
>
> I've had another look at C-Lightning protocol description[1], in the
> hope to make a sort of match between your message types and the message
> types in Amiko Pay. In the best case, there would be a near-perfect
> match; in the worst case, the entire sequence would be different
> (unlikely, since we try to accomplish similar things).
>
> The result was a bit unexpected: there was hardly any match at all, but
> this was not due to solving things in different ways, but because of
> implementing nearly opposite subsets of the functionality of Lightning.

Indeed! I kind of like that we're approaching from opposite ends, it means we can steal off each other.

Quoted text (7 lines)
> For me, this was a bit of an eye-opener, though I should have expected
> it, from what I know about C-Lightning. C-Lightning's protocol
> description will be a nice guide for developing a true Lightning style
> channel in Amiko Pay. Judging the development time and lines of code in
> C-lightning, I guess the part that is implemented in C-lightning has
> quite a bit of complexity, so I hope to build on Rusty's experience and
> expertise, to do things a bit faster in Amiko Pay.

Yes. I'm right now reworking it to do the update pipelining, and it's removed some of the complexity. But it's not complete yet, so some might come back :)

I'm off on paternity leave for a couple of weeks, but I've pushed my unworking code to the multi-htlc branch, so you can see the changes in the protocol as per my email to the list.

https://github.com/ElementsProject/lightning/tree/multi-htlc

Cheers! Rusty.

Rusty Russell in reply to Anthony Towns permalink original

Anthony Towns <aj at erisian.com.au> writes:

Quoted text (9 lines)
> On Wed, Jan 27, 2016 at 01:37:04PM +1030, Rusty Russell wrote:
>> Misc
>> ----
>> - shachain vs elkrem
>>   - We use this to generate the revocation secrets, to minimize storage
>>     and computation for a huge number of old commitment txs.
>>   - They're actually very similar, but elkrem is much easier to grok.[6]
>
> Hmm, I was going to say I like it, but I'm not sure I do...

OK, I revisited shachain; it's nicer to describe in terms of a binary tree. The derivation is still a little complex, but people should find this far less brainbendy.

And yes, I reversed the indices, so we start with 0xFFFFFFFFFFFFFFFF and work back towards the seed at 0.

Quoted text (1 line)
>From https://github.com/rustyrussell/ccan/blob/master/ccan/crypto/shachain/design.txt:

A Tree Solution ---------------

A better solution is to use a binary tree, with the seed at the root. The left child is the same as the parent, the right child is the SHA256() of the parent with one bit flipped (corresponding to the height).

This gives a tree like so:

                      seed
                    /      \
                  /          \
                /              \
              /                  \
            seed                   SHA256(seed^1)
           /    \                  /             \
       seed    SHA256(seed^2)  SHA256(seed^1)  SHA256(SHA256(seed^1)^2)
Index:  0         1                2                  3

Clearly, giving R(2) allows you to derive R(3), giving R(1) allows you to derive nothing new (you still have to remember R(2)), and giving R(0) allows you to derive everything.

In pseudocode, this looks like the following for a 64 bit tree:

generate_from_seed(index):
    value = seed
    for bit in 0 to 63:
        if bit set in index:
            flip(bit) in value
            value = SHA256(value)
    return value

The Receiver's Tree -------------------

To derive the value for a index N, you need to have the root of a tree which contains it. That is the same as needing an index I which is N rounded down in binary: eg. if N is 0b001100001, you need 0b001100000, 0b001000000 or 0b000000000.

Pseudocode:

# Can we derive the value for to_index from from_index?
can_derive(from_index, to_index):
    # to_index must be a subtree under from_index; this is the same as
    # saying that to_index must be the same as from_index up to the
    # trailing zeros in from_index.
    for bit in count_trailing_zeroes(from_index)..63:
        if bit set in from_index != bit set in to_index:
            return false
    return true
# Derive a value from a lesser index: generalization of generate_from_seed()
derive(from_index, to_index, from_value):
    assert(can_derive(from_index, to_index))
    value = from_value
    for bit in 0..63:
        if bit set in to_index and not bit set in from_index:
            flip bit in value
            value = SHA256(value)
    return value

If you are receiving values (in reverse order), you need to remember up to 64 of them to derive all previous values. The simplest method is to keep an array, indexed by the number of trailing zeroes in the received index:

# Receive a new value (assumes we receive them in order)
receive_value(index, value):
    pos = count_trailing_zeroes(index)
    # We should be able to generate every lesser value, otherwise invalid
    for i in 0..pos-1:
       if derive(index, value, known[i].index) != known[i].value:
            return false
    known[pos].index = index
    known[pos].value = value
    return true

To derive a previous value, find an element in that array from which you can derive the value you want, eg:

# Find an old value
regenerate_value(index):
    for i in known:
        if can_derive(i.index, index):
            return derive(i.index, i.value, index)
    fail

You can see the implementation for more optimized variants of the above code.

Rusty Russell <rusty at rustcorp.com.au>

CJP in reply to CJP permalink original

CJP schreef op di 02-02-2016 om 18:56 [+0100]:

Quoted text (22 lines)
>
> > > * Reserving before locking: this is an optimization, to reduce the risk
> > > of locking funds in payment channels on a part of the route, and then
> > > having to undo the locking when it turns out that the remaining part of
> > > the route doesn't exist (anymore). Reserving is an informal(*),
> > > temporary locking of funds for use in the transaction, and can be done
> > > and undone very fast, without any channel operations. It is done
> > > together with route searching + establishment.
> >
> > I think that trades one DoS for another, though.  It saves cryptographic
> > constructs, but latency is the real cost, and this increases it.
> >
> > Of course, we'll have to revisit that if the network in practice proves
> > subject to these problems...
>
> For one category of channel designs, reserving is absolutely essential:
> channels where bi-directional payments are made possible with a
> decrementing lock time. There, you want to make sure that failed routing
> attempts don't cause lock time decrements, since that would reduce the
> channel lifetime more than necessary. I'd have to check whether there is
> still any use case for this channel design, and whether the reserving
> step is important for some other reason.

After actually implementing some of these things, I'd like to revisit this discussion.

The "reserving" stage used to be important for channel types where the bi-directional nature of the channel is realized with decreasing lock times (see above). Now that a large part of the community has put its hope on Lightning, it's more likely that the extensions required for better channel types will be included in Bitcoin, so this issue has become less important.

Another reason why the "reserving" stage is important, is that it it necessary for bi-directional routing. In order to make both payer and payee anonymous, we need to provide this feature, where both route to a meeting point. For the part between meeting point and payee, routing goes from payee to meeting point(*), but locking goes from meeting point to payee, so they can't be done in the same stage.

Finally, the "reserving" stage allows you to set a tighter value on the HTLC time-outs. If you do routing together with locking, then routing has to go in the payer->payee direction; the time-out has to be reduced on every hop. Assuming(**) the payer doesn't know the number of hops in advance, the time-out has to be set to a very high value by the payer, to maximize chances of a successful transaction. If you do routing in the reverse direction (payee->payer), you can start with a very low time-out, and increment it on every hop. This will generally result in lower time-out values, which is desirable.

That's about it, for the advantages offered by the separate reserving stage in Amiko Pay. Let me finish with an attempt to make an ASCII-art sequence diagram of reserving, bi-directional routing and locking in Amiko Pay:

H(R) = the transaction hash (also included in other messages) MR() = MakeRoute message without time info MR(t) = MakeRoute message with time info HR() = HaveRoute message without time info HR(t) = HaveRoute message L(t) = Lock message (adds HTLC to channel) A = Alice (payer) B = Bob (meeting point) C = Carol (intermediate node). There can be many intermediate nodes between A and B, and between B and D. D = Dave (payee)

A               B               C             D
|<------------------ H(R) --------------------|
|------MR()---->|               |<-MR(T0+dt)--|
                |<-MR(T0+2*dt)--|
|<-HR(T0+3*dt)--|--HR(T0+2*dt)->|
                                |--HR(T0+dt)->|
|<------------------ HR() --------------------|
|--L(T0+3*dt)-->|--L(T0+2*dt)-->|--L(T0+dt)-->|

(...and then the sequence continues with removing the HTLCs and releasing funds towards payee-side of each channel.)

CJP

(*) It can't go in the other direction, since the meeting point should not know the identity (or network address) of the payee.

(**) This is the case for non-source routing. One advantage of non-source routing is that nodes don't need a map of the entire network; this improves privacy, and could help to keep the network open to new participants, even against the will of many powerful existing participants. In the end, I imagine a system where a mix of source-routing and non-source routing can be used, to get the best of both worlds.

Rusty Russell in reply to CJP permalink original

"C.J. Plooy" <cjplooy at ultimatestunts.nl> writes:

Quoted text (40 lines)
> CJP schreef op di 02-02-2016 om 18:56 [+0100]:
>>
>> > > * Reserving before locking: this is an optimization, to reduce the risk
>> > > of locking funds in payment channels on a part of the route, and then
>> > > having to undo the locking when it turns out that the remaining part of
>> > > the route doesn't exist (anymore). Reserving is an informal(*),
>> > > temporary locking of funds for use in the transaction, and can be done
>> > > and undone very fast, without any channel operations. It is done
>> > > together with route searching + establishment.
>> >
>> > I think that trades one DoS for another, though.  It saves cryptographic
>> > constructs, but latency is the real cost, and this increases it.
>> >
>> > Of course, we'll have to revisit that if the network in practice proves
>> > subject to these problems...
>>
>> For one category of channel designs, reserving is absolutely essential:
>> channels where bi-directional payments are made possible with a
>> decrementing lock time. There, you want to make sure that failed routing
>> attempts don't cause lock time decrements, since that would reduce the
>> channel lifetime more than necessary. I'd have to check whether there is
>> still any use case for this channel design, and whether the reserving
>> step is important for some other reason.
>
> After actually implementing some of these things, I'd like to revisit
> this discussion.
>
> The "reserving" stage used to be important for channel types where the
> bi-directional nature of the channel is realized with decreasing lock
> times (see above). Now that a large part of the community has put its
> hope on Lightning, it's more likely that the extensions required for
> better channel types will be included in Bitcoin, so this issue has
> become less important.
>
> Another reason why the "reserving" stage is important, is that it it
> necessary for bi-directional routing. In order to make both payer and
> payee anonymous, we need to provide this feature, where both route to a
> meeting point. For the part between meeting point and payee, routing
> goes from payee to meeting point(*), but locking goes from meeting point
> to payee, so they can't be done in the same stage.

This is an interesting problem. I previously beleived this could be done by some tunnelling mechanism in the meeting point (unknown to the payer), except that the timeouts are a problem. So it can still be done, but the payer would have to be told to bump their timeouts.

I fear the complexity of implementing a two-way reservation scheme up-front, however. It implies that the payee knows the timing of the payer, and adds failure modes when that's wrong.

I also dislike meeting points by default: there's a whole extra layer of deciding what meeting points to use. Beacons can be bypassed (if you notice the route is the same to and from, which is more likely if beacons are less connected).

Quoted text (9 lines)
> Finally, the "reserving" stage allows you to set a tighter value on the
> HTLC time-outs. If you do routing together with locking, then routing
> has to go in the payer->payee direction; the time-out has to be reduced
> on every hop. Assuming(**) the payer doesn't know the number of hops in
> advance, the time-out has to be set to a very high value by the payer,
> to maximize chances of a successful transaction. If you do routing in
> the reverse direction (payee->payer), you can start with a very low
> time-out, and increment it on every hop. This will generally result in
> lower time-out values, which is desirable.

With onioning, we need source routing. However, we can still get some of the benefits by splitting the stages, and having a non-binding propose message.

ie. currently BOLT#2 has a complete HTLC negotiation looking like this:

 update_add_htlc ->
 update_commit ->
                      <- update_revocation
                      <- update_commit
 update_revocation ->

The receiver can't forward the htlc until it knows the sender is bound to honour it, which takes these three trips.

If we introduce a non-binding step before the "add_htlc" (say "introduce_htlc"), this is possible: the receiver could forward the "introduce_htlc" instantly. Then there would be a (non-binding) feedback message, and a "cancel_htlc".

That would allow faster feedback, such as fee or route changes or outright failure.

Thoughts?

Quoted text (28 lines)
> That's about it, for the advantages offered by the separate reserving
> stage in Amiko Pay. Let me finish with an attempt to make an ASCII-art
> sequence diagram of reserving, bi-directional routing and locking in
> Amiko Pay:
>
> H(R) = the transaction hash (also included in other messages)
> MR() = MakeRoute message without time info
> MR(t) = MakeRoute message with time info
> HR() = HaveRoute message without time info
> HR(t) = HaveRoute message
> L(t) = Lock message (adds HTLC to channel)
> A = Alice (payer)
> B = Bob (meeting point)
> C = Carol (intermediate node). There can be many intermediate nodes
> between A and B, and between B and D.
> D = Dave (payee)
>
> A               B               C             D
> |<------------------ H(R) --------------------|
> |------MR()---->|               |<-MR(T0+dt)--|
>                 |<-MR(T0+2*dt)--|
> |<-HR(T0+3*dt)--|--HR(T0+2*dt)->|
>                                 |--HR(T0+dt)->|
> |<------------------ HR() --------------------|
> |--L(T0+3*dt)-->|--L(T0+2*dt)-->|--L(T0+dt)-->|
>
> (...and then the sequence continues with removing the HTLCs and
> releasing funds towards payee-side of each channel.)

This is a more interactive protocol. Which is nice in some ways, but I feel it's also more complex and more subject to timing analysis.

If we were to extend the protocol later, this would fit fairly nicely, though.

Cheers, Rusty.