Debian Codegraph @

tests/test_onion_message.py

raw symbols SCIP
1 import asyncio
2 import io
3 import os
4 import time
5 import dataclasses
6 import logging
7 from functools import partial
8 from unittest.mock import patch
9 from aiorpcx import NetAddress
10
11 import electrum_ecc as ecc
12 from electrum_ecc import ECPrivkey
13
14 from electrum import SimpleConfig
15 from electrum.lnmsg import decode_msg, OnionWireSerializer
16 from electrum.lnonion import (
17 OnionHopsDataSingle, OnionPacket, process_onion_packet, get_bolt04_onion_key, encrypt_onionmsg_data_tlv,
18 get_shared_secrets_along_route, new_onion_packet, ONION_MESSAGE_LARGE_SIZE, HOPS_DATA_SIZE, InvalidPayloadSize,
19 encrypt_hops_recipient_data, blinding_privkey, decrypt_onionmsg_data_tlv)
20 from electrum.crypto import get_ecdh, privkey_to_pubkey
21 from electrum.lntransport import LNPeerAddr
22 from electrum.lnutil import (LnFeatures, Keypair, MIN_FINAL_CLTV_DELTA_ACCEPTED, REMOTE,
23 MIN_FINAL_CLTV_DELTA_BUFFER_INVOICE)
24 from electrum.onion_message import (
25 create_blinded_path, OnionMessageManager, NoRouteFound, Timeout,
26 create_route_to_introduction_point, get_blinded_paths_to_me, NoOnionMessagePeers
27 )
28 from electrum.util import bfh, read_json_file, OldTaskGroup, get_asyncio_loop
29 from electrum.logging import console_stderr_handler
30
31 from . import ElectrumTestCase
32 from .test_lnpeer import TestPeer, inject_chan_into_gossipdb
33
34
35 TIME_STEP = 0.01 # run tests 100 x faster
36 OnionMessageManager.SLEEP_DELAY *= TIME_STEP
37 OnionMessageManager.REQUEST_REPLY_TIMEOUT *= TIME_STEP
38 OnionMessageManager.REQUEST_REPLY_RETRY_DELAY *= TIME_STEP
39 OnionMessageManager.FORWARD_RETRY_TIMEOUT *= TIME_STEP
40 OnionMessageManager.FORWARD_RETRY_DELAY *= TIME_STEP
41
42 # test vectors https://github.com/lightning/bolts/pull/759/files
43 path = os.path.join(os.path.dirname(__file__), 'blinded-onion-message-onion-test.json')
44 test_vectors = read_json_file(path)
45 ONION_MESSAGE_PACKET = bfh(test_vectors['onionmessage']['onion_message_packet'])
46 HOPS = test_vectors['generate']['hops']
47 ALICE_TLVS = HOPS[0]['tlvs']
48 BOB_TLVS = HOPS[1]['tlvs']
49 CAROL_TLVS = HOPS[2]['tlvs']
50 DAVE_TLVS = HOPS[3]['tlvs']
51
52 ALICE_PUBKEY = bfh(test_vectors['route']['first_node_id'])
53 BOB_PUBKEY = bfh(ALICE_TLVS['next_node_id'])
54 CAROL_PUBKEY = bfh(BOB_TLVS['next_node_id'])
55 DAVE_PUBKEY = bfh(CAROL_TLVS['next_node_id'])
56
57 BLINDING_SECRET = bfh(HOPS[0]['path_key_secret'])
58 BLINDING_OVERRIDE_SECRET = bfh(ALICE_TLVS['path_key_override_secret'])
59
60 SESSION_KEY = bfh(test_vectors['generate']['session_key'])
61
62
63 class TestOnionMessage(ElectrumTestCase):
64
65 def test_path_pubkeys_blinded_path_appended(self):
66
67 hop_shared_secrets1, blinded_node_ids1 = get_shared_secrets_along_route([ALICE_PUBKEY], BLINDING_SECRET)
68 hop_shared_secrets2, blinded_node_ids2 = get_shared_secrets_along_route([BOB_PUBKEY, CAROL_PUBKEY, DAVE_PUBKEY], BLINDING_OVERRIDE_SECRET)
69 hop_shared_secrets = hop_shared_secrets1 + hop_shared_secrets2
70 blinded_node_ids = blinded_node_ids1 + blinded_node_ids2
71
72 for i, ss in enumerate(hop_shared_secrets):
73 self.assertEqual(ss, bfh(HOPS[i]['ss']))
74 for i, ss in enumerate(blinded_node_ids):
75 self.assertEqual(ss, bfh(HOPS[i]['blinded_node_id']))
76
77 hops_data = [
78 OnionHopsDataSingle(
79 tlv_stream_name='onionmsg_tlv',
80 blind_fields={
81 'next_node_id': {'node_id': bfh(ALICE_TLVS['next_node_id'])},
82 'next_path_key_override': {'path_key': bfh(ALICE_TLVS['next_path_key_override'])},
83 },
84 ),
85 OnionHopsDataSingle(
86 tlv_stream_name='onionmsg_tlv',
87 blind_fields={
88 'next_node_id': {'node_id': bfh(BOB_TLVS['next_node_id'])},
89 'unknown_tag_561': {'data': bfh(BOB_TLVS['unknown_tag_561'])},
90 },
91 ),
92 OnionHopsDataSingle(
93 tlv_stream_name='onionmsg_tlv',
94 blind_fields={
95 'padding': {'padding': bfh(CAROL_TLVS['padding'])},
96 'next_node_id': {'node_id': bfh(CAROL_TLVS['next_node_id'])},
97 },
98 ),
99 OnionHopsDataSingle(
100 tlv_stream_name='onionmsg_tlv',
101 payload={'message': {'text': bfh(test_vectors['onionmessage']['unknown_tag_1'])}},
102 blind_fields={
103 'padding': {'padding': bfh(DAVE_TLVS['padding'])},
104 'path_id': {'data': bfh(DAVE_TLVS['path_id'])},
105 'unknown_tag_65535': {'data': bfh(DAVE_TLVS['unknown_tag_65535'])},
106 },
107 )
108 ]
109
110 encrypt_hops_recipient_data(hops_data, hop_shared_secrets)
111 packet = new_onion_packet(blinded_node_ids, SESSION_KEY, hops_data, onion_message=True)
112 self.assertEqual(packet.to_bytes(), ONION_MESSAGE_PACKET)
113
114 def test_onion_message_payload_size(self):
115 # Note: payload size is not _strictly_ limited to (1300+66, 32768+66), but Electrum only generates these sizes
116 # However, the spec allows for other payload sizes.
117 # https://github.com/lightning/bolts/blob/master/04-onion-routing.md
118 # "SHOULD set onion_message_packet len to 1366 or 32834."
119 hop_shared_secrets, blinded_node_ids = get_shared_secrets_along_route([DAVE_PUBKEY], SESSION_KEY)
120
121 def hops_data_for_message(message):
122 return [
123 OnionHopsDataSingle(
124 tlv_stream_name='onionmsg_tlv',
125 payload={'message': {'text': message.encode('utf-8')}},
126 blind_fields={
127 'path_id': {'data': bfh('deadbeefbadc0ffeedeadbeefbadc0ffeedeadbeefbadc0ffeedeadbeefbadc0')},
128 },
129 ),
130 ]
131 hops_data = hops_data_for_message('short_message') # fit in HOPS_DATA_SIZE
132 encrypt_hops_recipient_data(hops_data, hop_shared_secrets)
133 packet = new_onion_packet(blinded_node_ids, SESSION_KEY, hops_data, onion_message=True)
134 self.assertEqual(len(packet.to_bytes()), HOPS_DATA_SIZE + 66)
135
136 hops_data = hops_data_for_message('A' * HOPS_DATA_SIZE) # fit in ONION_MESSAGE_LARGE_SIZE
137 encrypt_hops_recipient_data(hops_data, hop_shared_secrets)
138 packet = new_onion_packet(blinded_node_ids, SESSION_KEY, hops_data, onion_message=True)
139
140 self.assertEqual(len(packet.to_bytes()), ONION_MESSAGE_LARGE_SIZE + 66)
141
142 hops_data = hops_data_for_message('A' * ONION_MESSAGE_LARGE_SIZE) # does not fit in ONION_MESSAGE_LARGE_SIZE
143 encrypt_hops_recipient_data(hops_data, hop_shared_secrets)
144
145 with self.assertRaises(InvalidPayloadSize):
146 new_onion_packet(blinded_node_ids, SESSION_KEY, hops_data, onion_message=True)
147
148 def test_decode_onion_message_packet(self):
149 op = OnionPacket.from_bytes(ONION_MESSAGE_PACKET)
150 self.assertEqual(op.hmac, bfh('8e7fc7590ff05a9e991de03f023d0aaf8688ed6170def5091c66576a424ac1cb'))
151 self.assertEqual(op.public_key, bfh('02531fe6068134503d2723133227c867ac8fa6c83c537e9a44c3c5bdbdcb1fe337'))
152 self.assertEqual(op.hops_data, bfh('93b828776d70aabbd8cef1a5b52d5a397ae1a20f20435ff6057cd8be339d5aee226660ef73b64afa45dbf2e6e8e26eb96a259b2db5aeecda1ce2e768bbc35d389d7f320ca3d2bd14e2689bef2f5ac0307eaaabc1924eb972c1563d4646ae131accd39da766257ed35ea36e4222527d1db4fa7b2000aab9eafcceed45e28b5560312d4e2299bd8d1e7fe27d10925966c28d497aec400b4630485e82efbabc00550996bdad5d6a9a8c75952f126d14ad2cff91e16198691a7ef2937de83209285f1fb90944b4e46bca7c856a9ce3da10cdf2a7d00dc2bf4f114bc4d3ed67b91cbde558ce9af86dc81fbdc37f8e301b29e23c1466659c62bdbf8cff5d4c20f0fb0851ec72f5e9385dd40fdd2e3ed67ca4517117825665e50a3e26f73c66998daf18e418e8aef9ce2d20da33c3629db2933640e03e7b44c2edf49e9b482db7b475cfd4c617ae1d46d5c24d697846f9f08561eac2b065f9b382501f6eabf07343ed6c602f61eab99cdb52adf63fd44a8db2d3016387ea708fc1c08591e19b4d9984ebe31edbd684c2ea86526dd8c7732b1d8d9117511dc1b643976d356258fce8313b1cb92682f41ab72dedd766f06de375f9edacbcd0ca8c99b865ea2b7952318ea1fd20775a28028b5cf59dece5de14f615b8df254eee63493a5111ea987224bea006d8f1b60d565eef06ac0da194dba2a6d02e79b2f2f34e9ca6e1984a507319d86e9d4fcaeea41b4b9144e0b1826304d4cc1da61cfc5f8b9850697df8adc5e9d6f3acb3219b02764b4909f2b2b22e799fd66c383414a84a7d791b899d4aa663770009eb122f90282c8cb9cda16aba6897edcf9b32951d0080c0f52be3ca011fbec3fb16423deb47744645c3b05fdbd932edf54ba6efd26e65340a8e9b1d1216582e1b30d64524f8ca2d6c5ba63a38f7120a3ed71bed8960bcac2feee2dd41c90be48e3c11ec518eb3d872779e4765a6cc28c6b0fa71ab57ced73ae963cc630edae4258cba2bf25821a6ae049fec2fca28b5dd1bb004d92924b65701b06dcf37f0ccd147a13a03f9bc0f98b7d78fe9058089756931e2cd0e0ed92ec6759d07b248069526c67e9e6ce095118fd3501ba0f858ef030b76c6f6beb11a09317b5ad25343f4b31aef02bc555951bc7791c2c289ecf94d5544dcd6ad3021ed8e8e3db34b2a73e1eedb57b578b068a5401836d6e382110b73690a94328c404af25e85a8d6b808893d1b71af6a31fadd8a8cc6e31ecc0d9ff7e6b91fd03c274a5c1f1ccd25b61150220a3fddb04c91012f5f7a83a5c90deb2470089d6e38cd5914b9c946eca6e9d31bbf8667d36cf87effc3f3ff283c21dd4137bd569fe7cf758feac94053e4baf7338bb592c8b7c291667fadf4a9bf9a2a154a18f612cbc7f851b3f8f2070e0a9d180622ee4f8e81b0ab250d504cef24116a3ff188cc829fcd8610b56343569e8dc997629410d1967ca9dd1d27eec5e01e4375aad16c46faba268524b154850d0d6fe3a76af2c6aa3e97647c51036049ac565370028d6a439a2672b6face56e1b171496c0722cfa22d9da631be359661617c5d5a2d286c5e19db9452c1e21a0107b6400debda2decb0c838f342dd017cdb2dccdf1fe97e3df3f881856b546997a3fed9e279c720145101567dd56be21688fed66bf9759e432a9aa89cbbd225d13cdea4ca05f7a45cfb6a682a3d5b1e18f7e6cf934fae5098108bae9058d05c3387a01d8d02a656d2bfff67e9f46b2d8a6aac28129e52efddf6e552214c3f8a45bc7a912cca9a7fec1d7d06412c6972cb9e3dc518983f56530b8bffe7f92c4b6eb47d4aef59fb513c4653a42de61bc17ad772'))
153
154 def test_decode_onion_message(self):
155 msg = test_vectors['decrypt']['hops'][0]['onion_message']
156 msgtype, data = decode_msg(bfh(msg))
157 self.assertEqual(msgtype, 'onion_message')
158 self.assertEqual(data, {
159 'path_key': bfh(test_vectors['route']['first_path_key']),
160 'len': 1366,
161 'onion_message_packet': ONION_MESSAGE_PACKET,
162 })
163
164 def test_decrypt_onion_message(self):
165 o = OnionPacket.from_bytes(ONION_MESSAGE_PACKET)
166 our_privkey = bfh(test_vectors['decrypt']['hops'][0]['privkey'])
167 blinding = bfh(test_vectors['route']['first_path_key'])
168
169 shared_secret = get_ecdh(our_privkey, blinding)
170 b_hmac = get_bolt04_onion_key(b'blinded_node_id', shared_secret)
171 b_hmac_int = int.from_bytes(b_hmac, byteorder="big")
172
173 our_privkey_int = int.from_bytes(our_privkey, byteorder="big")
174 our_privkey_int = our_privkey_int * b_hmac_int % ecc.CURVE_ORDER
175 our_privkey = our_privkey_int.to_bytes(32, byteorder="big")
176
177 p = process_onion_packet(o, our_privkey, tlv_stream_name='onionmsg_tlv')
178
179 self.assertEqual(p.hop_data.blind_fields, {})
180 self.assertEqual(p.hop_data.hmac, bfh('a5296325ba478ba1e1a9d1f30a2d5052b2e2889bbd64f72c72bc71d8817288a2'))
181 self.assertEqual(p.hop_data.payload, {'encrypted_recipient_data': {'encrypted_recipient_data': bfh('49531cf38d3280b7f4af6d6461a2b32e3df50acfd35176fc61422a1096eed4dfc3806f29bf74320f712a61c766e7f7caac0c42f86040125fbaeec0c7613202b206dbdd31fda56394367b66a711bfd7d5bedbe20bed1b')}})
182 self.assertEqual(p.hop_data.tlv_stream_name, 'onionmsg_tlv')
183
184 onion_message_bob = test_vectors['decrypt']['hops'][1]['onion_message']
185 msgtype, data = decode_msg(bfh(onion_message_bob))
186 self.assertEqual(msgtype, 'onion_message')
187 self.assertEqual(data, {
188 'path_key': bfh(ALICE_TLVS['next_path_key_override']),
189 'len': 1366,
190 'onion_message_packet': p.next_packet.to_bytes(),
191 })
192
193 def test_blinding_privkey(self):
194 a = blinding_privkey(bfh('4141414141414141414141414141414141414141414141414141414141414141'),
195 bfh('031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f'))
196 self.assertEqual(a, bfh('7e959bf6bdd3a98caf26cbbee7b69678381d5fa2882c6c12eb2042c2367264b0'))
197
198 def test_create_blinded_path(self):
199 pubkey = ALICE_PUBKEY
200 session_key = bfh('3030303030303030303030303030303030303030303030303030303030303030') # typo?
201 final_recipient_data = {'path_id': {'data': bfh('0102')}}
202 rp = create_blinded_path(session_key, [pubkey], final_recipient_data)
203
204 self.assertEqual(pubkey, rp['first_node_id'])
205 self.assertEqual(bfh('022ed557f5ad336b31a49857e4e9664954ac33385aa20a93e2d64bfe7f08f51277'), rp['first_path_key'])
206 self.assertEqual(b"\x01", rp['num_hops'])
207 self.assertEqual([{
208 'blinded_node_id': bfh('031e5d91e6c417f6e8c16d1086db1887edef7be9334f5e744d04edb8da7507481e'),
209 'enclen': 20,
210 'encrypted_recipient_data': bfh('2dbaa54a819775aa0548ab85db68c5099e7b1180')
211 }], rp['path'])
212
213 # TODO: serialization test to test_lnmsg.py
214 with io.BytesIO() as blinded_path_fd:
215 OnionWireSerializer.write_field(
216 fd=blinded_path_fd,
217 field_type='blinded_path',
218 count=1,
219 value=rp)
220 blinded_path = blinded_path_fd.getvalue()
221 self.assertEqual(blinded_path, bfh('02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619022ed557f5ad336b31a49857e4e9664954ac33385aa20a93e2d64bfe7f08f5127701031e5d91e6c417f6e8c16d1086db1887edef7be9334f5e744d04edb8da7507481e00142dbaa54a819775aa0548ab85db68c5099e7b1180'))
222
223 def prepare_blinded_path_bob_to_dave(self):
224 final_recipient_data = {
225 'padding': {'padding': bfh(DAVE_TLVS['padding'])},
226 'path_id': {'data': bfh(DAVE_TLVS['path_id'])},
227 'unknown_tag_65535': {'data': bfh(DAVE_TLVS['unknown_tag_65535'])}
228 }
229 hop_extras = [
230 {'unknown_tag_561': {'data': bfh(BOB_TLVS['unknown_tag_561'])}},
231 {'padding': {'padding': bfh(CAROL_TLVS['padding'])}}
232 ]
233 return create_blinded_path(BLINDING_OVERRIDE_SECRET, [BOB_PUBKEY, CAROL_PUBKEY, DAVE_PUBKEY], final_recipient_data, hop_extras=hop_extras)
234
235 def test_create_onionmessage_to_blinded_path_via_alice(self):
236 blinded_path_to_dave = self.prepare_blinded_path_bob_to_dave()
237 hop_shared_secrets, blinded_node_ids = get_shared_secrets_along_route([ALICE_PUBKEY], BLINDING_SECRET)
238 hops_data = [
239 OnionHopsDataSingle(
240 tlv_stream_name='onionmsg_tlv',
241 blind_fields={
242 'next_node_id': {'node_id': BOB_PUBKEY},
243 'next_path_key_override': {'path_key': bfh(ALICE_TLVS['next_path_key_override'])},
244 },
245 ),
246 ]
247 # encrypt encrypted_data_tlv here
248 encrypt_hops_recipient_data(hops_data, hop_shared_secrets)
249
250 blinded_path_blinded_ids = []
251 for i, x in enumerate(blinded_path_to_dave.get('path')):
252 blinded_path_blinded_ids.append(x.get('blinded_node_id'))
253 payload = {'encrypted_recipient_data': {'encrypted_recipient_data': x.get('encrypted_recipient_data')}}
254 if i == len(blinded_path_to_dave.get('path')) - 1:
255 # add final recipient payload
256 payload['message'] = {'text': bfh(test_vectors['onionmessage']['unknown_tag_1'])}
257 hops_data.append(
258 OnionHopsDataSingle(
259 tlv_stream_name='onionmsg_tlv',
260 payload=payload),
261 )
262 payment_path_pubkeys = blinded_node_ids + blinded_path_blinded_ids
263 packet = new_onion_packet(payment_path_pubkeys, SESSION_KEY, hops_data, onion_message=True)
264 self.assertEqual(packet.to_bytes(), ONION_MESSAGE_PACKET)
265
266
267 class MockNetwork:
268 def __init__(self):
269 self.asyncio_loop = get_asyncio_loop()
270 self.taskgroup = OldTaskGroup()
271 self.config = SimpleConfig()
272 self.config.EXPERIMENTAL_LN_FORWARD_PAYMENTS = True
273
274
275 ONION_MESSAGE_CAPABLE_PEER_FEATURES = LnFeatures(LnFeatures.OPTION_ONION_MESSAGE_OPT)
276
277 class MockPeer:
278 def __init__(self, pubkey, on_send_message=None, their_features=ONION_MESSAGE_CAPABLE_PEER_FEATURES):
279 self.pubkey = pubkey
280 self.on_send_message = on_send_message
281 self.their_features = their_features
282
283 async def wait_one_htlc_switch_iteration(self, *args):
284 pass
285
286 def is_initialized(self):
287 return True
288
289 def send_message(self, *args, **kwargs):
290 if self.on_send_message:
291 self.on_send_message(*args, **kwargs)
292
293
294 class TestOnionMessageManager(ElectrumTestCase):
295
296 @classmethod
297 def setUpClass(cls):
298 super().setUpClass()
299 console_stderr_handler.setLevel(logging.DEBUG)
300
301 def setUp(self):
302 super().setUp()
303
304 def keypair(privkey: ECPrivkey):
305 priv = privkey.get_secret_bytes()
306 return Keypair(pubkey=privkey_to_pubkey(priv), privkey=priv)
307
308 self.alice = keypair(ECPrivkey(privkey_bytes=b'\x41'*32))
309 self.bob = keypair(ECPrivkey(privkey_bytes=b'\x42'*32))
310 self.carol = keypair(ECPrivkey(privkey_bytes=b'\x43'*32))
311 self.dave = keypair(ECPrivkey(privkey_bytes=b'\x44'*32))
312 self.eve = keypair(ECPrivkey(privkey_bytes=b'\x45'*32))
313 self.fred = keypair(ECPrivkey(privkey_bytes=b'\x46'*32))
314
315 async def run_test1(self, t):
316 t1 = t.submit_send(
317 payload={'message': {'text': 'alice_timeout'.encode('utf-8')}},
318 node_id_or_blinded_paths=self.alice.pubkey)
319
320 with self.assertRaises(Timeout):
321 await t1
322
323 async def run_test2(self, t):
324 t2 = t.submit_send(
325 payload={'message': {'text': 'bob_slow_timeout'.encode('utf-8')}},
326 node_id_or_blinded_paths=self.bob.pubkey)
327
328 with self.assertRaises(Timeout):
329 await t2
330
331 async def run_test3(self, t, rkey):
332 t3 = t.submit_send(
333 payload={'message': {'text': 'carol_with_immediate_reply'.encode('utf-8')}},
334 node_id_or_blinded_paths=self.carol.pubkey,
335 key=rkey)
336
337 t3_result = await t3
338 self.assertEqual(t3_result, ({'path_id': {'data': b'electrum' + rkey}}, {}))
339
340 async def run_test4(self, t, rkey):
341 t4 = t.submit_send(
342 payload={'message': {'text': 'dave_with_slow_reply'.encode('utf-8')}},
343 node_id_or_blinded_paths=self.dave.pubkey,
344 key=rkey)
345
346 t4_result = await t4
347 self.assertEqual(t4_result, ({'path_id': {'data': b'electrum' + rkey}}, {}))
348
349 async def run_test5(self, t):
350 t5 = t.submit_send(
351 payload={'message': {'text': 'no_peer'.encode('utf-8')}},
352 node_id_or_blinded_paths=self.eve.pubkey)
353
354 # will not find route to eve, but has eve's address, but we are configured to not direct connect
355 with self.assertRaises(NoRouteFound) as c:
356 await t5
357 self.assertEqual(c.exception.peer_address, LNPeerAddr('localhost', 1234, self.eve.pubkey))
358
359 async def run_test6(self, t, rkey):
360 # bob will not reply, fred will
361 t6 = t.submit_send(
362 payload={'message': {'text': 'send_dest_roundrobin'.encode('utf-8')}},
363 node_id_or_blinded_paths=[self.bob.pubkey, self.fred.pubkey],
364 key=rkey
365 )
366
367 t6_result = await t6
368 self.assertEqual(t6_result, ({'path_id': {'data': b'electrum' + rkey}}, {}))
369
370 async def test_request_and_reply(self):
371 n = MockNetwork()
372 lnw = self.create_mock_lnwallet(name='test_request_and_reply')
373
374 # mock add_peer for direct connection fallback
375 async def mock__add_peer(host, port, node_id):
376 mock_peer = MockPeer(pubkey=node_id)
377 # lnw.lnpeermgr._peers[node_id] = mock_peer
378 return mock_peer
379 lnw.lnpeermgr._add_peer = mock__add_peer
380
381 def slow(*args, **kwargs):
382 time.sleep(2*TIME_STEP)
383
384 def withreply(key, *args, **kwargs):
385 t.on_onion_message_received({'path_id': {'data': b'electrum' + key}}, {})
386
387 def slowwithreply(key, *args, **kwargs):
388 time.sleep(2*TIME_STEP)
389 t.on_onion_message_received({'path_id': {'data': b'electrum' + key}}, {})
390
391 rkey1 = bfh('0102030405060708')
392 rkey2 = bfh('0102030405060709')
393 rkey3 = bfh('010203040506070a')
394
395 lnw.lnpeermgr._peers[self.alice.pubkey] = MockPeer(self.alice.pubkey)
396 lnw.lnpeermgr._peers[self.bob.pubkey] = MockPeer(self.bob.pubkey, on_send_message=slow)
397 lnw.lnpeermgr._peers[self.carol.pubkey] = MockPeer(self.carol.pubkey, on_send_message=partial(withreply, rkey1))
398 lnw.lnpeermgr._peers[self.dave.pubkey] = MockPeer(self.dave.pubkey, on_send_message=partial(slowwithreply, rkey2))
399 lnw.channel_db._addresses[self.eve.pubkey] = {NetAddress('localhost', '1234'): int(time.time())}
400 lnw.lnpeermgr._peers[self.fred.pubkey] = MockPeer(self.fred.pubkey, on_send_message=partial(withreply, rkey3))
401 t = OnionMessageManager(lnw)
402 t.start_network(network=n)
403
404 try:
405 await asyncio.sleep(TIME_STEP)
406 self.logger.debug('tests in sequence')
407 await self.run_test1(t)
408 await self.run_test2(t)
409 await self.run_test3(t, rkey1)
410 await self.run_test4(t, rkey2)
411 await self.run_test5(t)
412 await self.run_test6(t, rkey3)
413 self.logger.debug('tests in parallel')
414 async with OldTaskGroup() as group:
415 await group.spawn(self.run_test1(t))
416 await group.spawn(self.run_test2(t))
417 await group.spawn(self.run_test3(t, rkey1))
418 await group.spawn(self.run_test4(t, rkey2))
419 await group.spawn(self.run_test5(t))
420 await group.spawn(self.run_test6(t, rkey3))
421 finally:
422 await asyncio.sleep(TIME_STEP)
423
424 self.logger.debug('stopping manager')
425 await t.stop()
426 await lnw.stop()
427
428 async def test_forward(self):
429 n = MockNetwork()
430 lnw = self.create_mock_lnwallet(name='alice')
431 lnw.node_keypair = self.alice
432
433 self.was_sent = False
434
435 def on_send(to: str, *args, **kwargs):
436 self.assertEqual(to, 'bob')
437 self.was_sent = True
438 # validate what's sent to bob
439 self.assertEqual(bfh(HOPS[1]['E']), kwargs['blinding'])
440 message_type, payload = decode_msg(bfh(test_vectors['decrypt']['hops'][1]['onion_message']))
441 self.assertEqual(message_type, 'onion_message')
442 self.assertEqual(payload['onion_message_packet'], kwargs['onion_message_packet'])
443
444 lnw.lnpeermgr._peers[self.bob.pubkey] = MockPeer(self.bob.pubkey, on_send_message=partial(on_send, 'bob'))
445 lnw.lnpeermgr._peers[self.carol.pubkey] = MockPeer(self.carol.pubkey, on_send_message=partial(on_send, 'carol'))
446 t = OnionMessageManager(lnw)
447 t.start_network(network=n)
448
449 onionmsg = bfh(test_vectors['onionmessage']['onion_message_packet'])
450 try:
451 t.on_onion_message({
452 'path_key': bfh(test_vectors['route']['first_path_key']),
453 'len': len(onionmsg),
454 'onion_message_packet': onionmsg
455 })
456 finally:
457 await asyncio.sleep(2*TIME_STEP)
458
459 self.logger.debug('stopping manager')
460 await t.stop()
461 await lnw.stop()
462
463 self.assertTrue(self.was_sent)
464
465 async def test_receive_unsolicited(self):
466 n = MockNetwork()
467 lnw = self.create_mock_lnwallet(name='dave')
468 lnw.node_keypair = self.dave
469
470 t = OnionMessageManager(lnw)
471 t.start_network(network=n)
472
473 self.received_unsolicited = False
474
475 def my_on_onion_message_received_unsolicited(*args, **kwargs):
476 self.received_unsolicited = True
477
478 t.on_onion_message_received_unsolicited = my_on_onion_message_received_unsolicited
479 packet = bfh(test_vectors['decrypt']['hops'][3]['onion_message'])
480 message_type, payload = decode_msg(packet)
481 try:
482 t.on_onion_message(payload)
483 self.assertTrue(self.received_unsolicited)
484 finally:
485 await asyncio.sleep(TIME_STEP)
486
487 self.logger.debug('stopping manager')
488 await t.stop()
489 await lnw.stop()
490
491
492 class TestOnionMessageUtils(TestPeer):
493
494 async def test_get_blinded_paths_to_me_payment(self):
495 # A <- B (alice generates blinded path from bob to herself)
496 graph = self.prepare_chans_and_peers_in_graph(self.GRAPH_DEFINITIONS['single_chan'])
497 alice, bob = graph.workers.values()
498
499 # store bobs channel_update in alice
500 alice_chan = graph.channels[('alice', 'bob')][0]
501 bob_chan = graph.channels[('bob', 'alice')][0]
502 bob_update_raw = bob_chan.get_outgoing_gossip_channel_update()
503 bob_update = decode_msg(bob_update_raw)[1]
504 bob_update['raw'] = bob_update_raw
505 alice_chan.set_remote_update(bob_update)
506 alice.lnpeermgr.get_peer_by_pubkey(bob.node_keypair.pubkey).their_features |= LnFeatures.OPTION_ROUTE_BLINDING_OPT
507
508 final_recipient_data = {'path_id': {'data': os.urandom(32)}}
509 paths, payinfos = get_blinded_paths_to_me(alice, final_recipient_data, onion_message=False)
510
511 self.assertEqual(len(paths), 1)
512 self.assertEqual(len(payinfos), 1)
513
514 self.assertEqual(payinfos[0], {
515 'fee_base_msat': bob_chan.forwarding_fee_base_msat,
516 'fee_proportional_millionths': bob_chan.forwarding_fee_proportional_millionths,
517 'cltv_expiry_delta': bob_chan.forwarding_cltv_delta + MIN_FINAL_CLTV_DELTA_ACCEPTED + MIN_FINAL_CLTV_DELTA_BUFFER_INVOICE,
518 'htlc_minimum_msat': bob_chan.config[REMOTE].htlc_minimum_msat,
519 'htlc_maximum_msat': min(bob_chan.config[REMOTE].max_htlc_value_in_flight_msat, 1000 * bob_chan.constraints.capacity),
520 'flen': 0,
521 'features': bytes(0),
522 })
523
524 blinded_path = paths[0]
525 self.assertEqual(len(blinded_path['path']), 2)
526 self.assertEqual(blinded_path['first_node_id'], bob.node_keypair.pubkey)
527 self.assertEqual(len(blinded_path['first_path_key']), 33)
528 self.assertEqual(blinded_path['num_hops'], len(blinded_path['path']).to_bytes(length=1, byteorder='big'))
529 self.assertIn('blinded_node_id', blinded_path['path'][0])
530 self.assertIn('encrypted_recipient_data', blinded_path['path'][0])
531
532 async def test_create_route_to_introduction_point(self):
533 # A -- B -- C -- D -- E
534 # Alice constructs route to Edward as introduction point to some blinded path
535 line_graph = self.GRAPH_DEFINITIONS['line_graph']
536 graph = self.prepare_chans_and_peers_in_graph(line_graph)
537 alice, bob, carol, dave, edward = graph.workers.values()
538
539 session_key = os.urandom(32)
540 introduction_point = edward.node_keypair.pubkey
541 first_path_key = ecc.ECPrivkey.generate_random_key().get_public_key_bytes()
542 blinded_path = {
543 'first_path_key': first_path_key,
544 }
545 with self.assertRaises(NoRouteFound):
546 create_route_to_introduction_point(alice, blinded_path, introduction_point, session_key)
547
548 for name, definition in line_graph.items():
549 for channel_partner in definition.get('channels', {}):
550 inject_chan_into_gossipdb(
551 channel_db=alice.channel_db,
552 chanAB=graph.channels[(name, channel_partner)][0],
553 chanBA=graph.channels[(channel_partner, name)][0],
554 )
555
556 # patch is_onion_message_node so we don't have to inject node announcements
557 with patch('electrum.onion_message.is_onion_message_node', return_value=True):
558 r = create_route_to_introduction_point(alice, blinded_path, introduction_point, session_key)
559 peer, path_key, hops_data, blinded_node_ids = r
560 # alice hands the onion over to bob
561 self.assertEqual(peer.pubkey, bob.lnpeermgr.node_keypair.pubkey)
562
563 self.assertEqual(path_key, ecc.ECPrivkey(session_key).get_public_key_bytes())
564 self.assertEqual(len(hops_data), 3)
565 self.assertEqual(len(hops_data), len(blinded_node_ids))
566
567 # bob unwraps the first layer, sees the next peer, next peer should be carol
568 self.assertEqual(hops_data[0].blind_fields['next_node_id']['node_id'], carol.lnpeermgr.node_keypair.pubkey)
569 self.assertEqual(hops_data[1].blind_fields['next_node_id']['node_id'], dave.lnpeermgr.node_keypair.pubkey)
570 self.assertEqual(hops_data[2].blind_fields['next_node_id']['node_id'], edward.lnpeermgr.node_keypair.pubkey)
571 self.assertEqual(hops_data[2].blind_fields['next_path_key_override']['path_key'], first_path_key)
572
573 # verify that the recipient data is encrypted to the correct node
574 hop_shared_secrets, blinded_node_ids = get_shared_secrets_along_route(
575 (bob.node_keypair.pubkey, carol.node_keypair.pubkey, dave.node_keypair.pubkey),
576 session_key)
577 for hop, ss in zip(hops_data, hop_shared_secrets):
578 encrypted_recipient_data = hop.payload['encrypted_recipient_data']['encrypted_recipient_data']
579 decrypt_onionmsg_data_tlv(
580 shared_secret=ss,
581 encrypted_recipient_data=encrypted_recipient_data,
582 )
583
584 # now Bob is IP, Alice is directly connected to IP
585 introduction_point = bob.node_keypair.pubkey
586 r = create_route_to_introduction_point(alice, blinded_path, introduction_point, session_key)
587 peer, path_key, hops_data, blinded_node_ids = r
588 self.assertEqual(path_key, first_path_key)
589 self.assertEqual(len(hops_data), 0)
590 self.assertEqual(len(blinded_node_ids), 0)
591 alice_bob_peer = alice.lnpeermgr.get_peer_by_pubkey(bob.node_keypair.pubkey)
592 self.assertIsNotNone(alice_bob_peer)
593 self.assertEqual(peer, alice_bob_peer)