]> git.bitcoin.ninja Git - ldk-java/blob - ts/test/tests.mts
[TS] Apparently `console.log` doesn't actually throw, it just logs
[ldk-java] / ts / test / tests.mts
1 import * as rawldk from "../bindings.mjs";
2 import * as ldk from "../index.mjs";
3
4 const tests: Array<Function> = [];
5
6 function assert(val: boolean) {
7         if (!val) throw new Error("Assertion failed");
8 }
9 function array_eq(a: Uint8Array, b: Uint8Array): boolean {
10         return a.length == b.length && a.every((v, idx) => v == b[idx]);
11 }
12
13 tests.push(async () => {
14         const result = rawldk.CResult_boolLightningErrorZ_ok(true);
15         assert(rawldk.CResult_boolLightningErrorZ_is_ok(result));
16         assert(rawldk.CResult_boolLightningErrorZ_get_ok(result));
17         rawldk.CResult_boolLightningErrorZ_free(result);
18         const second_res = rawldk.CResult_boolLightningErrorZ_ok(false);
19         assert(rawldk.CResult_boolLightningErrorZ_is_ok(second_res));
20         assert(!rawldk.CResult_boolLightningErrorZ_get_ok(second_res));
21         rawldk.CResult_boolLightningErrorZ_free(second_res);
22
23         return true;
24 });
25
26 tests.push(async () => {
27         const ping = ldk.Ping.constructor_new(10, 2);
28         const new_ping = ldk.Ping.constructor_read(ping.write());
29         if (!(new_ping instanceof ldk.Result_PingDecodeErrorZ_OK)) return false;
30         if (!new_ping.is_ok()) return false;
31         if (new_ping.res.get_byteslen() != 2) return false;
32         if (new_ping.res.get_ponglen() != 10) return false;
33         return true;
34 });
35
36 tests.push(async () => {
37         const outpoint = ldk.OutPoint.constructor_new(new Uint8Array(32), 4);
38         const read_outpoint = ldk.OutPoint.constructor_read(outpoint.write());
39         if (!(read_outpoint instanceof ldk.Result_OutPointDecodeErrorZ_OK)) return false;
40         if (!read_outpoint.res.eq(outpoint)) return false;
41         if (read_outpoint.res.hash() != outpoint.hash()) return false;
42         const chan_id = read_outpoint.res.to_channel_id();
43         if (chan_id.length != 32) return false;
44         if (chan_id[31] != 4) return false;
45         return true;
46 });
47
48 tests.push(async () => {
49         const outpoint = ldk.OutPoint.constructor_new(new Uint8Array(32), 4);
50         const read_outpoint = ldk.OutPoint.constructor_read(outpoint.write());
51         if (!(read_outpoint instanceof ldk.Result_OutPointDecodeErrorZ_OK)) return false;
52         if (!read_outpoint.res.eq(outpoint)) return false;
53         if (read_outpoint.res.hash() != outpoint.hash()) return false;
54         const chan_id = read_outpoint.res.to_channel_id();
55         if (chan_id.length != 32) return false;
56         if (chan_id[31] != 4) return false;
57         return true;
58 });
59
60 var seed_counter = 0;
61 class Node {
62         node_id: Uint8Array;
63         node_secret: Uint8Array;
64         constructor(public chan_man: ldk.ChannelManager, public tx_broadcasted: Promise<Uint8Array>,
65         public logger: ldk.Logger, public keys_interface: ldk.KeysInterface) {
66                 this.node_id = chan_man.get_our_node_id();
67                 this.node_secret = (keys_interface.get_node_secret(ldk.Recipient.LDKRecipient_Node) as ldk.Result_SecretKeyNoneZ_OK).res;
68         }
69 }
70 function get_chanman(): Node {
71         const fee_est = ldk.FeeEstimator.new_impl({
72                 get_est_sat_per_1000_weight(confirmation_target: ldk.ConfirmationTarget): number {
73                         return 253;
74                 }
75         } as ldk.FeeEstimatorInterface);
76         var tx_broadcaster;
77         const tx_broadcasted: Promise<Uint8Array> = new Promise((resolve, reject) => {
78                 tx_broadcaster = ldk.BroadcasterInterface.new_impl({
79                         broadcast_transaction(tx: Uint8Array): void { console.log("Tx Broadcast: " + tx); resolve(tx); }
80                 } as ldk.BroadcasterInterfaceInterface);
81         });
82         const logger = ldk.Logger.new_impl({
83                 log(record: ldk.Record): void {
84                         console.log(record.get_module_path() + ": " + record.get_args());
85                 }
86         } as ldk.LoggerInterface);
87
88         const persister = ldk.Persist.new_impl({
89                 persist_new_channel(channel_id: ldk.OutPoint, data: ldk.ChannelMonitor, update_id: ldk.MonitorUpdateId): ldk.ChannelMonitorUpdateStatus {
90                         return ldk.ChannelMonitorUpdateStatus.LDKChannelMonitorUpdateStatus_Completed;
91                 },
92                 update_persisted_channel(channel_id: ldk.OutPoint, update: ldk.ChannelMonitorUpdate, data: ldk.ChannelMonitor, update_id: ldk.MonitorUpdateId): ldk.ChannelMonitorUpdateStatus {
93                         return ldk.ChannelMonitorUpdateStatus.LDKChannelMonitorUpdateStatus_Completed;
94                 }
95         } as ldk.PersistInterface);
96
97         const chain_monitor = ldk.ChainMonitor.constructor_new(ldk.Option_FilterZ.constructor_none(), tx_broadcaster, logger, fee_est, persister);
98         const chain_watch: ldk.Watch = chain_monitor.as_Watch();
99
100         const seed = new Uint8Array(32);
101         seed.fill(seed_counter);
102         seed_counter++;
103         const keys_manager = ldk.KeysManager.constructor_new(seed, BigInt(42), 42);
104         const keys_interface = keys_manager.as_KeysInterface();
105         const config = ldk.UserConfig.constructor_default();
106         const params = ldk.ChainParameters.constructor_new(ldk.Network.LDKNetwork_Testnet, ldk.BestBlock.constructor_from_genesis(ldk.Network.LDKNetwork_Testnet));
107
108         const chan_man = ldk.ChannelManager.constructor_new(fee_est, chain_watch, tx_broadcaster, logger, keys_interface, config, params);
109         return new Node(chan_man, tx_broadcasted, logger, keys_interface);
110 }
111
112 function exchange_messages(a: ldk.ChannelManager, b: ldk.ChannelManager) {
113         var found_msgs = true;
114         while (found_msgs) {
115                 const as_msgs = a.as_MessageSendEventsProvider().get_and_clear_pending_msg_events();
116                 const bs_msgs = b.as_MessageSendEventsProvider().get_and_clear_pending_msg_events();
117                 found_msgs = as_msgs.length != 0 || bs_msgs.length != 0;
118                 for (var i = 0; i < 2; i++) {
119                         var to: ldk.ChannelManager; var from: ldk.ChannelManager; var msgs: ldk.MessageSendEvent[];
120                         if (i == 0) { from = a; to = b; msgs = as_msgs; } else { from = b; to = a; msgs = bs_msgs; }
121                         for (var j = 0; j < msgs.length; j++) {
122                                 const msg = msgs[j];
123                                 if (msg instanceof ldk.MessageSendEvent_SendOpenChannel) {
124                                         if (!array_eq(msg.node_id, to.get_our_node_id())) return false;
125                                         const features = from.as_ChannelMessageHandler().provided_init_features(to.get_our_node_id());
126                                         to.as_ChannelMessageHandler().handle_open_channel(from.get_our_node_id(), features, msg.msg);
127                                 } else if (msg instanceof ldk.MessageSendEvent_SendAcceptChannel) {
128                                         if (!array_eq(msg.node_id, to.get_our_node_id())) return false;
129                                         const features = from.as_ChannelMessageHandler().provided_init_features(to.get_our_node_id());
130                                         to.as_ChannelMessageHandler().handle_accept_channel(from.get_our_node_id(), features, msg.msg);
131                                 } else if (msg instanceof ldk.MessageSendEvent_SendFundingCreated) {
132                                         if (!array_eq(msg.node_id, to.get_our_node_id())) return false;
133                                         to.as_ChannelMessageHandler().handle_funding_created(from.get_our_node_id(), msg.msg);
134                                 } else if (msg instanceof ldk.MessageSendEvent_SendFundingSigned) {
135                                         if (!array_eq(msg.node_id, to.get_our_node_id())) return false;
136                                         to.as_ChannelMessageHandler().handle_funding_signed(from.get_our_node_id(), msg.msg);
137                                 } else {
138                                         return false;
139                                 }
140                         }
141                 }
142         }
143         return true;
144 }
145
146 function assign_u64(arr: Uint8Array, offset: number, value: bigint) {
147         arr[offset + 0] = Number((value >> BigInt(8 * 0)) & BigInt(0xff));
148         arr[offset + 1] = Number((value >> BigInt(8 * 1)) & BigInt(0xff));
149         arr[offset + 2] = Number((value >> BigInt(8 * 2)) & BigInt(0xff));
150         arr[offset + 3] = Number((value >> BigInt(8 * 3)) & BigInt(0xff));
151         arr[offset + 4] = Number((value >> BigInt(8 * 4)) & BigInt(0xff));
152         arr[offset + 5] = Number((value >> BigInt(8 * 5)) & BigInt(0xff));
153         arr[offset + 6] = Number((value >> BigInt(8 * 6)) & BigInt(0xff));
154         arr[offset + 7] = Number((value >> BigInt(8 * 7)) & BigInt(0xff));
155 }
156
157 function get_event(chan_man: ldk.ChannelManager): ldk.Event {
158         const events: Array<ldk.Event> = [];
159         const event_handler = ldk.EventHandler.new_impl({
160                 handle_event(event: ldk.Event): void {
161                         events.push(event);
162                 }
163         } as ldk.EventHandlerInterface);
164
165         chan_man.as_EventsProvider().process_pending_events(event_handler);
166         assert(events.length == 1);
167         return events[0];
168 }
169
170 tests.push(async () => {
171         const a = get_chanman();
172         const b = get_chanman();
173
174         const features = a.chan_man.as_ChannelMessageHandler().provided_init_features(b.chan_man.get_our_node_id());
175
176         a.chan_man.as_ChannelMessageHandler().peer_connected(b.chan_man.get_our_node_id(), ldk.Init.constructor_new(features, ldk.Option_NetAddressZ.constructor_none()));
177         b.chan_man.as_ChannelMessageHandler().peer_connected(a.chan_man.get_our_node_id(), ldk.Init.constructor_new(features, ldk.Option_NetAddressZ.constructor_none()));
178
179         const chan_create_err = a.chan_man.create_channel(b.chan_man.get_our_node_id(), BigInt(0), BigInt(400), BigInt(0), ldk.UserConfig.constructor_default());
180         if (chan_create_err.is_ok()) return false;
181         if (!(chan_create_err instanceof ldk.Result__u832APIErrorZ_Err)) return false;
182         if (!(chan_create_err.err instanceof ldk.APIError_APIMisuseError)) return false;
183         if (chan_create_err.err.err != "Channel value must be at least 1000 satoshis. It was 0") return false;
184
185         const chan_create_res = a.chan_man.create_channel(b.chan_man.get_our_node_id(), BigInt(1000000), BigInt(400), BigInt(0), ldk.UserConfig.constructor_default());
186         if (!chan_create_res.is_ok()) return false;
187
188         if (!exchange_messages(a.chan_man, b.chan_man)) return false;
189
190         const event = get_event(a.chan_man) as ldk.Event_FundingGenerationReady;
191
192         // (very) manually create a funding transaction
193         const witness_pos = event.output_script.length + 58;
194         const funding_tx = new Uint8Array(witness_pos + 7);
195         funding_tx[0] = 2; // 4-byte tx version 2
196         funding_tx[4] = 0; funding_tx[5] = 1; // segwit magic bytes
197         funding_tx[6] = 1; // 1-byte input count 1
198         // 36 bytes previous outpoint all-0s
199         funding_tx[43] = 0; // 1-byte input script length 0
200         funding_tx[44] = 0xff; funding_tx[45] = 0xff; funding_tx[46] = 0xff; funding_tx[47] = 0xff; // 4-byte nSequence
201         funding_tx[48] = 1; // one output
202         assign_u64(funding_tx, 49, event.channel_value_satoshis);
203         funding_tx[57] = event.output_script.length; // 1-byte output script length
204         funding_tx.set(event.output_script, 58);
205         funding_tx[witness_pos] = 1; funding_tx[witness_pos + 1] = 1; funding_tx[witness_pos + 2] = 0xff; // one witness element of size 1 with contents 0xff
206         funding_tx[witness_pos + 3] = 0; funding_tx[witness_pos + 4] = 0; funding_tx[witness_pos + 5] = 0; funding_tx[witness_pos + 6] = 0; // lock time 0
207
208         const funding_res = a.chan_man.funding_transaction_generated(event.temporary_channel_id, event.counterparty_node_id, funding_tx);
209         if (!(funding_res instanceof ldk.Result_NoneAPIErrorZ_OK)) return false;
210
211         if (!exchange_messages(a.chan_man, b.chan_man)) return false;
212
213         const tx_broadcasted: Uint8Array = (await a.tx_broadcasted);
214         if (!array_eq(tx_broadcasted, funding_tx)) return false;
215
216         return true;
217 });
218
219 tests.push(async () => {
220         const a = get_chanman();
221         const b = get_chanman();
222
223         const ignorer = ldk.IgnoringMessageHandler.constructor_new();
224         const pm_a = ldk.PeerManager.constructor_new(a.chan_man.as_ChannelMessageHandler(), ignorer.as_RoutingMessageHandler(), ignorer.as_OnionMessageHandler(), a.node_secret, 0xdeadbeef, a.node_secret, a.logger, ignorer.as_CustomMessageHandler());
225         const pm_b = ldk.PeerManager.constructor_new(b.chan_man.as_ChannelMessageHandler(), ignorer.as_RoutingMessageHandler(), ignorer.as_OnionMessageHandler(), b.node_secret, 0xdeadbeef, b.node_secret, b.logger, ignorer.as_CustomMessageHandler());
226
227         var sock_b: ldk.SocketDescriptor;
228         const sock_a = ldk.SocketDescriptor.new_impl({
229                 send_data(data: Uint8Array, resume_read: boolean): number {
230                         assert(pm_b.read_event(sock_b, data) instanceof ldk.Result_boolPeerHandleErrorZ_OK);
231                         return data.length;
232                 },
233                 disconnect_socket(): void {
234                         assert(false);
235                 },
236                 eq(other: ldk.SocketDescriptor): boolean {
237                         return other.hash() == this.hash();
238                 },
239                 hash(): bigint {
240                         return BigInt(1);
241                 }
242         } as ldk.SocketDescriptorInterface);
243         sock_b = ldk.SocketDescriptor.new_impl({
244                 send_data(data: Uint8Array, resume_read: boolean): number {
245                         assert(pm_a.read_event(sock_a, data) instanceof ldk.Result_boolPeerHandleErrorZ_OK);
246                         return data.length;
247                 },
248                 disconnect_socket(): void {
249                         assert(false);
250                 },
251                 eq(other: ldk.SocketDescriptor): boolean {
252                         return other.hash() == this.hash();
253                 },
254                 hash(): bigint {
255                         return BigInt(2);
256                 }
257         } as ldk.SocketDescriptorInterface);
258
259         const update_fut = a.chan_man.get_persistable_update_future();
260         var update_done = false;
261         update_fut.register_callback_fn(ldk.FutureCallback.new_impl({
262                 call(): void { update_done = true; }
263         }));
264         if (update_done) return false;
265
266         const v4_netaddr = ldk.NetAddress.constructor_ipv4(Uint8Array.from([42,0,42,1]), 9735);
267         assert(pm_b.new_inbound_connection(sock_b, ldk.Option_NetAddressZ.constructor_some(v4_netaddr)) instanceof ldk.Result_NonePeerHandleErrorZ_OK);
268         const init_bytes = pm_a.new_outbound_connection(b.node_id, sock_a, ldk.Option_NetAddressZ.constructor_none());
269         if (!(init_bytes instanceof ldk.Result_CVec_u8ZPeerHandleErrorZ_OK)) return false;
270         assert(pm_b.read_event(sock_b, init_bytes.res) instanceof ldk.Result_boolPeerHandleErrorZ_OK);
271
272         assert(pm_a.get_peer_node_ids().length == 0);
273         assert(pm_b.get_peer_node_ids().length == 0);
274
275         pm_b.process_events();
276         pm_a.process_events();
277         pm_b.process_events();
278
279         assert(pm_a.get_peer_node_ids().length == 1);
280         assert(pm_b.get_peer_node_ids().length == 1);
281
282         const chan_create_res = a.chan_man.create_channel(b.node_id, BigInt(1000000), BigInt(400), BigInt(0), ldk.UserConfig.constructor_default());
283         if (!chan_create_res.is_ok()) return false;
284         if (!update_done) return false;
285
286         pm_a.process_events();
287         pm_b.process_events();
288
289         const event = get_event(a.chan_man);
290         if (!(event instanceof ldk.Event_FundingGenerationReady)) return false;
291
292         return true;
293 });
294
295 tests.push(async () => {
296         // Test passing onion messages through a custom trait implementation.
297         const a = get_chanman();
298         const b = get_chanman();
299
300         const ignorer = ldk.IgnoringMessageHandler.constructor_new();
301
302         var a_handled_msg = false;
303         const om_handler_a = ldk.CustomOnionMessageHandler.new_impl({
304                 read_custom_message(message_type: bigint, buffer: Uint8Array): ldk.Result_COption_CustomOnionMessageContentsZDecodeErrorZ {
305                         assert(message_type == 4343n);
306                         assert(buffer.length == 44);
307                         for (var i = 0; i < 44; i++) assert(buffer[i] == 67);
308                         return ldk.Result_COption_CustomOnionMessageContentsZDecodeErrorZ.constructor_ok(ldk.Option_CustomOnionMessageContentsZ.constructor_some(ldk.CustomOnionMessageContents.new_impl({
309                                 tlv_type(): bigint { return 9998n; },
310                                 write(): Uint8Array { assert(false); return null; }
311                         } as ldk.CustomOnionMessageContentsInterface)));
312                 },
313                 handle_custom_message(msg: ldk.CustomOnionMessageContents) {
314                         assert(msg.tlv_type() == 9998n);
315                         a_handled_msg = true;
316                 },
317         } as ldk.CustomOnionMessageHandlerInterface);
318
319         const underlying_om_a = ldk.OnionMessenger.constructor_new(a.keys_interface, a.logger, om_handler_a);
320         const om_provider_a = {
321                 next_onion_message_for_peer(peer_node_id: Uint8Array): ldk.OnionMessage {
322                         return underlying_om_a.as_OnionMessageProvider().next_onion_message_for_peer(peer_node_id);
323                 }
324         } as ldk.OnionMessageProviderInterface;
325         const om_a = ldk.OnionMessageHandler.new_impl({
326                 handle_onion_message(peer_node_id: Uint8Array, msg: ldk.OnionMessage) {
327                         underlying_om_a.as_OnionMessageHandler().handle_onion_message(peer_node_id, msg);
328                 },
329                 peer_connected(their_node_id: Uint8Array, init: ldk.Init): ldk.Result_NoneNoneZ {
330                         return underlying_om_a.as_OnionMessageHandler().peer_connected(their_node_id, init)
331                 },
332                 peer_disconnected(their_node_id: Uint8Array, no_connection_possible: boolean) {
333                         underlying_om_a.as_OnionMessageHandler().peer_disconnected(their_node_id, no_connection_possible);
334                 },
335                 provided_node_features(): ldk.NodeFeatures {
336                         return underlying_om_a.as_OnionMessageHandler().provided_node_features();
337                 },
338                 provided_init_features(their_node_id: Uint8Array): ldk.InitFeatures {
339                         return underlying_om_a.as_OnionMessageHandler().provided_init_features(their_node_id);
340                 }
341         } as ldk.OnionMessageHandlerInterface, om_provider_a);
342
343         var b_handled_msg = false;
344         const om_handler_b = ldk.CustomOnionMessageHandler.new_impl({
345                 read_custom_message(message_type: bigint, buffer: Uint8Array): ldk.Result_COption_CustomOnionMessageContentsZDecodeErrorZ {
346                         assert(message_type == 4242n);
347                         assert(buffer.length == 43);
348                         for (var i = 0; i < 43; i++) assert(buffer[i] == 66);
349                         return ldk.Result_COption_CustomOnionMessageContentsZDecodeErrorZ.constructor_ok(ldk.Option_CustomOnionMessageContentsZ.constructor_some(ldk.CustomOnionMessageContents.new_impl({
350                                 tlv_type(): bigint { return 9999n; },
351                                 write(): Uint8Array { assert(false); return null; }
352                         } as ldk.CustomOnionMessageContentsInterface)));
353                 },
354                 handle_custom_message(msg: ldk.CustomOnionMessageContents) {
355                         assert(msg.tlv_type() == 9999n);
356                         b_handled_msg = true;
357                 },
358         } as ldk.CustomOnionMessageHandlerInterface);
359         const om_b = ldk.OnionMessenger.constructor_new(b.keys_interface, b.logger, om_handler_b);
360
361         const pm_a = ldk.PeerManager.constructor_new(a.chan_man.as_ChannelMessageHandler(), ignorer.as_RoutingMessageHandler(), om_a, a.node_secret, 0xdeadbeef, a.node_secret, a.logger, ignorer.as_CustomMessageHandler());
362         const pm_b = ldk.PeerManager.constructor_new(b.chan_man.as_ChannelMessageHandler(), ignorer.as_RoutingMessageHandler(), om_b.as_OnionMessageHandler(), b.node_secret, 0xdeadbeef, b.node_secret, b.logger, ignorer.as_CustomMessageHandler());
363
364         var sock_b: ldk.SocketDescriptor;
365         const sock_a = ldk.SocketDescriptor.new_impl({
366                 send_data(data: Uint8Array, resume_read: boolean): number {
367                         assert(pm_b.read_event(sock_b, data) instanceof ldk.Result_boolPeerHandleErrorZ_OK);
368                         return data.length;
369                 },
370                 disconnect_socket(): void {
371                         assert(false);
372                 },
373                 eq(other: ldk.SocketDescriptor): boolean {
374                         return other.hash() == this.hash();
375                 },
376                 hash(): bigint {
377                         return BigInt(1);
378                 }
379         } as ldk.SocketDescriptorInterface);
380         sock_b = ldk.SocketDescriptor.new_impl({
381                 send_data(data: Uint8Array, resume_read: boolean): number {
382                         assert(pm_a.read_event(sock_a, data) instanceof ldk.Result_boolPeerHandleErrorZ_OK);
383                         return data.length;
384                 },
385                 disconnect_socket(): void {
386                         assert(false);
387                 },
388                 eq(other: ldk.SocketDescriptor): boolean {
389                         return other.hash() == this.hash();
390                 },
391                 hash(): bigint {
392                         return BigInt(2);
393                 }
394         } as ldk.SocketDescriptorInterface);
395
396         const v4_netaddr = ldk.NetAddress.constructor_ipv4(Uint8Array.from([42,0,42,1]), 9735);
397         assert(pm_b.new_inbound_connection(sock_b, ldk.Option_NetAddressZ.constructor_some(v4_netaddr)) instanceof ldk.Result_NonePeerHandleErrorZ_OK);
398         const init_bytes = pm_a.new_outbound_connection(b.node_id, sock_a, ldk.Option_NetAddressZ.constructor_none());
399         if (!(init_bytes instanceof ldk.Result_CVec_u8ZPeerHandleErrorZ_OK)) return false;
400         assert(pm_b.read_event(sock_b, init_bytes.res) instanceof ldk.Result_boolPeerHandleErrorZ_OK);
401
402         assert(pm_a.get_peer_node_ids().length == 0);
403         assert(pm_b.get_peer_node_ids().length == 0);
404
405         pm_b.process_events();
406         pm_a.process_events();
407         pm_b.process_events();
408
409         assert(pm_a.get_peer_node_ids().length == 1);
410         assert(pm_b.get_peer_node_ids().length == 1);
411
412         underlying_om_a.send_custom_onion_message([], ldk.Destination.constructor_node(b.node_id), ldk.CustomOnionMessageContents.new_impl({
413                         tlv_type(): bigint { return 4242n; },
414                         write(): Uint8Array {
415                                 const ret = new Uint8Array(43);
416                                 for (var i = 0; i < 43; i++) ret[i] = 66;
417                                 return ret;
418                         }
419                 } as ldk.CustomOnionMessageContentsInterface), null);
420         pm_a.process_events();
421         assert(b_handled_msg);
422
423         om_b.send_custom_onion_message([], ldk.Destination.constructor_node(a.node_id), ldk.CustomOnionMessageContents.new_impl({
424                         tlv_type(): bigint { return 4343n; },
425                         write(): Uint8Array {
426                                 const ret = new Uint8Array(44);
427                                 for (var i = 0; i < 44; i++) ret[i] = 67;
428                                 return ret;
429                         }
430                 } as ldk.CustomOnionMessageContentsInterface), null);
431         pm_b.process_events();
432         assert(a_handled_msg);
433
434         return true;
435 });
436
437 tests.push(async () => {
438         // Test that we can do basic locking of a NetworkGraph
439         const genesis_hash = new Uint8Array([0x00, 0x00, 0x00, 0x00, 0x00, 0x19, 0xd6, 0x68, 0x9c, 0x08, 0x5a, 0xe1, 0x65, 0x83, 0x1e, 0x93, 0x4f, 0xf7, 0x63, 0xae, 0x46, 0xa2, 0xa6, 0xc1, 0x72, 0xb3, 0xf1, 0xb6, 0x0a, 0x8c, 0xe2, 0x6f]);
440         const logger = ldk.Logger.new_impl({
441                 log(record: ldk.Record): void {
442                         if (record.get_level() != ldk.Level.LDKLevel_Gossip)
443                                 console.log(record.get_module_path() + ": " + record.get_args());
444                 }
445         } as ldk.LoggerInterface);
446         const network_graph = ldk.NetworkGraph.constructor_new(genesis_hash, logger);
447         const graph_lock_1 = network_graph.read_only();
448         graph_lock_1.free();
449         const graph_lock_2 = network_graph.read_only();
450         graph_lock_2.free();
451
452         return true;
453 });
454
455 async function run_tests(check_leaks: boolean) {
456         var test_runs = [];
457         for (const test of tests) {
458                 test_runs.push(test());
459         }
460         const results = await Promise.all(test_runs);
461         console.log("test results: " + results);
462         const result = results.every((v) => { return v === true });
463         console.log("all tests passed: " + result);
464         if (result !== true || !check_leaks) { return result; }
465
466         const allocs_finished = new Promise((resolve, reject) => {
467                 var loop_count = 0;
468                 const interval_id = setInterval(() => {
469                         const alloc_count = rawldk.getRemainingAllocationCount();
470                         if (loop_count % 20 == 0)
471                                 console.log("Remaining LDK allocation count: " + alloc_count);
472
473                         // chromium with --js-flags="--expose-gc" exposes a `window.gc()` which we call if we can
474                         // @ts-ignore window.gc is considered a type error in TS
475                         if (typeof window !== "undefined" && typeof window.gc !== "undefined") window.gc();
476
477                         // Note that there are currently 9 leaks in the above tests. At least some are known - look for XXX in bindings.c
478                         if (alloc_count <= 10) { clearInterval(interval_id); rawldk.debugPrintRemainingAllocs(); resolve(true); }
479                         loop_count += 1;
480                         if (loop_count > 30*2) { clearInterval(interval_id); rawldk.debugPrintRemainingAllocs(); resolve(false); }
481                 }, 500);
482         });
483         return allocs_finished;
484 }
485
486 export async function run_tests_web(wasm_path: string, check_leaks: boolean = true) {
487         await ldk.initializeWasmWebFetch(wasm_path);
488         return await run_tests(check_leaks);
489 }
490
491 export async function run_tests_node(wasm_file: Uint8Array, check_leaks: boolean = true) {
492         await ldk.initializeWasmFromBinary(wasm_file);
493         return await run_tests(check_leaks);
494 }