Research/Bitcoin Dev Archive / lightning-dev list
Blinded channel observation
20 messages, Aug 8 to 18, 2016. Started by Tadge Dryja.
Rusty Russell (9), Joseph Poon (6), Tadge Dryja (5)
Blinded outsourcing of channel monitoring
The big risk in LN is that an attacking node can close a channel at an old, invalidated state beneficial to the attacker, and the Bitcoin network will accept these transactions. The node being attacked can defend by grabbing both outputs, which will probably make such attacks quite rare. But, nodes have to be online to detect this attack and defend against it, or risk losing funds.
Outsourcing this vigilance can further defend against attacks by allowing multiple parties to mount the defense. My initial thinking was that minimizing the amount of data stored on the observer would be best, but I don't think there's a way to make it O(log(n)) with the way Bitcoin works today. (Sighash_noinput, some variants of MAST, etc could make that work and we should keep that in mind, but that may be longer term)
So if it's going to be O(n), another way to make outsourcing better is to anonimize / blind it. Of course if the observer actually sees an invalid close and sends out a transaction moving the attacker's time-locked funds, they will learn about how big the channel was, the txid, etc. But 99.999% of the time, channels won't get closed at an invalid state, so the observer doesn't actually do anything. Most of the time channels will be closed cooperatively, but some times they'll be closed unilaterally because one node is offline / unresponsive. We should keep privacy in either of those cases.
States with in-flight HTLCs are another issue... if you want to keep the data storage down, you can just not include them, and make a policy that the sum of all the HTLCs should be less than either non-HTLC balance in the channel. That way the attacker still loses money if they try to attack. They potentially might not lose all of it though. You could make it variable size and include HTLCs as well but that increases the data rate significantly and probably hurts anonymity in various ways.
Without HTLCs, the script I have now specifies 2 pubkeys and requires 1 of 2 signatures- either from the timeout key or the revocable key. The goal is that the observer is monitoring a channel, but even an uncooperative close of that channel is undetectable, even after the output is spent and the pubkeys are revealed in the p2wsh preimage. To meet this goal the two pubkeys have to change completely with every new state, and also the non-timelocked pubkey Hash output also needs to change each time.
A simple way to do it would be to have the two sides of the channel make up new timeout and revocable pubkeys for each new state, but that's a lot of data for them, and also an extra 66 bytes per state for the observer. Instead, we can use the elkrem tree not just to revoke states, but also to obscure the keys in each state.
To do this, the messages actually didn't change too much, but key derivation changes a bit. At channel setup, A and B share "base points", which are their public keys which will be used in the commitment script. However these public keys are never used directly so I call them "points" on the curve rather than pubkeys themselves. (Not sure what the best convention is for that; I figure, call it a pubkey if you end up putting it on the blockchain and making a signature with it; call it a point if it's used otherwise, including to build a pubkey.)
When making a new state, instead of A sending B a revokable pubkey, A instead sends two "elkrem points" specific to the state number. These points are both deterministically derived from the same elkrem hash. For example, if we're building state 9, A goes down the branches of their elkrem tree to node #9, and gets a 32 byte hash. A appends ascii "t" for the timeout point, and ascii "r" for the revocable point. A then uses those two hashes as private scalars and multiplies by G, creating points on the curve, or public keys. A sends those points to B as the "elkrem points". B then adds elkrem point R to A's base point and elkrem point T to B's own base point. The former results in A's revokable pubkey, the latter in B's timeout pubkey for the script.
A sends elkrem points: elkrem point R + B base point: Revokable Pubkey elkrem point T + A base point: Timeout Pubkey
B's elkrem point R + B's refund point: Refund Pubkey hash with these points, B signs & sends, A stores.
B sends elkrem points: elkrem point R + A base point: Revokable Pubkey elkrem point T + B base point: Timeout Pubkey
A's elkrem point R + A's refund point: Refund Pubkey hash with these points, A signs & sends, B stores.
Before the state is revoked, the sender knows the scalar to generate the elkrem points, so there's nothing hidden about the timeout and refund pubkeys. Those just obscure the channel. The revokation pubkey is the only one where nobody individually knows the private key for the pubkey until the hashes are revealed.
Once the hashes are revealed and put into the tree, either party can regenerate all the pubkeys at any previous state quickly. That's not actually useful for the two nodes (why would you want to generate the script of an old state?) but it's very useful for the outsourcing node. They won't be able to recognize state n, but state 0 ... n-1 are recognizable and can be stored efficiently.
The reason two different points are needed is that if you add the same elkrem point to the two base points, the observer can subtract the base points from the public key seen in the witness script.
A base point - timeout pubkey = elkrem B base point - revokable pubkey = elkrem
if (A base point - timeout pubkey) == (B base point - revokable pubkey)
then that point must be the elkrem point, which would indicate that those base points were used, allowing the observer to identify the channel.
Those are (I think) the only changes needed in the LN messages / protocol itself. The design of the observer is not quite done but I have the basic idea. It's kindof interesting, scalability-wise, because it will be looking for a set of txids that's potentially much larger than the whole blockchain! Basically when a node wants to give the observer an old state to watch, it just gives a signature, a txid, and an elkrem hash. Only the signature and txid need to be stored. Also you can drop part of the txid at the risk of collisions, but the cost of collisions is pretty small (mainly a few EC operations to build the pubkeys for the script), so 16 or even 8 byte txids could work.
If the observer sees a transaction in a block which matches a txid they're looking for, they do some sanity checks (e.g. does this tx have a p2wsh output?) then re-create the script, by using the elkrem tree they have, getting the state number from the tx itself (6 bytes, encoded in nLockTime / nSequence), generating the elkrem points, adding them to their stored base points, hashing the script and seeing if the script matches. If it does, , add the fixed output address, and figure out the output amount based on the input amount. Then add the signature, which should match up and result in a valid transaction.
This is preliminary and I wanted to send this mail about a week ago but I kept finding ways the observer could figure out which channel it was observing, and then devising ways to stop that.
The nice part about this way of doing it is that you can share the channel state data with people you don't know or trust. Maybe they won't actually watch over the channel for you, but maybe they might. If someone wanted to be really nice, they could try to get *every* channel and observe it. All you need is one or two nice people like that, and invalid closes become nigh impossible.
I'll post a bit more once it's more finalized. If people see any problems with this method please let me know!
-Tadge
Tadge Dryja <tadge at lightning.network> writes:
Quoted text (1 line)
> Blinded outsourcing of channel monitoring
But if we don't steal HTLCs, the lack of channel utilization is a pain:
Quoted text (7 lines)
> States with in-flight HTLCs are another issue... if you want to keep the > data storage down, you can just not include them, and make a policy that > the sum of all the HTLCs should be less than either non-HTLC balance in the > channel. That way the attacker still loses money if they try to attack. > They potentially might not lose all of it though. You could make it > variable size and include HTLCs as well but that increases the data rate > significantly and probably hurts anonymity in various ways.
But now they must *always* keep their balance greater than all the HTLCs they ever previously received at once, otherwise it's worth them cheating.
I think we really do want to capture those HTLCs, but I don't think it's as bad as you think: an HTLC can be described in ~40 bytes. We need to do some magic to pad it out to hide the number of HTLCs, of course.
So, my method was less ambitious. I'll describe it here:
We send the observer the "steal" tx every update (not really: we only need to send the to-us/to-them amounts, pubkeys, HTLCs info and sig). This gets encrypted+HMAC with the txid of the commit tx (or, if that's too guessable, the SHA256() of our signature on the commit tx).
I had assumed we'd tell the observer our channel funding txid: when it sees that spent, it tries to use those signatures to decrypt all the txs we sent. If one succeeds, it spends it.
If we want to obscure our funding tx, we can simply use a txid qualifier the same way you did (and maybe use the sha256(txid) as the encryption key to avoid weakening that).
Whatever we do, we might want to offer our own peers to do that watching for them (for a fee?).
Cheers! Rusty.
Hi Rusty,
On Tue, Aug 09, 2016 at 03:13:57PM +0930, Rusty Russell wrote:
Quoted text (10 lines)
> We send the observer the "steal" tx every update (not really: we only > need to send the to-us/to-them amounts, pubkeys, HTLCs info and sig). > This gets encrypted+HMAC with the txid of the commit tx (or, if that's > too guessable, the SHA256() of our signature on the commit tx). > > [snip] > > If we want to obscure our funding tx, we can simply use a txid qualifier > the same way you did (and maybe use the sha256(txid) as the encryption > key to avoid weakening that).
I think it may be necessary to identify when the transaction occurs as an index for outsourcing services, so the key can't be dervied directly from the txid with a single HMAC/sha256. It's possible there are millions of transactions to compare, and an index based on txid is necessary. The two options I can see are:
1. Take the txid and use two salts (globally for all users). HMAC(txid+salt1) and HMAC(txid+salt2). Give the result of HMAC(txid+salt1) and the encrypted blob to the outsourcer. The first is used for identifying the txid, the second salt is for the secret key and can only be derived when the actual txid is seen. When a transaction is received, do HMAC(txid+salt1) and see if there's any matches to decrypt & broadcast.
2. HMAC the transaction itself (not txid) as the secret key (or anything part of the transaction, as long as it isn't SHA256(tx) for obvious reasons). I like something along these lines better than option #1. Whatever computational cost there is will be extremely low, as the operations are constrained by block size.
I do like encrypting the outsourcing blobs best as an approach so far, as it gives maximum flexibility in terms of implementation (individual client behavior can be upgraded in the future without modifying the outsourcing code/nodes in most instances).
Joseph Poon <joseph at lightning.network> writes:
Quoted text (19 lines)
> Hi Rusty, > > On Tue, Aug 09, 2016 at 03:13:57PM +0930, Rusty Russell wrote: >> We send the observer the "steal" tx every update (not really: we only >> need to send the to-us/to-them amounts, pubkeys, HTLCs info and sig). >> This gets encrypted+HMAC with the txid of the commit tx (or, if that's >> too guessable, the SHA256() of our signature on the commit tx). >> >> [snip] >> >> If we want to obscure our funding tx, we can simply use a txid qualifier >> the same way you did (and maybe use the sha256(txid) as the encryption >> key to avoid weakening that). > > I think it may be necessary to identify when the transaction occurs as > an index for outsourcing services, so the key can't be dervied directly > from the txid with a single HMAC/sha256. It's possible there are > millions of transactions to compare, and an index based on txid is > necessary. The two options I can see are:
This is fun!
Yes, I think we agree some "filter hint" is needed to avoid a crazy amount of outsourcing work (eg. first 8/16 bytes of txid). I don't think an HMAC check per registered commitment is quite fast enough.
But there's a problem with most naive filters, if you can guess commitment tx N-1 from commitment tx N. If the outsourcing service sees an old commit they can guess at previous commitment txs using that. Probably unroll the whole channel history if they can guess enough HTLCs.
Quoted text (5 lines)
> 2. HMAC the transaction itself (not txid) as the secret key (or anything > part of the transaction, as long as it isn't SHA256(tx) for obvious > reasons). I like something along these lines better than option #1. > Whatever computational cost there is will be extremely low, as the > operations are constrained by block size.
If we include the witness in that HMAC we risk reintroducing malleability. If we don't, we risk txs being predictable.
I can think of a few fixes: insert some randomness in the tx (OP_RETURN? Different addresses each time?), or try to extract the input signature from the witness, which is unguessable, as our filter?
What's simplest? Rusty.
On Wed, Aug 10, 2016 at 06:36:11AM +0930, Rusty Russell wrote:
Quoted text (3 lines)
> Yes, I think we agree some "filter hint" is needed to avoid a crazy > amount of outsourcing work (eg. first 8/16 bytes of txid). I don't > think an HMAC check per registered commitment is quite fast enough.
For #1, the HMAC would be pre-computed by the outsourcer. So the flow looks like:
1. The outsourcer takes the txid, HMAC(txid+salt1) and encrypts the blob 2. The outsourcer gives the 32-byte hmac and blob to the watcher 3. The watcher adds the 32-byte hmac and the blob to a key-value store (the watcher can optionally truncate or whatever) 4. When the watcher receives a new block, they HMAC(txid+salt1) all transactions and compare against the key-value store
This method does not require significant computation upon receiving a new block and checking against the datastore. I forgot to note, that the salt2 is sort of unnecessary, it can just be the pure txid as the key but was there for superstition and aid in understanding what's going on. I was just making a point that there needs to be some kind of "hint"/key to look for.
Quoted text (8 lines)
> > 2. HMAC the transaction itself (not txid) as the secret key (or anything > > part of the transaction, as long as it isn't SHA256(tx) for obvious > > reasons). I like something along these lines better than option #1. > > Whatever computational cost there is will be extremely low, as the > > operations are constrained by block size. > > If we include the witness in that HMAC we risk reintroducing > malleability. If we don't, we risk txs being predictable.
I was referring to the non-witness txid when making that comment, but there should be sufficient entropy from the revocation hash (whose P2WSH is part of the Commitment outputs).
Quoted text (3 lines)
> I can think of a few fixes: insert some randomness in the tx (OP_RETURN? > Different addresses each time?), or try to extract the input signature > from the witness, which is unguessable, as our filter?
Yeah! I like this idea to use one's own input sig as the key for the encrypted blob too. If Alice is the one outsourcing the Commitment which Bob can broadcast, Bob can only broadcast it using the sig Alice gave Bob as it's spending from a 2-of-2. If Alice is outsourcing Bob's Commitment broadcasts, a hash of her input signature is a solid way to derive a key as well without malleability concerns.
I also like that it "encourages" more nodes to download witness data; ignoring witnesses is a concern of mine which this helps with :^)
Quoted text (7 lines)
> > 4. When the watcher receives a new block, they HMAC(txid+salt1) all > transactions and compare against the key-value store > > This method does not require significant computation upon receiving a > new block and checking against the datastore. I forgot to note, that the >
If you're only watching 1 channel, this is OK as you're just doing one HMAC operation per incoming tx. This works when the number of states per channel is high but the number of channels watched is low. If you're watching 1M channels with 1K states each, this requires 1M HMAC operations for every incoming tx.
By giving the whole (or a truncated part) of the txid, the observing node can put all txids being watched for into the same tree and have seek access time independent of the number of separate channels being watched. Whether it's 1 channel with 1 billion states, or 100M channels with 10 states each, you have the same cpu and I/O cost per incoming tx.
I'm not clear on the advantages of sending encrypted state information to the observer. Most information the observer needs to construct a punishing transaction is available in the observed commitment tx; the only per-state information which needs to be stored is the signature (and in the case of HTLCs, the preimage). Reconstructing messages from hashes and / or signatures isn't possible as long as there's sufficient unknown data in the preimage or message. This is achievable by changing the pubkeys used in the commit tx script and pubkey hash each state, without needing additional data in an OP_RETURN.
-Tadge
On Tue, Aug 9, 2016 at 6:29 PM, Joseph Poon <joseph at lightning.network> wrote:
Quoted text (53 lines)
> On Wed, Aug 10, 2016 at 06:36:11AM +0930, Rusty Russell wrote: > > Yes, I think we agree some "filter hint" is needed to avoid a crazy > > amount of outsourcing work (eg. first 8/16 bytes of txid). I don't > > think an HMAC check per registered commitment is quite fast enough. > > For #1, the HMAC would be pre-computed by the outsourcer. So the flow > looks like: > > 1. The outsourcer takes the txid, HMAC(txid+salt1) and encrypts the blob > 2. The outsourcer gives the 32-byte hmac and blob to the watcher > 3. The watcher adds the 32-byte hmac and the blob to a key-value store > (the watcher can optionally truncate or whatever) > 4. When the watcher receives a new block, they HMAC(txid+salt1) all > transactions and compare against the key-value store > > This method does not require significant computation upon receiving a > new block and checking against the datastore. I forgot to note, that the > salt2 is sort of unnecessary, it can just be the pure txid as the key > but was there for superstition and aid in understanding what's going on. > I was just making a point that there needs to be some kind of "hint"/key > to look for. > > > > 2. HMAC the transaction itself (not txid) as the secret key (or > anything > > > part of the transaction, as long as it isn't SHA256(tx) for obvious > > > reasons). I like something along these lines better than option #1. > > > Whatever computational cost there is will be extremely low, as the > > > operations are constrained by block size. > > > > If we include the witness in that HMAC we risk reintroducing > > malleability. If we don't, we risk txs being predictable. > > I was referring to the non-witness txid when making that comment, but > there should be sufficient entropy from the revocation hash (whose P2WSH > is part of the Commitment outputs). > > > I can think of a few fixes: insert some randomness in the tx (OP_RETURN? > > Different addresses each time?), or try to extract the input signature > > from the witness, which is unguessable, as our filter? > > Yeah! I like this idea to use one's own input sig as the key for the > encrypted blob too. If Alice is the one outsourcing the Commitment which > Bob can broadcast, Bob can only broadcast it using the sig Alice gave > Bob as it's spending from a 2-of-2. If Alice is outsourcing Bob's > Commitment broadcasts, a hash of her input signature is a solid way to > derive a key as well without malleability concerns. > > I also like that it "encourages" more nodes to download witness data; > ignoring witnesses is a concern of mine which this helps with :^) > > -- > Joseph Poon >
Joseph Poon <joseph at lightning.network> writes:
Quoted text (14 lines)
> On Wed, Aug 10, 2016 at 06:36:11AM +0930, Rusty Russell wrote: >> Yes, I think we agree some "filter hint" is needed to avoid a crazy >> amount of outsourcing work (eg. first 8/16 bytes of txid). I don't >> think an HMAC check per registered commitment is quite fast enough. > > For #1, the HMAC would be pre-computed by the outsourcer. So the flow > looks like: > > 1. The outsourcer takes the txid, HMAC(txid+salt1) and encrypts the blob > 2. The outsourcer gives the 32-byte hmac and blob to the watcher > 3. The watcher adds the 32-byte hmac and the blob to a key-value store > (the watcher can optionally truncate or whatever) > 4. When the watcher receives a new block, they HMAC(txid+salt1) all > transactions and compare against the key-value store
Ah OK! I am in sync now, sorry for the noise!
Quoted text (6 lines)
>> If we include the witness in that HMAC we risk reintroducing >> malleability. If we don't, we risk txs being predictable. > > I was referring to the non-witness txid when making that comment, but > there should be sufficient entropy from the revocation hash (whose P2WSH > is part of the Commitment outputs).
Unfortunately, watcher knows revocation preimage N, so it can figure out some or all previous revocation preimages (and thus hashes). That's true with shachain, and I think elkrem has similar properties (it's kind of what we were after!).
Quoted text (10 lines)
>> I can think of a few fixes: insert some randomness in the tx (OP_RETURN? >> Different addresses each time?), or try to extract the input signature >> from the witness, which is unguessable, as our filter? > > Yeah! I like this idea to use one's own input sig as the key for the > encrypted blob too. If Alice is the one outsourcing the Commitment which > Bob can broadcast, Bob can only broadcast it using the sig Alice gave > Bob as it's spending from a 2-of-2. If Alice is outsourcing Bob's > Commitment broadcasts, a hash of her input signature is a solid way to > derive a key as well without malleability concerns.
But it rests on the assumption that there are no unknown malleability issues on signatures, which I believe makes crypto people nervous. I've asked some, though, as that's above my pay grade!
It also assumes they can't set up the witness such that our sig is not 2nd or 3rd in the witness element. I think that's true...
Quoted text (2 lines)
> I also like that it "encourages" more nodes to download witness data; > ignoring witnesses is a concern of mine which this helps with :^)
Good point!
Cheers, Rusty.
Tadge Dryja <tadge at lightning.network> writes:
Quoted text (18 lines)
>> >> 4. When the watcher receives a new block, they HMAC(txid+salt1) all >> transactions and compare against the key-value store >> >> This method does not require significant computation upon receiving a >> new block and checking against the datastore. I forgot to note, that the > > If you're only watching 1 channel, this is OK as you're just doing one HMAC > operation per incoming tx. This works when the number of states per > channel is high but the number of channels watched is low. > If you're watching 1M channels with 1K states each, this requires 1M HMAC > operations for every incoming tx. > > By giving the whole (or a truncated part) of the txid, the observing node > can put all txids being watched for into the same tree and have seek access > time independent of the number of separate channels being watched. Whether > it's 1 channel with 1 billion states, or 100M channels with 10 states each, > you have the same cpu and I/O cost per incoming tx.
Yes, I think I agree.
Quoted text (5 lines)
> I'm not clear on the advantages of sending encrypted state information to > the observer. Most information the observer needs to construct a punishing > transaction is available in the observed commitment tx; the only per-state > information which needs to be stored is the signature (and in the case of > HTLCs, the preimage).
Yes. To be precise, watcher needs preimage, pubkeys, a signature, OP_CSV delay amounts for each side, and HTLCs.
If the pubkeys and OP_CSV delay amounts are fixed, you need a signature and preimage (required to steal the to-them output as well as htlcs) every new commit tx (ie. every new watch request). And you'll add a new HTLC information on average every second commit tx.
But I think you're better attaching every relevant HTLC to every watch request; otherwise, you're exposing all previous HTLCs. I recalculated: they're only 24 bytes each (ripemd hash + expiry).
If we really want to optimize that,maybe we can come up with a cleverer scheme, where you optionally include the key to the previous watch request with the encrypted information, allowing the sender to control the privacy/data tradeoff? Then the watcher would gather HTLCs from those previous requests as well, and see which ones are required? {Insert bikeshed here}. {No, here}.
Quoted text (5 lines)
> Reconstructing messages from hashes and / or > signatures isn't possible as long as there's sufficient unknown data in the > preimage or message. This is achievable by changing the pubkeys used in > the commit tx script and pubkey hash each state, without needing additional > data in an OP_RETURN.
FWIW, I take back the idea about using the signature as a key: 1) While the crypto people tell me it's probably OK, they can't prove it. 2) If we go to Schnorr, I think it falls apart as both sigs are combined.
OTOH, changing pubkeys every step isn't required if we go for Laolu's key-revocation scheme instead of shachain/elkrem. I think? (Roasbeef, this is your cue to describe it in detail!)
Cheers, Rusty,
The method of using a revocation key is compatible with shachain/elkrem so has log(n) storage; I'll describe what I developed which omits hashing in the commit script and uses only signature verification. If Laolu has made a different key revocation scheme I'm not aware, but please do post if so.
The script is:
DUP [Revocable Pubkey] CHECKSIG NOTIF [Timeout Pubkey] CHECKSIGVERIFY [timeout period] CHECKSEQUENCEVERIFY ENDIF
This is a little ugly as the less likely checksig (the revocable one) happens first. Saves space in the script though and we don't pay any more for a checksig than any other 1 byte opcode.
As an if statement, it ends up being: if (revocable sig) || (timeout sig && CSV > timeout)
To build the revocable pubkey, Alice takes their elkrem sender hash from state n, which we'll call EHn. Alice multiples EHn * G, getting a point EPn. (Elkrem point n) Alice sends EPn to Bob, who adds their commitment pubkey (BP, which is never seen raw) to EPn. The result, (RPub n = BP + EPn), is the revocable pubkey for state n. At state n+1, Alice sends Bob EHn. Bob can then compute the private key for Rpub n, as it's just their commitment private key plus EHn, modulo the order of the curve.
A similar procedure is used for the timeout key; Alice adds a point to their own timeout key, which seems kindof pointless because they know both scalars. It obscures the commitment script by making both pubkeys different each state, as they're all generated from the hash tree. Bob only needs to keep track of the most recent "elkrem points" and the hash tree itself.
Hope this is clear and sorry if I'm describing something completely different than what you're asking about!
-Tadge
Tadge Dryja <tadge at lightning.network> writes:
Quoted text (4 lines)
> The method of using a revocation key is compatible with shachain/elkrem so > has log(n) storage; I'll describe what I developed which omits hashing in > the commit script and uses only signature verification. If Laolu has made > a different key revocation scheme I'm not aware, but please do post if so.
Oh, I blamed Laolu because he told me about it; sorry for misattribution.
Quoted text (11 lines)
> The script is: > > DUP > [Revocable Pubkey] > CHECKSIG > NOTIF > [Timeout Pubkey] > CHECKSIGVERIFY > [timeout period] > CHECKSEQUENCEVERIFY > ENDIF
OK, so far so good.
Quoted text (4 lines)
> To build the revocable pubkey, Alice takes their elkrem sender hash from > state n, which we'll call EHn. Alice multiples EHn * G, getting a point > EPn. (Elkrem point n) Alice sends EPn to Bob, who adds their commitment > pubkey (BP, which is never seen raw) to EPn.
"never seen raw on-chain" I assume, since Bob will send it to Alice in setup?
Quoted text (4 lines)
> The result, (RPub n = BP + EPn), is the revocable pubkey for state n. > At state n+1, Alice sends Bob EHn. Bob can then compute the private > key for Rpub n, as it's just their commitment private key plus EHn, > modulo the order of the curve.
So, AFACIT this scheme gives us a slightly smaller script and makes previous commit transactions underivable.
The property I was *hoping* for was the ability for Alice (and Bob) to independently predict each others' future revocation hashes/pubkeys. That would neatly allow an arbitrary number of commitment transactions in flight each way at once. Naively, seems like that should be possible.
Quoted text (6 lines)
> A similar procedure is used for the timeout key; Alice adds a point to > their own timeout key, which seems kindof pointless because they know both > scalars. It obscures the commitment script by making both pubkeys > different each state, as they're all generated from the hash tree. Bob > only needs to keep track of the most recent "elkrem points" and the hash > tree itself.
I think changing the timeout key is harmless, but gratuitous; changing the revocation key is sufficient for each commitment script unguessably different from the last one, no?
Quoted text (2 lines)
> Hope this is clear and sorry if I'm describing something completely > different than what you're asking about!
It's all good; this is a big space and sometimes I don't even know what I don't know...
Thanks! Rusty.
Hi, this is very interesting idea that I hadn't thought of!
Quoted text (1 line)
> Oh, I blamed Laolu because he told me about it; sorry for misattribution.
Heh not at all, I don't know who's coming up with what either.
Quoted text (7 lines)
> > To build the revocable pubkey, Alice takes their elkrem sender hash from > > state n, which we'll call EHn. Alice multiples EHn * G, getting a point > > EPn. (Elkrem point n) Alice sends EPn to Bob, who adds their commitment > > pubkey (BP, which is never seen raw) to EPn. > > "never seen raw on-chain" I assume, since Bob will send it to Alice in > setup?
Right; Alice and Bob share these base points when they're funding the channel but if never shows up on-chain.
Quoted text (9 lines)
> So, AFACIT this scheme gives us a slightly smaller script and makes > previous commit transactions underivable. > > The property I was *hoping* for was the ability for Alice (and Bob) to > independently predict each others' future revocation hashes/pubkeys. > That would neatly allow an arbitrary number of commitment transactions > in flight each way at once. Naively, seems like that should be > possible. >
That... is a very cool idea which I had not considered. Sketching it out, it seems like you'd need some kind of bi-directional trap door function. RSA comes to mind where repeated exponentiation to the e can be reversed by exponentiation to the d. But in RSA "private keys" (d) and "public keys" (e) are the same thing (scalars) but here they're different.
My gut feeling is that with secp256k1 it's not possible though. Setting up a homomorphic relationship such that Pubkey0 lets you compute Pubkey1 seems like it would also allow you to compute from Scalar0 to Scalar1 -- just perform whatever additions and multiplications you did to the point on the scalar. Definitely something to think about though, because it'd be very cool. (In practice it doesn't really affect storage, and reduces data on the wire a somewhat, so not a huge difference scalability-wise, but still would be really cool if possible)
Quoted text (3 lines)
> I think changing the timeout key is harmless, but gratuitous; changing > the revocation key is sufficient for each commitment script unguessably > different from the last one, no?
Yeah, I didn't alter the timeout key initially, but I put it in because it helps keep the channel private from the observer in the case where you just send them signatures. If the timeout key is unchanging, they'd see it when the channel close un-cooperatively and recognize the channel they were monitoring.
For privacy, the points you add to the timeout key and revocable key also need to be *different* points. If you add the same point to both, an observer who knows the base points can try subtracting the timeout and revocable base points from the observed pubkeys. If the result for both is the same, they'll know they've found the channel they're looking for.
Thanks for the new idea to stew over on the train! -Tadge
On Wed, Aug 10, 2016 at 11:33:46AM +0930, Rusty Russell wrote:
Quoted text (2 lines)
> Unfortunately, watcher knows revocation preimage N, so it can figure out > some or all previous revocation preimages (and thus hashes).
If you take the results then HMAC it as the final step in shachain/elkrem (to establish a single leaf), should be fine even if revocation hashes are used in lieu of a revocation pubkey.
Quoted text (6 lines)
> But it rests on the assumption that there are no unknown malleability > issues on signatures, which I believe makes crypto people nervous. I've > asked some, though, as that's above my pay grade! > > It also assumes they can't set up the witness such that our sig is not > 2nd or 3rd in the witness element. I think that's true...
Yeah, good point. Perhaps it could be better to keep it simple and just use an HMAC of the non-witness transaction. There shouldn't be stuff that's easily mutatable, and the exposure is not expanded (since that would break LN's child transactions anyway).
On Thu, Aug 11, 2016 at 11:25:36AM +0930, Rusty Russell wrote:
Quoted text (7 lines)
> Tadge Dryja <tadge at lightning.network> writes: > > The method of using a revocation key is compatible with shachain/elkrem so > > has log(n) storage; I'll describe what I developed which omits hashing in > > the commit script and uses only signature verification. If Laolu has made > > a different key revocation scheme I'm not aware, but please do post if so. > > Oh, I blamed Laolu because he told me about it; sorry for misattribution.
I came up with it a long time ago, and worked out the details/optimizations /w Laolu more recently (I think he told you that night when everything was finalized). I mentioned the general construction to you a LONG time ago too when you were in the Bay Area, but I probably didn't explain it properly (I was comparing with Vanitygen, if that helps). I think Tadge was the first to implement it though, not sure.
Quoted text (5 lines)
> The property I was *hoping* for was the ability for Alice (and Bob) to > independently predict each others' future revocation hashes/pubkeys. > That would neatly allow an arbitrary number of commitment transactions > in flight each way at once. Naively, seems like that should be > possible.
I'm not inclined to think an increase in complexity is helpful (if this is necessary), but there are probably some things you can do if you're looking down these paths.
It's possible to get the same *bandwidth* optimization you want, except opposite. The idea with "predicting the future revocation hashes/pubkeys" is you only need to send revocations. Instead, it's possible to only send revocation hashes/pubkeys and not send revocations. In other words, instead of predicting each others' future revocation hashes/pubkeys, it's possible to revoke as *part of* giving the next revocation hash/pubkey.
You can arrange something similar to a hashchain (shachain/elkrem is an optimization of this, ignore optimizations for a second). We treat privkey->pubkey as an elaborate hash function. I think if you pre-compute it so that privkey -> pubkey, and then take the pubkey output to create a privkey, you have a reversed list of items (let's say you do this 100,000 times). The final privkey -> pubkey computation is the first "revocation keypair" used. The pubkey->privkey step can do anything you want, including hash functions if it makes you feel better (this is the point where one can optimize).
(Note: I really mean EC point here, but it's simpler to understand it as a pubkey)
If you want multiple in-flight, just have multiple parallel chains (minor increase in permanent storage of counterparty's revocations). I don't see any need for more than a handful in-flight. Note that this explicitly breaks doing multiple in-flight on a single chain, since disclosure of a pubkey is disclosure of all prior revocation states.
Essentially, what happens is when you disclose a pubkey, you are providing the next pubkey AND revoking the prior one at the same time. This construction is also possible using hashtree like structures if you're using revocation hashes instead of revocation pubkeys.
For the pubkey revocation, a nested chain of privkey->pubkeys are needed instead of hashes since you can't have a usable pubkey point without also getting the corresponding private key.
Not sure how useful this is, though. Seems a lot of complexity for some small bandwidth savings, not really that interested in doing all that, but it's the closest I can get to what you want. This is off the top of my head/memory, I didn't write any notes on this, so parts of this (or entirety) might be wrong...
Joseph Poon <joseph at lightning.network> writes:
Quoted text (34 lines)
> On Thu, Aug 11, 2016 at 11:25:36AM +0930, Rusty Russell wrote: >> Tadge Dryja <tadge at lightning.network> writes: >> > The method of using a revocation key is compatible with shachain/elkrem so >> > has log(n) storage; I'll describe what I developed which omits hashing in >> > the commit script and uses only signature verification. If Laolu has made >> > a different key revocation scheme I'm not aware, but please do post if so. >> >> Oh, I blamed Laolu because he told me about it; sorry for misattribution. > > I came up with it a long time ago, and worked out the > details/optimizations /w Laolu more recently (I think he told you that > night when everything was finalized). I mentioned the general > construction to you a LONG time ago too when you were in the Bay Area, > but I probably didn't explain it properly (I was comparing with > Vanitygen, if that helps). I think Tadge was the first to implement it > though, not sure. > >> The property I was *hoping* for was the ability for Alice (and Bob) to >> independently predict each others' future revocation hashes/pubkeys. >> That would neatly allow an arbitrary number of commitment transactions >> in flight each way at once. Naively, seems like that should be >> possible. > > I'm not inclined to think an increase in complexity is helpful (if this > is necessary), but there are probably some things you can do if you're > looking down these paths. > > It's possible to get the same *bandwidth* optimization you want, except > opposite. The idea with "predicting the future revocation > hashes/pubkeys" is you only need to send revocations. Instead, it's > possible to only send revocation hashes/pubkeys and not send > revocations. In other words, instead of predicting each others' future > revocation hashes/pubkeys, it's possible to revoke as *part of* giving > the next revocation hash/pubkey.
Yeah, I do that already. We give the N+1th hash when we send the revocation for N:
// Complete the update.
message update_revocation {
// Hash preimage which revokes old commitment tx.
required sha256_hash revocation_preimage = 1;
// Revocation hash for my next commit transaction
required sha256_hash next_revocation_hash = 2;
}
The trivial extension is to make in the N+Mth revocation hash, and instead of sending the first two revocation hashes on establishment, send the first M+1.
I just wanted to make sure there wasn't some clever alternative I was missing. Greg Maxwell and Pieter Wuille tell me there isn't an obvious one.
Quoted text (5 lines)
> Not sure how useful this is, though. Seems a lot of complexity for some > small bandwidth savings, not really that interested in doing all that, > but it's the closest I can get to what you want. This is off the top of > my head/memory, I didn't write any notes on this, so parts of this (or > entirety) might be wrong...
Yeah, agreed. Hash trees are nice and simple, so unless we get a signficiant win, let's stick with that?
Cheers, Rusty.
Joseph Poon <joseph at lightning.network> writes:
Quoted text (7 lines)
> On Wed, Aug 10, 2016 at 11:33:46AM +0930, Rusty Russell wrote: >> Unfortunately, watcher knows revocation preimage N, so it can figure out >> some or all previous revocation preimages (and thus hashes). > > If you take the results then HMAC it as the final step in > shachain/elkrem (to establish a single leaf), should be fine even if > revocation hashes are used in lieu of a revocation pubkey.
Sure, or just SHA the leaf again. But such schemes prevent the watcher from using the elkrem/shachain space-savings themselves, which is kind of painful. (Though see below...)
Let's look at space & comms requirements, per new commitment tx, for different schemes. Let's say we have N htlcs in the current HTLC.
Bytes Bytes
Communicated Stored (per tx)
Naive (whole steal tx) ~300 * (N+1) ~300 * (N+1)
rhash+sig+HTLCdata 32 + 32 + 24*N 32 + 32 + 24*N
+shachain/elkrem 32 + 32 + 24*N 32 + 24*N
+SIG_NOINPUT 32 + 24*N 24*N
+Dual-scriptpubkey MAST 32 0
The ultimate is shachain/elkrem, SIG_NOINPUT and a MAST scheme which places two scripthashes into the scriptpubkey, either of which would allow spending. In that case, we'd simply send a series of SIG_NOINPUT signed steal txs with 1, 2, 3 ... inputs at the beginning, and then send each new revocation preimage as we learned it. The storage overhead is basically constant (technically, log(N) for the shachain).
Interestingly, MAST by itself buys us nothing (bytewise): the 32 bytes we'd need to send for the other branch of MAST is larger than the 24 bytes for the HTLC description.
Revealing the preimages seems a win, BUT if we give them unencrypted to the watcher we need some other way of avoiding guessable prior commitment txs. Which implies we change at least one key in some way, which means we need to send that key to the watcher to store, which costs as much as they save using shachain/elkrem!
The other win is sharing HTLCs across transactions somehow (which reduces N to the "number of new HTLCs" instead of "number of HTLCs"). I can't come up with anything very good here, though :(
Quoted text (11 lines)
>> But it rests on the assumption that there are no unknown malleability >> issues on signatures, which I believe makes crypto people nervous. I've >> asked some, though, as that's above my pay grade! >> >> It also assumes they can't set up the witness such that our sig is not >> 2nd or 3rd in the witness element. I think that's true... > > Yeah, good point. Perhaps it could be better to keep it simple and just > use an HMAC of the non-witness transaction. There shouldn't be stuff > that's easily mutatable, and the exposure is not expanded (since that > would break LN's child transactions anyway).
I still don't understand why use an HMAC-of-tx instead of just the txid? What does it gain?
Thanks! Rusty.
Hi Rusty,
Yeah, interesting thoughts!
On Fri, Aug 12, 2016 at 01:17:52PM +0930, Rusty Russell wrote:
Quoted text (2 lines)
> I still don't understand why use an HMAC-of-tx instead of just the txid? > What does it gain?
I'm presuming you need to index by txid to see if there needs to be a penalty transaction broadcast, so you can't use that as a secret key.
On Fri, Aug 12, 2016 at 12:54:52PM +0930, Rusty Russell wrote:
Quoted text (10 lines)
> Yeah, I do that already. We give the N+1th hash when we send the
> revocation for N:
>
> // Complete the update.
> message update_revocation {
> // Hash preimage which revokes old commitment tx.
> required sha256_hash revocation_preimage = 1;
> // Revocation hash for my next commit transaction
> required sha256_hash next_revocation_hash = 2;
> }Yeah, the way I described would (optimally over-the-wire) be a tree of chained preimages *AND* hashes as a part of the tree itself (so the chain looks like preimage->hash->preimage->hash instead of preimage->preimage). That way if you're willing to forgo the ability to have multiple "next revocation hashes" in-flight (by instead having multiple trees to achieve multiple in-flight), it's possible to only send the "next revocation hash", which will automatically reveal the prior "revocation preimage". In other words, the wire message could only be sending next_revocation_hash. If one were to use pubkey revocations, then that construction *requires* using privkeys+pubkeys instead of preimages+hashes, which ups the cost/complexity -- which is why I said it probably wasn't worth it.
Quoted text (2 lines)
> Yeah, agreed. Hash trees are nice and simple, so unless we get a > signficiant win, let's stick with that?
For sure.
Joseph Poon <joseph at lightning.network> writes:
Quoted text (10 lines)
> Hi Rusty, > > Yeah, interesting thoughts! > > On Fri, Aug 12, 2016 at 01:17:52PM +0930, Rusty Russell wrote: >> I still don't understand why use an HMAC-of-tx instead of just the txid? >> What does it gain? > > I'm presuming you need to index by txid to see if there needs to be a > penalty transaction broadcast, so you can't use that as a secret key.
But SHA256(txid) would be sufficent, no?
(Unless we're happy with 128 bit keys, then just use the upper bits for hint and lower bits for key).
So, here's a strawman spec (written in cat > style, so includes bugs):
1) We change the protocol slightly to use shachain/elkrem with an additional SHA256() to get the preimage. On-wire we reveal the leaf node, which you SHA256() to get the preimage. This makes commit N-1 unguessable even if you know commit N.
2) Format of message-to-watcher is:
[8-byte-txid-prefix-hint]
[chacha20poly1305 blob, key is SHA256(txid):
[txid-of-previous-commit-or-zero]
[bitcoin signature]
[revocation preimage]
[htlc #1 H-hash ripemd160]
[htlc #1 expiry]
[htlc #2 H-hash ripemd160]
[htlc #2 expiry]
...
[arbitrary zero padding]
]
3) Implementations should pad this out to some reasonable amount to cover expected HTLCs and avoid revealing too much using size. Handwave.
4) Implementations should set the txid-of-previous-commit field sparingly: it saves space for HTLCs which are in multiple commits, but leaks information. Handwave.
5) Initially watcher would be given commit and timeout keys for both sides (which I'm assuming are static).
6) Upon seeing a txid prefix match, watcher tries to decrypt. If success, decrypts previous message-to-watchers as possible using txid-of-previous-commit-or-zero fields and walking back. Accumulates all the HTLCs, calculates the wscripts for them, sees which match outputs. Also look for the one the cheater paid to-self. Generates transaction that spends all the outputs it can match, checks [bitcoin signature] is valid, sends tx.
What have I missed? Rusty.
There's two approaches with encrypted vs non-encrypted: the non-encrypted design which I kindof like, is to make all the information given to the observer not mean anything on its own. With encrypted, you achieve the same result, but have some decryption key stuffed somewhere in the observed transaction to reveal meaningful data which identifies the channel, but is encrypted.
Non-encrypted can be more efficient, because it's hard to squeeze down compact encrypted data (though see below for an attempt!). But most things in the channel states can be obfuscated such that even if you tell everything to the observer, they don't learn anything. (Even in the case where the observer is watching both sides of the channel, they shouldn't be able to match them... well other than timing, which is admittedly a very effective way to do it!)
I skipped over HTLCs though because they didn't fit with this model. And they really don't -- unlike the updating pubkeys in the commit tx, HTLC's are passed though multiple nodes, so information about them can get to the observer pretty easily. So I think HTLCs would need to be in some kind of encrypted blob to send to the observer.
I really like txid[0:16] as the truncated txid for the observer and txid[16:32] as the decryption key because it's simple and quite fast. This would allow constant-time lookups into the observer's database regarless of how many channels it's watching, which HMAC'ing the txid doesn't have. (You could hash txid[16:32] again for the decryption key if you want 32 bytes.)
The non-HTLC data can be sent unencrypted -- it's pretty much just a signature and hash from the tree. If there is a new HTLC (or a few) added in that state, the node can elect to send that to the observer as well. I think the format can be something like:
htlc #1 expiry (4 bytes) htlc #1 preimage (20 bytes) htlc #2 expiry (4 bytes) htlc #2 preimage (20 bytes) offset to previous blob (2 bytes) decrypt key for previous blob (16 bytes)
having pointers to previous states can save a lot of space if HTLCs are added incrementally. The "blobs" can be kept in a separate data store indexed by state number, so it's quick to see that, e.g, state 471 also has an HTLC from state 465, which has HTLCs from state 442. This chained decryption may end up revealing more HTLCs than are needed (which are quick for the observer to detect and discard) but if the fraud has occurred then anonymity is gone anyway and it's no big deal if the observer learns a little more -- they already learned all the important stuff.
I *think* 2 bytes is enough; it's not that an HTLC can't last more than 65K states, it's that an HTLC can't persist > 65K states with no other HTLCs being added during that period. A long-lived HTLC wouldn't be referenced directly; instead later states which still had it would point to a previous state that also pointed to it. It's a bit more work for the observer, who might end up with hundreds of extra preimages, but I think optimizing for space savings at the cost of CPU time when the fraud occurs is a good trade-off. (The fraud occurs almost never, while the state data transfers and storage happen always)
This would also allow nodes to omit or include HTLCs to the observer as they see fit, which seems useful for micropayments which might outstrip the abilities of the observer.
Also, yeah, padding (handwave) and timing are what make hiding the channel very tricky, especially for HTLCs. With non-HTLC updates, it can be hard to know when 2 nodes are updating a channel state, but with HTLCs there are more nodes in the mix with more points for data to leak out to the observer. That's another reason you might want to omit sending out some portion of HTLC recovery data.
I will try coding some of this and see, because it seems to work in my head but that's no indication it'll work on the computer :)
-Tadge
Tadge Dryja <tadge at lightning.network> writes:
Quoted text (20 lines)
> There's two approaches with encrypted vs non-encrypted: the non-encrypted > design which I kindof like, is to make all the information given to the > observer not mean anything on its own. With encrypted, you achieve the > same result, but have some decryption key stuffed somewhere in the observed > transaction to reveal meaningful data which identifies the channel, but is > encrypted. > > Non-encrypted can be more efficient, because it's hard to squeeze down > compact encrypted data (though see below for an attempt!). But most things > in the channel states can be obfuscated such that even if you tell > everything to the observer, they don't learn anything. (Even in the case > where the observer is watching both sides of the channel, they shouldn't be > able to match them... well other than timing, which is admittedly a very > effective way to do it!) > > I skipped over HTLCs though because they didn't fit with this model. And > they really don't -- unlike the updating pubkeys in the commit tx, HTLC's > are passed though multiple nodes, so information about them can get to the > observer pretty easily. So I think HTLCs would need to be in some kind of > encrypted blob to send to the observer.
Yeah, I think that makes the non-encrypted idea a non-starter; we need to steal those HTLCs without introducing nasty restrictions.
Quoted text (6 lines)
> I really like txid[0:16] as the truncated txid for the observer and > txid[16:32] as the decryption key because it's simple and quite fast. This > would allow constant-time lookups into the observer's database regarless of > how many channels it's watching, which HMAC'ing the txid doesn't have. > (You could hash txid[16:32] again for the decryption key if you want 32 > bytes.)
Yeah; I'd just hash the whole txid again though. I mean, why not?
Quoted text (4 lines)
> The non-HTLC data can be sent unencrypted -- it's pretty much just a > signature and hash from the tree. If there is a new HTLC (or a few) added > in that state, the node can elect to send that to the observer as well. I > think the format can be something like:
You can't send hash in the clear unless you're using variable keys in commit txs (since that hash is what makes the previous txids unguessable). But that's OK, encrypting it doesn't hurt us AFAICT.
Quoted text (15 lines)
> htlc #1 expiry (4 bytes) > htlc #1 preimage (20 bytes) > htlc #2 expiry (4 bytes) > htlc #2 preimage (20 bytes) > offset to previous blob (2 bytes) > decrypt key for previous blob (16 bytes) > > having pointers to previous states can save a lot of space if HTLCs are > added incrementally. The "blobs" can be kept in a separate data store > indexed by state number, so it's quick to see that, e.g, state 471 also has > an HTLC from state 465, which has HTLCs from state 442. This chained > decryption may end up revealing more HTLCs than are needed (which are quick > for the observer to detect and discard) but if the fraud has occurred then > anonymity is gone anyway and it's no big deal if the observer learns a > little more -- they already learned all the important stuff.
Hmm, this is more sophisticated that my suggestion, by allowing reference to *any* prev blob.
Would that win much though? If HTLCs have been added then removed, it's possible, but I'm not sure how much it saves.
eg.
HTLCs
Commit tx:
1 1
2 1 2
3 2
4 2 3 4 5
5 5
6 6 7
7 6 8
8 6
Using a heuristic says "don't ever leak more than <current-htlcs> unnessary HTLCs" gives:
#1: HTLC1 #2: (references #1) HTLC2 #3: (references #2) #4: HTLC2 HTLC3 HTLC4 HTLC5 #5: HTLC5 #6: HTLC6 HTLC7 #7: (references #6) HTLC8 #8: (refefences #6) HTLC6
Assuming 24 bytes per HTLC, and 18 bytes per backref, the naive encoding would be 14 * 24 = 336, backref = 11 * 24 + 3 * 18 = 318 bytes. Not much.
OK, let me write a quick simulator, with exponential distribution times (because bitcoin!). Hmm, attached below. It only references the previous HTLC, not any previous, but it does show that it's hard to make the savings more than 50% (reduce the chance of an HTLC expiring to 1%, for example).
See horrible hacked-up code below.
Quoted text (6 lines)
> Also, yeah, padding (handwave) and timing are what make hiding the channel > very tricky, especially for HTLCs. With non-HTLC updates, it can be hard > to know when 2 nodes are updating a channel state, but with HTLCs there are > more nodes in the mix with more points for data to leak out to the > observer. That's another reason you might want to omit sending out some > portion of HTLC recovery data.
Yes, this is the hard part.
Quoted text (2 lines)
> I will try coding some of this and see, because it seems to work in my head > but that's no indication it'll work on the computer :)
For sure! Here's my hacky simulation results for 1M commitment txs with the mean and stddev in the brackets:
Num htlcs: 0-24(3.99+/-2.5) Raw-encoding bytes: 0-576(95+/-60) Backref-encoding bytes: 16-520(40+/-34) Best-encoding bytes: 0-528(65+/-51)
Cheers, Rusty.
// 2>/dev/null; set -e; OUT=/tmp/`basename $0 .c`; if [ ! -f "$OUT" ] || [ "$OUT" -ot "$0" ]; then gcc -g -Wall -o "$OUT".$$ $0 -lm && mv "$OUT".$$ "$OUT"; fi; exec "$OUT" "$@" #include <stdio.h> #include <math.h> #include <stdlib.h> #include <assert.h> #include <string.h>
/* For convenience, avoid allocation */ #define MAX_HTLCS 1000
/* Percentage chance of HTLC being removed. */ #define REMOVE_CHANCE 25 /* Percentage chance of HTLC being added. */ #define ADD_CHANCE 50
#define BYTES_PER_HTLC 24 #define BACKREF_BYTES 16
static void add_some_htlcs(unsigned int htlcs[], size_t *n_htlcs,
size_t *counter)
{
/* Exponential distribution again. */
while (random() < (RAND_MAX * (long long)ADD_CHANCE / 100)) {
assert(*n_htlcs < MAX_HTLCS);
htlcs[*n_htlcs] = *counter;
(*counter)++;
(*n_htlcs)++;
}
}
static size_t calc_encoding(const unsigned int old_htlcs[], size_t n_old,
const unsigned int new_htlcs[], size_t n_new,
size_t prev_leaks)
{
size_t o, n, num_new = 0, num_old = 0;
size_t raw_bytes, bytes_using_backref;
/* Figure out number only in new, only in old. */
for (o = n = 0; o < n_old || n < n_new;) {
if (o == n_old) {
num_new++;
n++;
} else if (n == n_new) {
num_old++;
o++;
} else if (old_htlcs[o] == new_htlcs[n]) {
o++;
n++;
} else if (old_htlcs[o] < new_htlcs[n]) {
num_old++;
o++;
} else {
num_new++;
n++;
}
}
raw_bytes = n_new * BYTES_PER_HTLC; bytes_using_backref = num_new * BYTES_PER_HTLC + BACKREF_BYTES;
/* Num htlcs, raw-encoding, backref-encoding, encoding-used */
printf("%zu,%zu,%zu,", n_new, raw_bytes, bytes_using_backref);
/* Don't use backref if we would leak more than #current. */
if (!num_old || num_old + prev_leaks > n_new) {
printf("%zu\n", raw_bytes);
return 0;
} else {
printf("%zu\n", bytes_using_backref);
return num_old + prev_leaks;
}
}
static void iterate(unsigned int htlcs[], size_t *n_htlcs, size_t *counter,
size_t *leaks)
{
size_t i, num;
unsigned int tmp_htlcs[MAX_HTLCS];
/* REMOVE_CHANCE percentage chance of HTLC being closed. */
for (i = 0, num = 0; i < *n_htlcs; i++) {
if (random() < (RAND_MAX * (long long)REMOVE_CHANCE / 100))
continue;
tmp_htlcs[num++] = htlcs[i];
}
add_some_htlcs(tmp_htlcs, &num, counter);
*leaks = calc_encoding(htlcs, *n_htlcs, tmp_htlcs, num, *leaks); memcpy(htlcs, tmp_htlcs, num * sizeof(htlcs[0])); *n_htlcs = num; }
int main(int argc, char *argv[])
{
size_t i, n_iter;
unsigned int htlcs[MAX_HTLCS];
size_t n_htlcs = 0, counter = 0, leaks = 0;
printf("Num htlcs, raw-encoding bytes, backref-encoding bytes, best-encoding bytes\n");
n_iter = argv[1] ? atoi(argv[1]) : 100;
for (i = 0; i < n_iter; i++)
iterate(htlcs, &n_htlcs, &counter, &leaks);
return 0; }