Debian Codegraph @

tests/test_lnchannel.py

raw symbols SCIP
1 # Copyright (C) 2018 The Electrum developers
2 # Copyright (C) 2015-2018 The Lightning Network Developers
3 #
4 # Permission is hereby granted, free of charge, to any person obtaining a copy
5 # of this software and associated documentation files (the "Software"), to deal
6 # in the Software without restriction, including without limitation the rights
7 # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8 # copies of the Software, and to permit persons to whom the Software is
9 # furnished to do so, subject to the following conditions:
10 #
11 # The above copyright notice and this permission notice shall be included in
12 # all copies or substantial portions of the Software.
13 #
14 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17 # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18 # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19 # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
20 # THE SOFTWARE.
21 #
22 # Many of these unit tests are heavily based on unit tests in lnd
23 # (around commit 42de4400bff5105352d0552155f73589166d162b).
24
25 import unittest
26 from unittest import mock
27 import os
28 import logging
29 import dataclasses
30 import time
31
32 from electrum import bitcoin
33 from electrum import lnchannel
34 from electrum import lnutil
35 from electrum.crypto import sha256
36 from electrum.lnutil import (
37 SENT, LOCAL, REMOTE, RECEIVED, UpdateAddHtlc, ChannelType,
38 effective_htlc_tx_weight, ZEROCONF_TIMEOUT,
39 CHANNEL_OPENING_TIMEOUT_SEC,
40 )
41 from electrum.logging import console_stderr_handler
42 from electrum.lnchannel import ChannelState, Channel
43
44 from . import ElectrumTestCase
45 from .lnhelpers import create_test_channels
46
47
48 one_bitcoin_in_msat = bitcoin.COIN * 1000
49
50
51 class TestFee(ElectrumTestCase):
52 """
53 test
54 https://github.com/lightningnetwork/lightning-rfc/blob/e0c436bd7a3ed6a028e1cb472908224658a14eca/03-transactions.md#requirements-2
55 """
56
57 async def asyncSetUp(self):
58 await super().asyncSetUp()
59 self.alice_lnwallet = self.create_mock_lnwallet(name="alice")
60 self.bob_lnwallet = self.create_mock_lnwallet(name="bob")
61
62 async def test_fee(self):
63 alice_channel, bob_channel = create_test_channels(
64 feerate=253,
65 local_msat=10_000_000_000,
66 remote_msat=5_000_000_000,
67 alice_lnwallet=self.alice_lnwallet,
68 bob_lnwallet=self.bob_lnwallet,
69 )
70 expected_value = 9_999_056 if self.TEST_ANCHOR_CHANNELS else 9_999_817
71 self.assertIn(expected_value, [x.value for x in alice_channel.get_latest_commitment(LOCAL).outputs()])
72
73
74 class TestChannel(ElectrumTestCase):
75 maxDiff = 999
76
77 def assertOutputExistsByValue(self, tx, amt_sat):
78 for o in tx.outputs():
79 if o.value == amt_sat:
80 break
81 else:
82 self.assertFalse()
83
84 def assertNumberNonAnchorOutputs(self, number, tx):
85 self.assertEqual(number, len(tx.outputs()) - (2 if self.TEST_ANCHOR_CHANNELS else 0))
86
87 @classmethod
88 def setUpClass(cls):
89 super().setUpClass()
90 console_stderr_handler.setLevel(logging.DEBUG)
91
92 async def asyncSetUp(self):
93 await super().asyncSetUp()
94 self.alice_lnwallet = self.create_mock_lnwallet(name="alice")
95 self.bob_lnwallet = self.create_mock_lnwallet(name="bob")
96
97 # Create a test channel which will be used for the duration of this
98 # unittest. The channel will be funded evenly with Alice having 5 BTC,
99 # and Bob having 5 BTC.
100 self.alice_channel, self.bob_channel = create_test_channels(
101 alice_lnwallet=self.alice_lnwallet, bob_lnwallet=self.bob_lnwallet)
102
103 self.paymentPreimage = b"\x01" * 32
104 paymentHash = bitcoin.sha256(self.paymentPreimage)
105 self.htlc = UpdateAddHtlc(
106 payment_hash=paymentHash,
107 amount_msat=one_bitcoin_in_msat,
108 cltv_abs=5,
109 timestamp=0,
110 )
111
112 # First Alice adds the outgoing HTLC to her local channel's state
113 # update log. Then Alice sends this wire message over to Bob who adds
114 # this htlc to his remote state update log.
115 self.aliceHtlcIndex = self.alice_channel.add_htlc(self.htlc).htlc_id
116 self.assertNotEqual(list(self.alice_channel.hm.htlcs_by_direction(REMOTE, RECEIVED, 1).values()), [])
117
118 before = self.bob_channel.balance_minus_outgoing_htlcs(REMOTE)
119 beforeLocal = self.bob_channel.balance_minus_outgoing_htlcs(LOCAL)
120
121 self.bobHtlcIndex = self.bob_channel.receive_htlc(self.htlc).htlc_id
122
123 self.htlc = self.bob_channel.hm.log[REMOTE]['adds'][0]
124
125 def test_concurrent_reversed_payment(self):
126 self.htlc = dataclasses.replace(
127 self.htlc,
128 payment_hash=bitcoin.sha256(32 * b'\x02'),
129 amount_msat=self.htlc.amount_msat + 1000,
130 )
131 self.bob_channel.add_htlc(self.htlc)
132 self.alice_channel.receive_htlc(self.htlc)
133
134 self.assertNumberNonAnchorOutputs(2, self.alice_channel.get_latest_commitment(LOCAL))
135 self.assertNumberNonAnchorOutputs(3, self.alice_channel.get_next_commitment(LOCAL))
136 self.assertNumberNonAnchorOutputs(2, self.alice_channel.get_latest_commitment(REMOTE))
137 self.assertNumberNonAnchorOutputs(3, self.alice_channel.get_next_commitment(REMOTE))
138
139 self.alice_channel.receive_new_commitment(*self.bob_channel.sign_next_commitment())
140
141 self.assertNumberNonAnchorOutputs(3, self.alice_channel.get_latest_commitment(LOCAL))
142 self.assertNumberNonAnchorOutputs(3, self.alice_channel.get_next_commitment(LOCAL))
143 self.assertNumberNonAnchorOutputs(2, self.alice_channel.get_latest_commitment(REMOTE))
144 self.assertNumberNonAnchorOutputs(3, self.alice_channel.get_next_commitment(REMOTE))
145
146 self.alice_channel.revoke_current_commitment()
147
148 self.assertNumberNonAnchorOutputs(3, self.alice_channel.get_latest_commitment(LOCAL))
149 self.assertNumberNonAnchorOutputs(3, self.alice_channel.get_next_commitment(LOCAL))
150 self.assertNumberNonAnchorOutputs(2, self.alice_channel.get_latest_commitment(REMOTE))
151 self.assertNumberNonAnchorOutputs(4, self.alice_channel.get_next_commitment(REMOTE))
152
153 async def test_SimpleAddSettleWorkflow(self):
154 alice_channel, bob_channel = self.alice_channel, self.bob_channel
155 htlc = self.htlc
156
157 # Starting point: alice has sent an update_add_htlc message to bob
158 # but the htlc is not yet committed to
159 alice_out = alice_channel.get_latest_commitment(LOCAL).outputs()
160 if not alice_channel.has_anchors():
161 # ctx outputs are ordered by increasing amounts
162 low_amt_idx = 0
163 assert len(alice_out[low_amt_idx].address) == 62 # p2wsh
164 high_amt_idx = 1
165 assert len(alice_out[high_amt_idx].address) == 42 # p2wpkh
166 else:
167 # using anchor outputs, all outputs are p2wsh
168 low_amt_idx = 2
169 assert len(alice_out[low_amt_idx].address) == 62
170 high_amt_idx = 3
171 assert len(alice_out[high_amt_idx].address) == 62
172 self.assertLess(alice_out[low_amt_idx].value, 5 * 10**8, alice_out)
173 self.assertEqual(alice_out[high_amt_idx].value, 5 * 10**8, alice_out)
174
175 alice_out = alice_channel.get_latest_commitment(REMOTE).outputs()
176 if not alice_channel.has_anchors():
177 low_amt_idx = 0
178 assert len(alice_out[low_amt_idx].address) == 42
179 high_amt_idx = 1
180 assert len(alice_out[high_amt_idx].address) == 62
181 else:
182 low_amt_idx = 2
183 assert len(alice_out[low_amt_idx].address) == 62
184 high_amt_idx = 3
185 assert len(alice_out[high_amt_idx].address) == 62
186 self.assertLess(alice_out[low_amt_idx].value, 5 * 10**8)
187 self.assertEqual(alice_out[high_amt_idx].value, 5 * 10**8)
188
189 self.assertTrue(alice_channel.signature_fits(alice_channel.get_latest_commitment(LOCAL)))
190
191 self.assertNotEqual(alice_channel.included_htlcs(REMOTE, RECEIVED, 1), [])
192
193 self.assertEqual(alice_channel.included_htlcs(REMOTE, RECEIVED, 0), [])
194 self.assertEqual(alice_channel.included_htlcs(REMOTE, RECEIVED, 1), [htlc])
195
196 self.assertEqual(bob_channel.included_htlcs(REMOTE, SENT, 0), [])
197 self.assertEqual(bob_channel.included_htlcs(REMOTE, SENT, 1), [])
198
199 self.assertEqual(alice_channel.included_htlcs(REMOTE, SENT, 0), [])
200 self.assertEqual(alice_channel.included_htlcs(REMOTE, SENT, 1), [])
201
202 self.assertEqual(bob_channel.included_htlcs(REMOTE, RECEIVED, 0), [])
203 self.assertEqual(bob_channel.included_htlcs(REMOTE, RECEIVED, 1), [])
204
205 from electrum.lnutil import extract_ctn_from_tx_and_chan
206 tx0 = str(alice_channel.force_close_tx())
207 self.assertEqual(alice_channel.get_oldest_unrevoked_ctn(LOCAL), 0)
208 self.assertEqual(extract_ctn_from_tx_and_chan(alice_channel.force_close_tx(), alice_channel), 0)
209 self.assertTrue(alice_channel.signature_fits(alice_channel.get_latest_commitment(LOCAL)))
210
211 # Next alice commits this change by sending a signature message. Since
212 # we expect the messages to be ordered, Bob will receive the HTLC we
213 # just sent before he receives this signature, so the signature will
214 # cover the HTLC.
215 aliceSig, aliceHtlcSigs = alice_channel.sign_next_commitment()
216 self.assertEqual(len(aliceHtlcSigs), 1, "alice should generate one htlc signature")
217
218 self.assertTrue(alice_channel.signature_fits(alice_channel.get_latest_commitment(LOCAL)))
219
220 self.assertEqual(next(iter(alice_channel.hm.get_htlcs_in_next_ctx(REMOTE)))[0], RECEIVED)
221 self.assertEqual(alice_channel.hm.get_htlcs_in_next_ctx(REMOTE), bob_channel.hm.get_htlcs_in_next_ctx(LOCAL))
222 self.assertEqual(alice_channel.get_latest_commitment(REMOTE).outputs(), bob_channel.get_next_commitment(LOCAL).outputs())
223
224 # Bob receives this signature message, and checks that this covers the
225 # state he has in his remote log. This includes the HTLC just sent
226 # from Alice.
227 self.assertTrue(bob_channel.signature_fits(bob_channel.get_latest_commitment(LOCAL)))
228 bob_channel.receive_new_commitment(aliceSig, aliceHtlcSigs)
229 self.assertTrue(bob_channel.signature_fits(bob_channel.get_latest_commitment(LOCAL)))
230
231 self.assertEqual(bob_channel.get_oldest_unrevoked_ctn(REMOTE), 0)
232 self.assertEqual(bob_channel.included_htlcs(LOCAL, RECEIVED, 1), [htlc])
233
234 self.assertEqual(alice_channel.included_htlcs(REMOTE, RECEIVED, 0), [])
235 self.assertEqual(alice_channel.included_htlcs(REMOTE, RECEIVED, 1), [htlc])
236
237 self.assertEqual(alice_channel.included_htlcs(REMOTE, SENT, 0), [])
238 self.assertEqual(alice_channel.included_htlcs(REMOTE, SENT, 1), [])
239
240 self.assertEqual(bob_channel.included_htlcs(REMOTE, RECEIVED, 0), [])
241 self.assertEqual(bob_channel.included_htlcs(REMOTE, RECEIVED, 1), [])
242
243 # Bob revokes his prior commitment given to him by Alice, since he now
244 # has a valid signature for a newer commitment.
245 bobRevocation = bob_channel.revoke_current_commitment()
246 self.assertTrue(bob_channel.signature_fits(bob_channel.get_latest_commitment(LOCAL)))
247
248 # Bob finally sends a signature for Alice's commitment transaction.
249 # This signature will cover the HTLC, since Bob will first send the
250 # revocation just created. The revocation also acks every received
251 # HTLC up to the point where Alice sent her signature.
252 bobSig, bobHtlcSigs = bob_channel.sign_next_commitment()
253 self.assertTrue(bob_channel.signature_fits(bob_channel.get_latest_commitment(LOCAL)))
254
255 self.assertEqual(len(bobHtlcSigs), 1)
256
257 self.assertTrue(alice_channel.signature_fits(alice_channel.get_latest_commitment(LOCAL)))
258
259 # so far: Alice added htlc, Alice signed.
260 self.assertNumberNonAnchorOutputs(2, alice_channel.get_latest_commitment(LOCAL))
261 self.assertNumberNonAnchorOutputs(2, alice_channel.get_next_commitment(LOCAL))
262 self.assertNumberNonAnchorOutputs(2, alice_channel.get_oldest_unrevoked_commitment(REMOTE))
263 self.assertNumberNonAnchorOutputs(3, alice_channel.get_latest_commitment(REMOTE))
264
265 # Alice then processes this revocation, sending her own revocation for
266 # her prior commitment transaction. Alice shouldn't have any HTLCs to
267 # forward since she's sending an outgoing HTLC.
268 alice_channel.receive_revocation(bobRevocation)
269
270 self.assertTrue(alice_channel.signature_fits(alice_channel.get_latest_commitment(LOCAL)))
271
272 self.assertNumberNonAnchorOutputs(2, alice_channel.get_latest_commitment(LOCAL))
273 self.assertNumberNonAnchorOutputs(3, alice_channel.get_latest_commitment(REMOTE))
274 self.assertNumberNonAnchorOutputs(2, alice_channel.force_close_tx())
275
276 self.assertEqual(len(alice_channel.hm.log[LOCAL]['adds']), 1)
277 self.assertEqual(alice_channel.get_next_commitment(LOCAL).outputs(),
278 bob_channel.get_latest_commitment(REMOTE).outputs())
279
280 # Alice then processes bob's signature, and since she just received
281 # the revocation, she expects this signature to cover everything up to
282 # the point where she sent her signature, including the HTLC.
283 alice_channel.receive_new_commitment(bobSig, bobHtlcSigs)
284
285 self.assertNumberNonAnchorOutputs(3, alice_channel.get_latest_commitment(REMOTE))
286 self.assertNumberNonAnchorOutputs(3, alice_channel.force_close_tx())
287
288 self.assertEqual(len(alice_channel.hm.log[LOCAL]['adds']), 1)
289
290 tx1 = str(alice_channel.force_close_tx())
291 self.assertNotEqual(tx0, tx1)
292
293 # Alice then generates a revocation for bob.
294 aliceRevocation = alice_channel.revoke_current_commitment()
295
296 tx2 = str(alice_channel.force_close_tx())
297 # since alice already has the signature for the next one, it doesn't change her force close tx (it was already the newer one)
298 self.assertEqual(tx1, tx2)
299
300 # Finally Bob processes Alice's revocation, at this point the new HTLC
301 # is fully locked in within both commitment transactions. Bob should
302 # also be able to forward an HTLC now that the HTLC has been locked
303 # into both commitment transactions.
304 self.assertTrue(bob_channel.signature_fits(bob_channel.get_latest_commitment(LOCAL)))
305 bob_channel.receive_revocation(aliceRevocation)
306
307 # At this point, both sides should have the proper number of satoshis
308 # sent, and commitment height updated within their local channel
309 # state.
310 aliceSent = 0
311 bobSent = 0
312
313 self.assertEqual(alice_channel.total_msat(SENT), aliceSent, "alice has incorrect milli-satoshis sent")
314 self.assertEqual(alice_channel.total_msat(RECEIVED), bobSent, "alice has incorrect milli-satoshis received")
315 self.assertEqual(bob_channel.total_msat(SENT), bobSent, "bob has incorrect milli-satoshis sent")
316 self.assertEqual(bob_channel.total_msat(RECEIVED), aliceSent, "bob has incorrect milli-satoshis received")
317 self.assertEqual(bob_channel.get_oldest_unrevoked_ctn(LOCAL), 1, "bob has incorrect commitment height")
318 self.assertEqual(alice_channel.get_oldest_unrevoked_ctn(LOCAL), 1, "alice has incorrect commitment height")
319
320 # Both commitment transactions should have three outputs, and one of
321 # them should be exactly the amount of the HTLC.
322 alice_ctx = alice_channel.get_next_commitment(LOCAL)
323 bob_ctx = bob_channel.get_next_commitment(LOCAL)
324 self.assertNumberNonAnchorOutputs(3, alice_ctx)
325 self.assertNumberNonAnchorOutputs(3, bob_ctx)
326 self.assertOutputExistsByValue(alice_ctx, htlc.amount_msat // 1000)
327 self.assertOutputExistsByValue(bob_ctx, htlc.amount_msat // 1000)
328
329 # Now we'll repeat a similar exchange, this time with Bob settling the
330 # HTLC once he learns of the preimage.
331 preimage = self.paymentPreimage
332 bob_channel.settle_htlc(preimage, self.bobHtlcIndex)
333
334 alice_channel.receive_htlc_settle(preimage, self.aliceHtlcIndex)
335
336 tx3 = str(alice_channel.force_close_tx())
337 # just settling a htlc does not change her force close tx
338 self.assertEqual(tx2, tx3)
339
340 bobSig2, bobHtlcSigs2 = bob_channel.sign_next_commitment()
341 self.assertEqual(len(bobHtlcSigs2), 0)
342
343 self.assertEqual(list(alice_channel.hm.htlcs_by_direction(REMOTE, RECEIVED).values()), [htlc])
344 self.assertEqual(alice_channel.included_htlcs(REMOTE, RECEIVED, alice_channel.get_oldest_unrevoked_ctn(REMOTE)), [htlc])
345
346 self.assertEqual(alice_channel.included_htlcs(REMOTE, RECEIVED, 1), [htlc])
347 self.assertEqual(alice_channel.included_htlcs(REMOTE, RECEIVED, 2), [htlc])
348
349 self.assertEqual(bob_channel.included_htlcs(REMOTE, SENT, 1), [htlc])
350 self.assertEqual(bob_channel.included_htlcs(REMOTE, SENT, 2), [])
351
352 self.assertEqual(alice_channel.included_htlcs(REMOTE, SENT, 1), [])
353 self.assertEqual(alice_channel.included_htlcs(REMOTE, SENT, 2), [])
354
355 self.assertEqual(bob_channel.included_htlcs(REMOTE, RECEIVED, 1), [])
356 self.assertEqual(bob_channel.included_htlcs(REMOTE, RECEIVED, 2), [])
357
358 alice_ctx_bob_version = bob_channel.get_latest_commitment(REMOTE).outputs()
359 alice_ctx_alice_version = alice_channel.get_next_commitment(LOCAL).outputs()
360 self.assertEqual(alice_ctx_alice_version, alice_ctx_bob_version)
361
362 alice_channel.receive_new_commitment(bobSig2, bobHtlcSigs2)
363
364 tx4 = str(alice_channel.force_close_tx())
365 self.assertNotEqual(tx3, tx4)
366
367 self.assertEqual(alice_channel.balance(LOCAL), 500000000000)
368 self.assertEqual(1, alice_channel.get_oldest_unrevoked_ctn(LOCAL))
369 self.assertEqual(len(alice_channel.included_htlcs(LOCAL, RECEIVED, ctn=2)), 0)
370 aliceRevocation2 = alice_channel.revoke_current_commitment()
371 aliceSig2, aliceHtlcSigs2 = alice_channel.sign_next_commitment()
372 self.assertEqual(aliceHtlcSigs2, [], "alice should generate no htlc signatures")
373 self.assertNumberNonAnchorOutputs(3, bob_channel.get_latest_commitment(LOCAL))
374 bob_channel.receive_revocation(aliceRevocation2)
375
376 bob_channel.receive_new_commitment(aliceSig2, aliceHtlcSigs2)
377
378 bobRevocation2 = bob_channel.revoke_current_commitment()
379 received = lnchannel.htlcsum(bob_channel.hm.received_in_ctn(bob_channel.get_latest_ctn(LOCAL)))
380 self.assertEqual(one_bitcoin_in_msat, received)
381 alice_channel.receive_revocation(bobRevocation2)
382
383 # At this point, Bob should have 6 BTC settled, with Alice still having
384 # 4 BTC. Alice's channel should show 1 BTC sent and Bob's channel
385 # should show 1 BTC received. They should also be at commitment height
386 # two, with the revocation window extended by 1 (5).
387 mSatTransferred = one_bitcoin_in_msat
388 self.assertEqual(alice_channel.total_msat(SENT), mSatTransferred, "alice satoshis sent incorrect")
389 self.assertEqual(alice_channel.total_msat(RECEIVED), 0, "alice satoshis received incorrect")
390 self.assertEqual(bob_channel.total_msat(RECEIVED), mSatTransferred, "bob satoshis received incorrect")
391 self.assertEqual(bob_channel.total_msat(SENT), 0, "bob satoshis sent incorrect")
392 self.assertEqual(bob_channel.get_latest_ctn(LOCAL), 2, "bob has incorrect commitment height")
393 self.assertEqual(alice_channel.get_latest_ctn(LOCAL), 2, "alice has incorrect commitment height")
394
395 alice_channel.update_fee(100000, True)
396 alice_outputs = alice_channel.get_next_commitment(REMOTE).outputs()
397 old_outputs = bob_channel.get_next_commitment(LOCAL).outputs()
398 bob_channel.update_fee(100000, False)
399 new_outputs = bob_channel.get_next_commitment(LOCAL).outputs()
400 self.assertNotEqual(old_outputs, new_outputs)
401 self.assertEqual(alice_outputs, new_outputs)
402
403 tx5 = str(alice_channel.force_close_tx())
404 # sending a fee update does not change her force close tx
405 self.assertEqual(tx4, tx5)
406
407 force_state_transition(alice_channel, bob_channel)
408
409 tx6 = str(alice_channel.force_close_tx())
410 self.assertNotEqual(tx5, tx6)
411
412 self.htlc = dataclasses.replace(
413 self.htlc,
414 amount_msat=self.htlc.amount_msat * 5,
415 )
416 bob_index = bob_channel.add_htlc(self.htlc).htlc_id
417 alice_index = alice_channel.receive_htlc(self.htlc).htlc_id
418
419 force_state_transition(bob_channel, alice_channel)
420
421 alice_channel.settle_htlc(self.paymentPreimage, alice_index)
422 bob_channel.receive_htlc_settle(self.paymentPreimage, bob_index)
423
424 force_state_transition(alice_channel, bob_channel)
425 self.assertEqual(alice_channel.total_msat(SENT), one_bitcoin_in_msat, "alice satoshis sent incorrect")
426 self.assertEqual(alice_channel.total_msat(RECEIVED), 5 * one_bitcoin_in_msat, "alice satoshis received incorrect")
427 self.assertEqual(bob_channel.total_msat(RECEIVED), one_bitcoin_in_msat, "bob satoshis received incorrect")
428 self.assertEqual(bob_channel.total_msat(SENT), 5 * one_bitcoin_in_msat, "bob satoshis sent incorrect")
429
430 def alice_to_bob_fee_update(self, fee=1111):
431 aoldctx = self.alice_channel.get_next_commitment(REMOTE).outputs()
432 self.alice_channel.update_fee(fee, True)
433 anewctx = self.alice_channel.get_next_commitment(REMOTE).outputs()
434 self.assertNotEqual(aoldctx, anewctx)
435 boldctx = self.bob_channel.get_next_commitment(LOCAL).outputs()
436 self.bob_channel.update_fee(fee, False)
437 bnewctx = self.bob_channel.get_next_commitment(LOCAL).outputs()
438 self.assertNotEqual(boldctx, bnewctx)
439 self.assertEqual(anewctx, bnewctx)
440 return fee
441
442 def test_UpdateFeeSenderCommits(self):
443 alice_channel, bob_channel = self.alice_channel, self.bob_channel
444
445 old_feerate = alice_channel.get_next_feerate(LOCAL)
446
447 fee = self.alice_to_bob_fee_update()
448 self.assertEqual(alice_channel.get_next_feerate(LOCAL), old_feerate)
449
450 alice_sig, alice_htlc_sigs = alice_channel.sign_next_commitment()
451 #self.assertEqual(alice_channel.get_next_feerate(LOCAL), old_feerate)
452
453 bob_channel.receive_new_commitment(alice_sig, alice_htlc_sigs)
454
455 self.assertNotEqual(fee, bob_channel.get_oldest_unrevoked_feerate(LOCAL))
456 self.assertEqual(fee, bob_channel.get_latest_feerate(LOCAL))
457 rev = bob_channel.revoke_current_commitment()
458 self.assertEqual(fee, bob_channel.get_oldest_unrevoked_feerate(LOCAL))
459
460 alice_channel.receive_revocation(rev)
461
462
463 bob_sig, bob_htlc_sigs = bob_channel.sign_next_commitment()
464 alice_channel.receive_new_commitment(bob_sig, bob_htlc_sigs)
465
466 self.assertNotEqual(fee, alice_channel.get_oldest_unrevoked_feerate(LOCAL))
467 self.assertEqual(fee, alice_channel.get_latest_feerate(LOCAL))
468 rev = alice_channel.revoke_current_commitment()
469 self.assertEqual(fee, alice_channel.get_oldest_unrevoked_feerate(LOCAL))
470
471 bob_channel.receive_revocation(rev)
472 self.assertEqual(fee, bob_channel.get_oldest_unrevoked_feerate(LOCAL))
473 self.assertEqual(fee, bob_channel.get_latest_feerate(LOCAL))
474
475
476 def test_UpdateFeeReceiverCommits(self):
477 fee = self.alice_to_bob_fee_update()
478
479 alice_channel, bob_channel = self.alice_channel, self.bob_channel
480
481 bob_sig, bob_htlc_sigs = bob_channel.sign_next_commitment()
482 alice_channel.receive_new_commitment(bob_sig, bob_htlc_sigs)
483
484 alice_revocation = alice_channel.revoke_current_commitment()
485 bob_channel.receive_revocation(alice_revocation)
486 alice_sig, alice_htlc_sigs = alice_channel.sign_next_commitment()
487 bob_channel.receive_new_commitment(alice_sig, alice_htlc_sigs)
488
489 self.assertNotEqual(fee, bob_channel.get_oldest_unrevoked_feerate(LOCAL))
490 self.assertEqual(fee, bob_channel.get_latest_feerate(LOCAL))
491 bob_revocation = bob_channel.revoke_current_commitment()
492 self.assertEqual(fee, bob_channel.get_oldest_unrevoked_feerate(LOCAL))
493
494 bob_sig, bob_htlc_sigs = bob_channel.sign_next_commitment()
495 alice_channel.receive_revocation(bob_revocation)
496 alice_channel.receive_new_commitment(bob_sig, bob_htlc_sigs)
497
498 self.assertNotEqual(fee, alice_channel.get_oldest_unrevoked_feerate(LOCAL))
499 self.assertEqual(fee, alice_channel.get_latest_feerate(LOCAL))
500 alice_revocation = alice_channel.revoke_current_commitment()
501 self.assertEqual(fee, alice_channel.get_oldest_unrevoked_feerate(LOCAL))
502
503 bob_channel.receive_revocation(alice_revocation)
504 self.assertEqual(fee, bob_channel.get_oldest_unrevoked_feerate(LOCAL))
505 self.assertEqual(fee, bob_channel.get_latest_feerate(LOCAL))
506
507 @unittest.skip("broken probably because we haven't implemented detecting when we come out of a situation where we violate reserve")
508 def test_AddHTLCNegativeBalance(self):
509 # the test in lnd doesn't set the fee to zero.
510 # probably lnd subtracts commitment fee after deciding weather
511 # an htlc can be added. so we set the fee to zero so that
512 # the test can work.
513 self.alice_to_bob_fee_update(0)
514 force_state_transition(self.alice_channel, self.bob_channel)
515
516 self.htlc = dataclasses.replace(
517 self.htlc,
518 payment_hash=bitcoin.sha256(32 * b'\x02'),
519 )
520 self.alice_channel.add_htlc(self.htlc)
521 self.htlc = dataclasses.replace(
522 self.htlc,
523 payment_hash=bitcoin.sha256(32 * b'\x03'),
524 )
525 self.alice_channel.add_htlc(self.htlc)
526 # now there are three htlcs (one was in setUp)
527
528 # Alice now has an available balance of 2 BTC. We'll add a new HTLC of
529 # value 2 BTC, which should make Alice's balance negative (since she
530 # has to pay a commitment fee).
531 new = dataclasses.replace(
532 self.htlc,
533 amount_msat=int(self.htlc.amount_msat * 2.5),
534 payment_hash=bitcoin.sha256(32 * b'\x04'),
535 )
536 with self.assertRaises(lnutil.PaymentFailure) as cm:
537 self.alice_channel.add_htlc(new)
538 self.assertIn('Not enough local balance', cm.exception.args[0])
539
540 def test_unfunded_channel_can_be_removed(self):
541 """
542 Test that an incoming channel which stays unfunded longer than
543 lnutil.CHANNEL_OPENING_TIMEOUT_BLOCKS and lnutil.CHANNEL_OPENING_TIMEOUT_SEC
544 can be removed
545 """
546 # set the init_height and init_timestamp
547 self.current_height = 800_000
548 self.bob_channel.storage['init_height'] = self.current_height
549 self.alice_channel.storage['init_height'] = self.current_height
550 self.bob_channel.storage['init_timestamp'] = int(time.time())
551 self.alice_channel.storage['init_timestamp'] = int(time.time())
552
553 mock_lnworker = mock.Mock()
554 mock_blockchain = mock.Mock()
555 mock_lnworker.wallet = mock.Mock()
556 mock_lnworker.wallet.is_up_to_date = lambda: True
557 mock_blockchain.is_tip_stale = lambda: False
558 mock_lnworker.network.blockchain = lambda: mock_blockchain
559 mock_lnworker.network.get_local_height = lambda: self.current_height
560 self.bob_channel.lnworker = mock_lnworker
561 self.alice_channel.lnworker = mock_lnworker
562
563 # test that the non-initiator can remove the channel after timeout
564 self.assertFalse(self.bob_channel.is_initiator())
565 self.bob_channel._state = ChannelState.OPENING
566 self.assertFalse(self.bob_channel.can_be_deleted())
567 self.current_height += lnutil.CHANNEL_OPENING_TIMEOUT_BLOCKS + 1
568 self.assertFalse(self.bob_channel.can_be_deleted()) # needs both block and time based timeout
569 self.bob_channel.storage['init_timestamp'] -= lnutil.CHANNEL_OPENING_TIMEOUT_SEC + 1
570 self.alice_channel.storage['init_timestamp'] -= lnutil.CHANNEL_OPENING_TIMEOUT_SEC + 1
571 self.assertTrue(self.bob_channel.can_be_deleted()) # now both timeouts are reached
572 self.current_height = 800_000 # reset to check if we can delete with just the time based timeout
573 self.assertFalse(self.bob_channel.can_be_deleted())
574
575 # test that the initiator can't remove the channel, even after timeout
576 self.current_height += lnutil.CHANNEL_OPENING_TIMEOUT_BLOCKS + 1
577 self.assertTrue(self.alice_channel.is_initiator())
578 self.alice_channel._state = ChannelState.OPENING
579 self.assertFalse(self.alice_channel.can_be_deleted())
580
581 async def test_update_unfunded_zeroconf_channel(self):
582 """Cover the zeroconf branch of update_unfunded_state"""
583 chan = self.bob_channel
584 chan.set_state(ChannelState.OPEN, force=True)
585 bob = self.bob_lnwallet
586 self.assertFalse(chan.is_initiator())
587 trusted_node = f"{chan.node_id.hex()}@127.0.0.1:9735"
588 chan.storage['channel_type'] |= ChannelType.OPTION_ZEROCONF
589 self.assertTrue(chan.is_zeroconf())
590 # add channel to lnwallet/db
591 bob._channels[chan.channel_id] = chan
592 bob.db.get('channels')[chan.channel_id.hex()] = "something"
593 self.assertIsNotNone(bob.get_channel_by_id(chan.channel_id))
594 chan.storage['init_height'] = 0 # checked by has_funding_timed_out
595 chan.storage['init_timestamp'] = int(time.time())
596 self.assertEqual(chan.get_state(), ChannelState.OPEN)
597 self.assertEqual(chan.balance(LOCAL), 500000000000)
598 bob.config.ZEROCONF_TRUSTED_NODE = trusted_node
599
600 chan.update_unfunded_state()
601
602 # assert nothing happened
603 self.assertIsNotNone(bob.get_channel_by_id(chan.channel_id))
604 self.assertIsNotNone(bob.db.get('channels').get(chan.channel_id.hex()))
605 self.assertEqual(chan.get_state(), ChannelState.OPEN)
606 self.assertEqual(bob.config.ZEROCONF_TRUSTED_NODE, trusted_node)
607
608 # now time out zeroconf funding and try again, however her wallet is not up to date
609 chan.storage['init_timestamp'] -= ZEROCONF_TIMEOUT + 1
610 bob.wallet.is_up_to_date = lambda: False
611
612 chan.update_unfunded_state()
613
614 # assert nothing happened again
615 self.assertIsNotNone(bob.get_channel_by_id(chan.channel_id))
616 self.assertIsNotNone(bob.db.get('channels').get(chan.channel_id.hex()))
617 self.assertEqual(chan.get_state(), ChannelState.OPEN)
618 self.assertEqual(bob.config.ZEROCONF_TRUSTED_NODE, trusted_node)
619 self.assertFalse(chan.is_frozen_for_receiving())
620
621 # now her wallet is synced, and the channel is still unfunded
622 bob.wallet.is_up_to_date = lambda: True
623
624 chan.update_unfunded_state()
625
626 # check zeroconf provider gets unset
627 self.assertEqual(bob.config.ZEROCONF_TRUSTED_NODE, "")
628 self.assertFalse(chan.has_funding_timed_out())
629 self.assertTrue(chan.is_frozen_for_receiving())
630
631 # time out funding (~2 weeks)
632 chan.storage['init_timestamp'] -= CHANNEL_OPENING_TIMEOUT_SEC + 1
633 self.assertTrue(chan.has_funding_timed_out())
634
635 chan.update_unfunded_state()
636
637 # check that channel got removed, now that funding has timed out
638 self.assertIsNone(self.alice_lnwallet.get_channel_by_id(chan.channel_id))
639 self.assertIsNone(self.alice_lnwallet.db.get('channels').get(chan.channel_id.hex()))
640
641 async def test_should_be_closed_due_to_expiring_htlcs_offered_htlcs(self):
642 alice_lnwallet = self.create_mock_lnwallet(name="alice")
643 bob_lnwallet = self.create_mock_lnwallet(name="bob")
644 alice_channel, bob_channel = create_test_channels(alice_lnwallet=alice_lnwallet, bob_lnwallet=bob_lnwallet)
645
646 # no htlcs
647 self.assertFalse(alice_channel.should_be_closed_due_to_expiring_htlcs(local_height=100))
648
649 # one offered htlc, not expired
650 htlc = UpdateAddHtlc(payment_hash=sha256(os.urandom(32)), amount_msat=one_bitcoin_in_msat, cltv_abs=1000)
651 alice_channel.add_htlc(htlc)
652 alice_channel.sign_next_commitment()
653 self.assertFalse(alice_channel.should_be_closed_due_to_expiring_htlcs(local_height=100))
654
655 # expired offered htlc, within startup grace period
656 expired_local_height = 1000 + lnutil.NBLOCK_DEADLINE_DELTA_AFTER_EXPIRY_FOR_OFFERED_HTLCS + 5
657 self.assertFalse(alice_channel.should_be_closed_due_to_expiring_htlcs(expired_local_height))
658
659 # expired offered htlc, past startup grace period
660 alice_lnwallet.instantiation_timestamp -= (lnutil.TIME_FOR_OFFERED_HTLCS_TO_GET_FAILED_OFFCHAIN_ON_RESTART + 10)
661 self.assertTrue(alice_channel.should_be_closed_due_to_expiring_htlcs(expired_local_height))
662
663 async def test_should_be_closed_due_to_expiring_htlcs_received_htlcs(self):
664 alice_lnwallet = self.create_mock_lnwallet(name="alice")
665 bob_lnwallet = self.create_mock_lnwallet(name="bob")
666 alice_channel, bob_channel = create_test_channels(alice_lnwallet=alice_lnwallet, bob_lnwallet=bob_lnwallet)
667
668 preimage = os.urandom(32)
669 htlc = UpdateAddHtlc(payment_hash=sha256(preimage), amount_msat=one_bitcoin_in_msat, cltv_abs=100)
670 expired_height = 100 + lnutil.NBLOCK_DEADLINE_DELTA_BEFORE_EXPIRY_FOR_RECEIVED_HTLCS + 5
671 alice_channel.add_htlc(htlc)
672 bob_htlc_id = bob_channel.receive_htlc(htlc).htlc_id
673 force_state_transition(alice_channel, bob_channel)
674
675 # preimage wasn't released
676 self.assertFalse(bob_channel.should_be_closed_due_to_expiring_htlcs(local_height=expired_height))
677
678 # now the preimage is released
679 bob_channel.settle_htlc(preimage, bob_htlc_id)
680
681 # still in 30s grace period waiting for peers revack
682 self.assertFalse(bob_channel.should_be_closed_due_to_expiring_htlcs(local_height=expired_height))
683
684 # now the settled htlc is past the grace period
685 bob_channel.htlc_settle_time[bob_htlc_id] = int(time.time()) - 60
686 self.assertTrue(bob_channel.should_be_closed_due_to_expiring_htlcs(local_height=expired_height))
687
688
689 class TestChannelNoAnchors(TestChannel):
690 assert TestChannel.TEST_ANCHOR_CHANNELS is True
691 TEST_ANCHOR_CHANNELS = False
692
693
694 class TestAvailableToSpend(ElectrumTestCase):
695 async def asyncSetUp(self):
696 await super().asyncSetUp()
697 self.alice_lnwallet = self.create_mock_lnwallet(name="alice")
698 self.bob_lnwallet = self.create_mock_lnwallet(name="bob")
699
700 async def test_DesyncHTLCs(self):
701 alice_channel, bob_channel = create_test_channels(
702 alice_lnwallet=self.alice_lnwallet, bob_lnwallet=self.bob_lnwallet)
703 self.assertEqual(499986152000 if not alice_channel.has_anchors() else 499980692000, alice_channel.available_to_spend(LOCAL))
704 self.assertEqual(500000000000, bob_channel.available_to_spend(LOCAL))
705
706 paymentPreimage = b"\x01" * 32
707 paymentHash = bitcoin.sha256(paymentPreimage)
708 htlc = UpdateAddHtlc(
709 payment_hash=paymentHash,
710 amount_msat=one_bitcoin_in_msat * 41 // 10,
711 cltv_abs=5,
712 timestamp=0,
713 )
714
715 alice_idx = alice_channel.add_htlc(htlc).htlc_id
716 bob_idx = bob_channel.receive_htlc(htlc).htlc_id
717 self.assertEqual(89984088000 if not alice_channel.has_anchors() else 89978628000, alice_channel.available_to_spend(LOCAL))
718 self.assertEqual(500000000000, bob_channel.available_to_spend(LOCAL))
719
720 force_state_transition(alice_channel, bob_channel)
721 bob_channel.fail_htlc(bob_idx)
722 alice_channel.receive_fail_htlc(alice_idx, error_bytes=None)
723 self.assertEqual(89984088000 if not alice_channel.has_anchors() else 89978628000, alice_channel.available_to_spend(LOCAL))
724 self.assertEqual(500000000000, bob_channel.available_to_spend(LOCAL))
725 # Alice now has gotten all her original balance (5 BTC) back, however,
726 # adding a new HTLC at this point SHOULD fail, since if she adds the
727 # HTLC and signs the next state, Bob cannot assume she received the
728 # FailHTLC, and must assume she doesn't have the necessary balance
729 # available.
730 # We try adding an HTLC of value 1 BTC, which should fail because the
731 # balance is unavailable.
732 htlc = UpdateAddHtlc(
733 payment_hash=paymentHash,
734 amount_msat=one_bitcoin_in_msat,
735 cltv_abs=5,
736 timestamp=0,
737 )
738 with self.assertRaises(lnutil.PaymentFailure):
739 alice_channel.add_htlc(htlc)
740 # Now do a state transition, which will ACK the FailHTLC, making Alice
741 # able to add the new HTLC.
742 force_state_transition(alice_channel, bob_channel)
743 self.assertEqual(499986152000 if not alice_channel.has_anchors() else 499980692000, alice_channel.available_to_spend(LOCAL))
744 self.assertEqual(500000000000, bob_channel.available_to_spend(LOCAL))
745 alice_channel.add_htlc(htlc)
746
747 async def test_single_payment(self):
748 alice_channel, bob_channel = create_test_channels(
749 local_msat=4000000000,
750 remote_msat=4000000000,
751 local_max_inflight=1000000000,
752 remote_max_inflight=2000000000,
753 alice_lnwallet=self.alice_lnwallet,
754 bob_lnwallet=self.bob_lnwallet,
755 )
756
757 # alice can send 20 but bob can only receive 10, because of stricter receiving rules
758 self.assertEqual(2000000000, alice_channel.available_to_spend(LOCAL))
759 self.assertEqual(1000000000, bob_channel.available_to_spend(REMOTE))
760
761 # bob can send 10, alice can receive 10
762 self.assertEqual(1000000000, bob_channel.available_to_spend(LOCAL))
763 self.assertEqual(1000000000, alice_channel.available_to_spend(REMOTE))
764
765 paymentPreimage1 = b"\x01" * 32
766 htlc = UpdateAddHtlc(
767 payment_hash=bitcoin.sha256(paymentPreimage1),
768 amount_msat=1000000000,
769 cltv_abs=5,
770 timestamp=0,
771 )
772 # put 10mBTC inflight a->b
773 alice_idx1 = alice_channel.add_htlc(htlc).htlc_id
774 bob_idx1 = bob_channel.receive_htlc(htlc).htlc_id
775 force_state_transition(alice_channel, bob_channel)
776
777 self.assertEqual(1000000000, alice_channel.available_to_spend(LOCAL))
778 self.assertEqual(0, bob_channel.available_to_spend(REMOTE))
779
780 self.assertEqual(1000000000, bob_channel.available_to_spend(LOCAL))
781 self.assertEqual(1000000000, alice_channel.available_to_spend(REMOTE))
782
783 paymentPreimage2 = b"\x02" * 32
784 htlc2 = UpdateAddHtlc(
785 payment_hash=bitcoin.sha256(paymentPreimage2),
786 amount_msat=1500000000,
787 cltv_abs=5,
788 timestamp=0,
789 )
790 # try to add another 15mBTC HTLC while 15mBTC already inflight
791 with self.assertRaises(lnutil.PaymentFailure):
792 alice_idx2 = alice_channel.add_htlc(htlc2).htlc_id
793
794 # settle htlc 1 to clear inflight
795 bob_channel.settle_htlc(paymentPreimage1, bob_idx1)
796 alice_channel.receive_htlc_settle(paymentPreimage1, alice_idx1)
797 force_state_transition(alice_channel, bob_channel)
798
799 self.assertEqual(2000000000, alice_channel.available_to_spend(LOCAL))
800 self.assertEqual(1000000000, alice_channel.available_to_spend(REMOTE))
801
802 self.assertEqual(1000000000, bob_channel.available_to_spend(LOCAL))
803 self.assertEqual(1000000000, alice_channel.available_to_spend(REMOTE))
804
805
806 class TestAvailableToSpendNoAnchors(TestAvailableToSpend):
807 assert TestAvailableToSpend.TEST_ANCHOR_CHANNELS is True
808 TEST_ANCHOR_CHANNELS = False
809
810
811 class TestChanReserve(ElectrumTestCase):
812 async def asyncSetUp(self):
813 await super().asyncSetUp()
814 alice_lnwallet = self.create_mock_lnwallet(name="alice")
815 bob_lnwallet = self.create_mock_lnwallet(name="bob")
816 alice_channel, bob_channel = create_test_channels(alice_lnwallet=alice_lnwallet, bob_lnwallet=bob_lnwallet)
817 alice_min_reserve = int(.5 * one_bitcoin_in_msat // 1000)
818 # We set Bob's channel reserve to a value that is larger than
819 # his current balance in the channel. This will ensure that
820 # after a channel is first opened, Bob can still receive HTLCs
821 # even though his balance is less than his channel reserve.
822 bob_min_reserve = 6 * one_bitcoin_in_msat // 1000
823 # bob min reserve was decided by alice, but applies to bob
824
825 alice_channel.config[LOCAL].reserve_sat = bob_min_reserve
826 alice_channel.config[REMOTE].reserve_sat = alice_min_reserve
827
828 bob_channel.config[LOCAL].reserve_sat = alice_min_reserve
829 bob_channel.config[REMOTE].reserve_sat = bob_min_reserve
830
831 self.alice_channel = alice_channel
832 self.bob_channel = bob_channel
833
834 @unittest.skip("broken probably because we haven't implemented detecting when we come out of a situation where we violate reserve")
835 def test_part1(self):
836 # Add an HTLC that will increase Bob's balance. This should succeed,
837 # since Alice stays above her channel reserve, and Bob increases his
838 # balance (while still being below his channel reserve).
839 #
840 # Resulting balances:
841 # Alice: 4.5
842 # Bob: 5.0
843 paymentPreimage = b"\x01" * 32
844 paymentHash = bitcoin.sha256(paymentPreimage)
845 htlc = UpdateAddHtlc(
846 payment_hash=paymentHash,
847 amount_msat=int(.5 * one_bitcoin_in_msat),
848 cltv_abs=5,
849 timestamp=0,
850 )
851 self.alice_channel.add_htlc(htlc)
852 self.bob_channel.receive_htlc(htlc)
853 # Force a state transition, making sure this HTLC is considered valid
854 # even though the channel reserves are not met.
855 force_state_transition(self.alice_channel, self.bob_channel)
856
857 aliceSelfBalance = self.alice_channel.balance(LOCAL)\
858 - lnchannel.htlcsum(self.alice_channel.hm.htlcs_by_direction(LOCAL, SENT).values())
859 bobBalance = self.bob_channel.balance(REMOTE)\
860 - lnchannel.htlcsum(self.alice_channel.hm.htlcs_by_direction(REMOTE, SENT).values())
861 self.assertEqual(aliceSelfBalance, one_bitcoin_in_msat*4.5)
862 self.assertEqual(bobBalance, one_bitcoin_in_msat*5)
863 # Now let Bob try to add an HTLC. This should fail, since it will
864 # decrease his balance, which is already below the channel reserve.
865 #
866 # Resulting balances:
867 # Alice: 4.5
868 # Bob: 5.0
869 with self.assertRaises(lnutil.PaymentFailure):
870 htlc = dataclasses.replace(htlc, payment_hash=bitcoin.sha256(32 * b'\x02'))
871 self.bob_channel.add_htlc(htlc)
872 with self.assertRaises(lnutil.RemoteMisbehaving):
873 self.alice_channel.receive_htlc(htlc)
874
875 def part2(self):
876 paymentPreimage = b"\x01" * 32
877 paymentHash = bitcoin.sha256(paymentPreimage)
878 # Now we'll add HTLC of 3.5 BTC to Alice's commitment, this should put
879 # Alice's balance at 1.5 BTC.
880 #
881 # Resulting balances:
882 # Alice: 1.5
883 # Bob: 9.5
884 htlc = UpdateAddHtlc(
885 payment_hash=paymentHash,
886 amount_msat=int(3.5 * one_bitcoin_in_msat),
887 cltv_abs=5,
888 )
889 self.alice_channel.add_htlc(htlc)
890 self.bob_channel.receive_htlc(htlc)
891 # Add a second HTLC of 1 BTC. This should fail because it will take
892 # Alice's balance all the way down to her channel reserve, but since
893 # she is the initiator the additional transaction fee makes her
894 # balance dip below.
895 htlc = dataclasses.replace(htlc, amount_msat=one_bitcoin_in_msat)
896 with self.assertRaises(lnutil.PaymentFailure):
897 self.alice_channel.add_htlc(htlc)
898 with self.assertRaises(lnutil.RemoteMisbehaving):
899 self.bob_channel.receive_htlc(htlc)
900
901 def part3(self):
902 # Add a HTLC of 2 BTC to Alice, and the settle it.
903 # Resulting balances:
904 # Alice: 3.0
905 # Bob: 7.0
906 paymentPreimage = b"\x01" * 32
907 paymentHash = bitcoin.sha256(paymentPreimage)
908 htlc = UpdateAddHtlc(
909 payment_hash=paymentHash,
910 amount_msat=int(2 * one_bitcoin_in_msat),
911 cltv_abs=5,
912 timestamp=0,
913 )
914 alice_idx = self.alice_channel.add_htlc(htlc).htlc_id
915 bob_idx = self.bob_channel.receive_htlc(htlc).htlc_id
916 force_state_transition(self.alice_channel, self.bob_channel)
917 self.check_bals(one_bitcoin_in_msat * 3
918 - self.alice_channel.get_next_fee(LOCAL),
919 one_bitcoin_in_msat * 5)
920 self.bob_channel.settle_htlc(paymentPreimage, bob_idx)
921 self.alice_channel.receive_htlc_settle(paymentPreimage, alice_idx)
922 force_state_transition(self.alice_channel, self.bob_channel)
923 self.check_bals(one_bitcoin_in_msat * 3
924 - self.alice_channel.get_next_fee(LOCAL),
925 one_bitcoin_in_msat * 7)
926 # And now let Bob add an HTLC of 1 BTC. This will take Bob's balance
927 # all the way down to his channel reserve, but since he is not paying
928 # the fee this is okay.
929 htlc = dataclasses.replace(htlc, amount_msat=one_bitcoin_in_msat)
930 self.bob_channel.add_htlc(htlc)
931 self.alice_channel.receive_htlc(htlc)
932 force_state_transition(self.alice_channel, self.bob_channel)
933 self.check_bals(one_bitcoin_in_msat * 3 \
934 - self.alice_channel.get_next_fee(LOCAL),
935 one_bitcoin_in_msat * 6)
936
937 def check_bals(self, amt1, amt2):
938 self.assertEqual(self.alice_channel.available_to_spend(LOCAL), amt1)
939 self.assertEqual(self.bob_channel.available_to_spend(REMOTE), amt1)
940 self.assertEqual(self.alice_channel.available_to_spend(REMOTE), amt2)
941 self.assertEqual(self.bob_channel.available_to_spend(LOCAL), amt2)
942
943
944 class TestChanReserveNoAnchors(TestChanReserve):
945 assert TestChanReserve.TEST_ANCHOR_CHANNELS is True
946 TEST_ANCHOR_CHANNELS = False
947
948
949 class TestDust(ElectrumTestCase):
950 async def asyncSetUp(self):
951 await super().asyncSetUp()
952 self.alice_lnwallet = self.create_mock_lnwallet(name="alice")
953 self.bob_lnwallet = self.create_mock_lnwallet(name="bob")
954
955 async def test_DustLimit(self):
956 """Test that addition of an HTLC below the dust limit changes the balances."""
957 alice_channel, bob_channel = create_test_channels(alice_lnwallet=self.alice_lnwallet, bob_lnwallet=self.bob_lnwallet)
958 dust_limit_alice = alice_channel.config[LOCAL].dust_limit_sat
959 dust_limit_bob = bob_channel.config[LOCAL].dust_limit_sat
960 self.assertLess(dust_limit_alice, dust_limit_bob)
961
962 bob_ctx = bob_channel.get_latest_commitment(LOCAL)
963 bobs_original_outputs = [x.value for x in bob_ctx.outputs()]
964 paymentPreimage = b"\x01" * 32
965 paymentHash = bitcoin.sha256(paymentPreimage)
966 fee_per_kw = alice_channel.get_next_feerate(LOCAL)
967 success_weight = effective_htlc_tx_weight(success=True, has_anchors=self.TEST_ANCHOR_CHANNELS)
968 # we put a single sat less into the htlc than bob can afford
969 # to pay for his htlc success transaction
970 below_dust_for_bob = dust_limit_bob - 1
971 htlc_amt = below_dust_for_bob + success_weight * (fee_per_kw // 1000)
972 htlc = UpdateAddHtlc(
973 payment_hash=paymentHash,
974 amount_msat=1000 * htlc_amt,
975 cltv_abs=5, # consistent with channel policy
976 timestamp=0,
977 )
978
979 # add the htlc
980 alice_htlc_id = alice_channel.add_htlc(htlc).htlc_id
981 bob_htlc_id = bob_channel.receive_htlc(htlc).htlc_id
982 force_state_transition(alice_channel, bob_channel)
983 alice_ctx = alice_channel.get_latest_commitment(LOCAL)
984 bob_ctx = bob_channel.get_latest_commitment(LOCAL)
985 bobs_second_outputs = [x.value for x in bob_ctx.outputs()]
986 self.assertNotEqual(bobs_original_outputs, bobs_second_outputs)
987 # the htlc appears as an output in alice's ctx, as she has a lower
988 # dust limit (also because her timeout tx costs less)
989 self.assertEqual(3, len(alice_ctx.outputs()) - (2 if self.TEST_ANCHOR_CHANNELS else 0))
990 # htlc in bob's case goes to miner fees
991 self.assertEqual(2, len(bob_ctx.outputs()) - (2 if self.TEST_ANCHOR_CHANNELS else 0))
992 self.assertEqual(htlc_amt, sum(bobs_original_outputs) - sum(bobs_second_outputs))
993 empty_ctx_fee = lnutil.calc_fees_for_commitment_tx(
994 num_htlcs=0, feerate=fee_per_kw, is_local_initiator=True,
995 round_to_sat=True, has_anchors=self.TEST_ANCHOR_CHANNELS)[LOCAL] // 1000
996 self.assertEqual(empty_ctx_fee + htlc_amt, bob_channel.get_next_fee(LOCAL))
997
998 bob_channel.settle_htlc(paymentPreimage, bob_htlc_id)
999 alice_channel.receive_htlc_settle(paymentPreimage, alice_htlc_id)
1000 force_state_transition(bob_channel, alice_channel)
1001 bob_ctx = bob_channel.get_latest_commitment(LOCAL)
1002 bobs_third_outputs = [x.value for x in bob_ctx.outputs()]
1003 # htlc is added back into the balance
1004 self.assertEqual(sum(bobs_original_outputs), sum(bobs_third_outputs))
1005 # balance shifts in bob's direction after settlement
1006 self.assertEqual(htlc_amt, bobs_third_outputs[1 + (2 if self.TEST_ANCHOR_CHANNELS else 0)] - bobs_original_outputs[1 + (2 if self.TEST_ANCHOR_CHANNELS else 0)])
1007 self.assertEqual(2, len(alice_channel.get_next_commitment(LOCAL).outputs()) - (2 if self.TEST_ANCHOR_CHANNELS else 0))
1008 self.assertEqual(2, len(bob_channel.get_next_commitment(LOCAL).outputs()) - (2 if self.TEST_ANCHOR_CHANNELS else 0))
1009 self.assertEqual(htlc_amt, alice_channel.total_msat(SENT) // 1000)
1010
1011 async def test_DustLimit_at_trim_threshold(self):
1012 """An HTLC worth *exactly* the trim threshold must NOT be trimmed.
1013
1014 BOLT-3 only trims when "the HTLC amount minus the HTLC-timeout/success fee
1015 would be less than dust_limit_satoshis". For anchor channels that fee is
1016 zero, so the threshold collapses onto the dust limit itself.
1017 """
1018 alice_channel, bob_channel = create_test_channels(
1019 alice_lnwallet=self.alice_lnwallet, bob_lnwallet=self.bob_lnwallet)
1020 dust_limit_bob = bob_channel.config[LOCAL].dust_limit_sat
1021 feerate = bob_channel.get_next_feerate(LOCAL)
1022 threshold_sat = lnutil.received_htlc_trim_threshold_sat(
1023 dust_limit_sat=dust_limit_bob, feerate=feerate,
1024 has_anchors=self.TEST_ANCHOR_CHANNELS)
1025 htlc = UpdateAddHtlc(
1026 payment_hash=bitcoin.sha256(b"\x01" * 32),
1027 amount_msat=1000 * threshold_sat,
1028 cltv_abs=5, # consistent with channel policy
1029 timestamp=0,
1030 )
1031 alice_channel.add_htlc(htlc)
1032 bob_channel.receive_htlc(htlc)
1033
1034 ctn = bob_channel.get_next_ctn(LOCAL)
1035 ctx = bob_channel.get_next_commitment(LOCAL)
1036 _secret, pcp = bob_channel.get_secret_and_point(subject=LOCAL, ctn=ctn)
1037 # the htlc counts as non-dust for fee purposes...
1038 self.assertEqual(1, len(bob_channel.included_htlcs(LOCAL, RECEIVED, ctn=ctn)))
1039 # ...so it must really have an output in the ctx
1040 self.assertEqual(3, len(ctx.outputs()) - (2 if self.TEST_ANCHOR_CHANNELS else 0))
1041 self.assertIn(threshold_sat, [x.value for x in ctx.outputs()])
1042 self.assertEqual(1, len(lnutil.map_htlcs_to_ctx_output_idxs(
1043 chan=bob_channel, ctx=ctx, pcp=pcp, subject=LOCAL, ctn=ctn)))
1044 # ...and the peer must be sent exactly one htlc signature for it
1045 _sig, htlc_sigs = alice_channel.sign_next_commitment()
1046 self.assertEqual(1, len(htlc_sigs))
1047
1048
1049 class TestDustNoAnchors(TestDust):
1050 assert TestDust.TEST_ANCHOR_CHANNELS is True
1051 TEST_ANCHOR_CHANNELS = False
1052
1053
1054 def force_state_transition(chanA: Channel, chanB: Channel) -> None:
1055 chanB.receive_new_commitment(*chanA.sign_next_commitment())
1056 rev = chanB.revoke_current_commitment()
1057 bob_sig, bob_htlc_sigs = chanB.sign_next_commitment()
1058 chanA.receive_revocation(rev)
1059 chanA.receive_new_commitment(bob_sig, bob_htlc_sigs)
1060 chanB.receive_revocation(chanA.revoke_current_commitment())