Update CI references to 0.0.122
[ldk-java] / python_strings.py
1 from bindingstypes import ConvInfo
2 from enum import Enum
3
4 def first_to_lower(string: str) -> str:
5     first = string[0]
6     return first.lower() + string[1:]
7
8
9 class Target(Enum):
10     PYTHON = 1,
11
12 class Consts:
13     def __init__(self, DEBUG: bool, target: Target, outdir: str, **kwargs):
14         self.outdir = outdir
15         self.struct_file_suffixes = {}
16         self.function_ptr_counter = 0
17         self.function_ptrs = {}
18         self.c_type_map = dict(
19             bool = ['bool', 'bool', 'XXX'],
20             uint8_t = ['int', 'int', 'Uint8Array'],
21             uint16_t = ['int', 'int', 'Uint16Array'],
22             uint32_t = ['int', 'int', 'Uint32Array'],
23             uint64_t = ['int', 'int', 'BigUint64Array'],
24         )
25         self.java_type_map = dict(
26             String = "number"
27         )
28         self.java_hu_type_map = dict(
29             String = "string"
30         )
31
32         self.to_hu_conv_templates = dict(
33             ptr = 'const {var_name}_hu_conv: {human_type} = new {human_type}(null, {var_name});',
34             default = 'const {var_name}_hu_conv: {human_type} = new {human_type}(null, {var_name});',
35         )
36
37         self.bindings_header = """
38 import * as version from './version.mjs';
39 import { UInt5, WitnessVersion } from './structs/CommonBase.mjs';
40
41 const imports: any = {};
42 imports.env = {};
43
44 var js_objs: Array<WeakRef<object>> = [];
45 var js_invoke: Function;
46 var getRandomValues: Function;
47
48 imports.wasi_snapshot_preview1 = {
49         "fd_write": (fd: number, iovec_array_ptr: number, iovec_array_len: number, bytes_written_ptr: number) => {
50                 // This should generally only be used to print panic messages
51                 const ptr_len_view = new Uint32Array(wasm.memory.buffer, iovec_array_ptr, iovec_array_len * 2);
52                 var bytes_written = 0;
53                 for (var i = 0; i < iovec_array_len; i++) {
54                         const bytes_view = new Uint8Array(wasm.memory.buffer, ptr_len_view[i*2], ptr_len_view[i*2+1]);
55                         console.log("[fd " + fd + "]: " + String.fromCharCode(...bytes_view));
56                         bytes_written += ptr_len_view[i*2+1]!;
57                 }
58                 const written_view = new Uint32Array(wasm.memory.buffer, bytes_written_ptr, 1);
59                 written_view[0] = bytes_written;
60                 return 0;
61         },
62         "fd_close": (_fd: number) => {
63                 // This is not generally called, but may be referenced in debug builds
64                 console.log("wasi_snapshot_preview1:fd_close");
65                 return 58; // Not Supported
66         },
67         "fd_seek": (_fd: number, _offset: bigint, _whence: number, _new_offset: number) => {
68                 // This is not generally called, but may be referenced in debug builds
69                 console.log("wasi_snapshot_preview1:fd_seek");
70                 return 58; // Not Supported
71         },
72         "random_get": (buf_ptr: number, buf_len: number) => {
73                 const buf = new Uint8Array(wasm.memory.buffer, buf_ptr, buf_len);
74                 getRandomValues(buf);
75                 return 0;
76         },
77         "environ_sizes_get": (environ_var_count_ptr: number, environ_len_ptr: number) => {
78                 // This is called before fd_write to format + print panic messages
79                 const out_count_view = new Uint32Array(wasm.memory.buffer, environ_var_count_ptr, 1);
80                 out_count_view[0] = 0;
81                 const out_len_view = new Uint32Array(wasm.memory.buffer, environ_len_ptr, 1);
82                 out_len_view[0] = 0;
83                 return 0;
84         },
85         "environ_get": (_environ_ptr: number, _environ_buf_ptr: number) => {
86                 // This is called before fd_write to format + print panic messages,
87                 // but only if we have variables in environ_sizes_get, so shouldn't ever actually happen!
88                 console.log("wasi_snapshot_preview1:environ_get");
89                 return 58; // Note supported - we said there were 0 environment entries!
90         },
91         "proc_exit" : () => {
92                 console.log("wasi_snapshot_preview1:proc_exit");
93         },
94 };
95
96 var wasm: any = null;
97 let isWasmInitialized: boolean = false;
98
99 async function finishInitializeWasm(wasmInstance: WebAssembly.Instance) {
100         if (typeof crypto === "undefined") {
101                 var crypto_import = (await import('crypto')).webcrypto;
102                 getRandomValues = crypto_import.getRandomValues.bind(crypto_import);
103         } else {
104                 getRandomValues = crypto.getRandomValues.bind(crypto);
105         }
106
107         wasm = wasmInstance.exports;
108         if (!wasm.test_bigint_pass_deadbeef0badf00d(BigInt("0xdeadbeef0badf00d"))) {
109                 throw new Error(\"Currently need BigInt-as-u64 support, try ----experimental-wasm-bigint");
110         }
111
112         if (decodeString(wasm.TS_get_lib_version_string()) !== version.get_ldk_java_bindings_version())
113                 throw new Error(\"Compiled LDK library and LDK class files do not match\");
114         // Fetching the LDK versions from C also checks that the header and binaries match
115         const c_bindings_ver: number = wasm.TS_get_ldk_c_bindings_version();
116         const ldk_ver: number = wasm.TS_get_ldk_version();
117         if (c_bindings_ver == 0)
118                 throw new Error(\"LDK version did not match the header we built against\");
119         if (ldk_ver == 0)
120                 throw new Error(\"LDK C bindings version did not match the header we built against\");
121         const c_bindings_version: string = decodeString(c_bindings_ver)
122         const ldk_version: string = decodeString(ldk_ver);
123         console.log(\"Loaded LDK-Java Bindings with LDK \" + ldk_version + \" and LDK-C-Bindings \" + c_bindings_version);
124
125         isWasmInitialized = true;
126 }
127
128 const fn_list = ["uuuuuu", "buuuuu", "bbuuuu", "bbbuuu", "bbbbuu",
129         "bbbbbb", "ubuubu", "ubuuuu", "ubbuuu", "uubuuu", "uububu", "ububuu"];
130
131 /* @internal */
132 export async function initializeWasmFromUint8Array(wasmBinary: Uint8Array) {
133         for (const fn of fn_list) { imports.env["js_invoke_function_" + fn] = js_invoke; }
134         const { instance: wasmInstance } = await WebAssembly.instantiate(wasmBinary, imports);
135         await finishInitializeWasm(wasmInstance);
136 }
137
138 /* @internal */
139 export async function initializeWasmFetch(uri: string) {
140         for (const fn of fn_list) { imports.env["js_invoke_function_" + fn] = js_invoke; }
141         const stream = fetch(uri);
142         const { instance: wasmInstance } = await WebAssembly.instantiateStreaming(stream, imports);
143         await finishInitializeWasm(wasmInstance);
144 }"""
145
146         self.bindings_header += """
147 // WASM CODEC
148
149 /* @internal */
150 export function uint5ArrToBytes(inputArray: Array<UInt5>): Uint8Array {
151         const arr = new Uint8Array(inputArray.length);
152         for (var i = 0; i < inputArray.length; i++) {
153                 arr[i] = inputArray[i]!.getVal();
154         }
155         return arr;
156 }
157
158 /* @internal */
159 export function WitnessVersionArrToBytes(inputArray: Array<WitnessVersion>): Uint8Array {
160         const arr = new Uint8Array(inputArray.length);
161         for (var i = 0; i < inputArray.length; i++) {
162                 arr[i] = inputArray[i]!.getVal();
163         }
164         return arr;
165 }
166
167
168
169 /* @internal */
170 export function encodeUint128 (inputVal: bigint): number {
171         if (inputVal >= 0x10000000000000000000000000000000n) throw "U128s cannot exceed 128 bits";
172         const cArrayPointer = wasm.TS_malloc(16 + 8);
173         const arrayLengthView = new BigUint64Array(wasm.memory.buffer, cArrayPointer, 1);
174         arrayLengthView[0] = BigInt(16);
175         const arrayMemoryView = new Uint8Array(wasm.memory.buffer, cArrayPointer + 8, 16);
176         for (var i = 0; i < 16; i++) arrayMemoryView[i] = Number((inputVal >> BigInt(i)*8n) & 0xffn);
177         return cArrayPointer;
178 }
179 /* @internal */
180 export function encodeUint8Array (inputArray: Uint8Array|null): number {
181         if (inputArray == null) return 0;
182         const cArrayPointer = wasm.TS_malloc(inputArray.length + 8);
183         const arrayLengthView = new BigUint64Array(wasm.memory.buffer, cArrayPointer, 1);
184         arrayLengthView[0] = BigInt(inputArray.length);
185         const arrayMemoryView = new Uint8Array(wasm.memory.buffer, cArrayPointer + 8, inputArray.length);
186         arrayMemoryView.set(inputArray);
187         return cArrayPointer;
188 }
189 /* @internal */
190 export function encodeUint32Array (inputArray: Uint32Array|Array<number>|null): number {
191         if (inputArray == null) return 0;
192         const cArrayPointer = wasm.TS_malloc((inputArray.length + 2) * 4);
193         const arrayLengthView = new BigUint64Array(wasm.memory.buffer, cArrayPointer, 1);
194         arrayLengthView[0] = BigInt(inputArray.length);
195         const arrayMemoryView = new Uint32Array(wasm.memory.buffer, cArrayPointer + 8, inputArray.length);
196         arrayMemoryView.set(inputArray);
197         return cArrayPointer;
198 }
199 /* @internal */
200 export function encodeUint64Array (inputArray: BigUint64Array|Array<bigint>|null): number {
201         if (inputArray == null) return 0;
202         const cArrayPointer = wasm.TS_malloc((inputArray.length + 1) * 8);
203         const arrayMemoryView = new BigUint64Array(wasm.memory.buffer, cArrayPointer, inputArray.length + 1);
204         arrayMemoryView[0] = BigInt(inputArray.length);
205         arrayMemoryView.set(inputArray, 1);
206         return cArrayPointer;
207 }
208
209 /* @internal */
210 export function check_arr_len(arr: Uint8Array|null, len: number): Uint8Array|null {
211         if (arr !== null && arr.length != len) { throw new Error("Expected array of length " + len + " got " + arr.length); }
212         return arr;
213 }
214
215 /* @internal */
216 export function getArrayLength(arrayPointer: number): number {
217         const arraySizeViewer = new BigUint64Array(wasm.memory.buffer, arrayPointer, 1);
218         const len = arraySizeViewer[0]!;
219         if (len >= (2n ** 32n)) throw new Error("Bogus Array Size");
220         return Number(len % (2n ** 32n));
221 }
222 /* @internal */
223 export function decodeUint128 (arrayPointer: number, free = true): bigint {
224         const arraySize = getArrayLength(arrayPointer);
225         if (arraySize != 16) throw "Need 16 bytes for a uint128";
226         const actualArrayViewer = new Uint8Array(wasm.memory.buffer, arrayPointer + 8, arraySize);
227         var val = 0n;
228         for (var i = 0; i < 16; i++) {
229                 val <<= 8n;
230                 val |= BigInt(actualArrayViewer[i]!);
231         }
232         if (free) {
233                 wasm.TS_free(arrayPointer);
234         }
235         return val;
236 }
237 /* @internal */
238 export function decodeUint8Array (arrayPointer: number, free = true): Uint8Array {
239         const arraySize = getArrayLength(arrayPointer);
240         const actualArrayViewer = new Uint8Array(wasm.memory.buffer, arrayPointer + 8, arraySize);
241         // Clone the contents, TODO: In the future we should wrap the Viewer in a class that
242         // will free the underlying memory when it becomes unreachable instead of copying here.
243         // Note that doing so may have edge-case interactions with memory resizing (invalidating the buffer).
244         const actualArray = actualArrayViewer.slice(0, arraySize);
245         if (free) {
246                 wasm.TS_free(arrayPointer);
247         }
248         return actualArray;
249 }
250 const decodeUint32Array = (arrayPointer: number, free = true) => {
251         const arraySize = getArrayLength(arrayPointer);
252         const actualArrayViewer = new Uint32Array(
253                 wasm.memory.buffer, // value
254                 arrayPointer + 8, // offset (ignoring length bytes)
255                 arraySize // uint32 count
256         );
257         // Clone the contents, TODO: In the future we should wrap the Viewer in a class that
258         // will free the underlying memory when it becomes unreachable instead of copying here.
259         const actualArray = actualArrayViewer.slice(0, arraySize);
260         if (free) {
261                 wasm.TS_free(arrayPointer);
262         }
263         return actualArray;
264 }
265 /* @internal */
266 export function decodeUint64Array (arrayPointer: number, free = true): bigint[] {
267         const arraySize = getArrayLength(arrayPointer);
268         const actualArrayViewer = new BigUint64Array(
269                 wasm.memory.buffer, // value
270                 arrayPointer + 8, // offset (ignoring length bytes)
271                 arraySize // uint32 count
272         );
273         // Clone the contents, TODO: In the future we should wrap the Viewer in a class that
274         // will free the underlying memory when it becomes unreachable instead of copying here.
275         const actualArray = new Array(arraySize);
276         for (var i = 0; i < arraySize; i++) actualArray[i] = actualArrayViewer[i];
277         if (free) {
278                 wasm.TS_free(arrayPointer);
279         }
280         return actualArray;
281 }
282
283 export function freeWasmMemory(pointer: number) { wasm.TS_free(pointer); }
284
285 /* @internal */
286 export function getU64ArrayElem(arrayPointer: number, idx: number): bigint {
287         const actualArrayViewer = new BigUint64Array(wasm.memory.buffer, arrayPointer + 8, idx + 1);
288         return actualArrayViewer[idx]!;
289 }
290
291 /* @internal */
292 export function getU32ArrayElem(arrayPointer: number, idx: number): number {
293         const actualArrayViewer = new Uint32Array(wasm.memory.buffer, arrayPointer + 8, idx + 1);
294         return actualArrayViewer[idx]!;
295 }
296
297 /* @internal */
298 export function getU8ArrayElem(arrayPointer: number, idx: number): number {
299         const actualArrayViewer = new Uint8Array(wasm.memory.buffer, arrayPointer + 8, idx + 1);
300         return actualArrayViewer[idx]!;
301 }
302
303
304 /* @internal */
305 export function encodeString(str: string): number {
306         const charArray = new TextEncoder().encode(str);
307         return encodeUint8Array(charArray);
308 }
309
310 /* @internal */
311 export function decodeString(stringPointer: number, free = true): string {
312         const arraySize = getArrayLength(stringPointer);
313         const memoryView = new Uint8Array(wasm.memory.buffer, stringPointer + 8, arraySize);
314         const result = new TextDecoder("utf-8").decode(memoryView);
315
316         if (free) {
317                 wasm.TS_free(stringPointer);
318         }
319
320         return result;
321 }
322 """
323         if DEBUG:
324             self.bindings_header += """
325 /* @internal */
326 export function getRemainingAllocationCount(): number {
327         return wasm.TS_allocs_remaining();
328 }
329 /* @internal */
330 export function debugPrintRemainingAllocs() {
331         wasm.TS_print_leaks();
332 }
333 """
334         else:
335             self.bindings_header += "\n/* @internal */ export function getRemainingAllocationCount(): number { return 0; }\n"
336             self.bindings_header += "/* @internal */ export function debugPrintRemainingAllocs() { }\n"
337
338         with open(outdir + "/index.py", 'a') as index:
339             index.write("""import { initializeWasmFetch, initializeWasmFromUint8Array } from './bindings.mjs';
340 /** Initializes the WASM backend by calling `fetch()` on the given URI - Browser only */
341 export async function initializeWasmWebFetch(uri: string) {
342         await initializeWasmFetch(uri);
343 }
344 /** Initializes the WASM backend given a Uint8Array of the .wasm binary file - Browser or Node.JS */
345 export async function initializeWasmFromBinary(bin: Uint8Array) {
346         await initializeWasmFromUint8Array(bin);
347 }
348
349 """)
350
351         self.bindings_version_file = """export function get_ldk_java_bindings_version(): String {
352         return "<git_version_ldk_garbagecollected>";
353 }"""
354
355         self.common_base = """
356 function freer(f: () => void) { f() }
357 const finalizer = new FinalizationRegistry(freer);
358 function get_freeer(ptr: bigint, free_fn: (ptr: bigint) => void) {
359         return () => {
360                 free_fn(ptr);
361         }
362 }
363
364 export class UInt5 {
365         public constructor(private val: number) {
366                 if (val > 32 || val < 0) throw new Error("UInt5 value is out of range");
367         }
368         public getVal(): number {
369                 return this.val;
370         }
371 }
372
373 export class WitnessVersion {
374         public constructor(private val: number) {
375                 if (val > 16 || val < 0) throw new Error("WitnessVersion value is out of range");
376         }
377         public getVal(): number {
378                 return this.val;
379         }
380 }
381
382 export class UnqualifiedError {
383         public constructor(_val: number) {}
384 }
385 """
386
387         self.txout_defn = """export class TxOut extends CommonBase {
388         /** The script_pubkey in this output */
389         public script_pubkey: Uint8Array;
390         /** The value, in satoshis, of this output */
391         public value: bigint;
392
393         /* @internal */
394         public constructor(_dummy: null, ptr: bigint) {
395                 super(ptr, bindings.TxOut_free);
396                 this.script_pubkey = bindings.decodeUint8Array(bindings.TxOut_get_script_pubkey(ptr));
397                 this.value = bindings.TxOut_get_value(ptr);
398         }
399         public static constructor_new(value: bigint, script_pubkey: Uint8Array): TxOut {
400                 return new TxOut(null, bindings.TxOut_new(bindings.encodeUint8Array(script_pubkey), value));
401         }
402 }"""
403         self.obj_defined(["TxOut"], "structs")
404
405         self.scalar_defn = """export class BigEndianScalar extends CommonBase {
406         /** The bytes of the scalar value, in big endian */
407         public scalar_bytes: Uint8Array;
408
409         /* @internal */
410         public constructor(_dummy: null, ptr: bigint) {
411                 super(ptr, bindings.BigEndianScalar_free);
412                 this.scalar_bytes = bindings.decodeUint8Array(bindings.BigEndianScalar_get_bytes(ptr));
413         }
414         public static constructor_new(scalar_bytes: Uint8Array): BigEndianScalar {
415                 return new BigEndianScalar(null, bindings.BigEndianScalar_new(bindings.encodeUint8Array(scalar_bytes)));
416         }
417 }"""
418         self.obj_defined(["BigEndianScalar"], "structs")
419
420         self.c_file_pfx = """#include "js-wasm.h"
421 #include <stdatomic.h>
422 #include <lightning.h>
423
424 // These should be provided...somehow...
425 void *memset(void *s, int c, size_t n);
426 void *memcpy(void *dest, const void *src, size_t n);
427 int memcmp(const void *s1, const void *s2, size_t n);
428
429 extern void __attribute__((noreturn)) abort(void);
430 static inline void assert(bool expression) {
431         if (!expression) { abort(); }
432 }
433
434 uint32_t __attribute__((export_name("test_bigint_pass_deadbeef0badf00d"))) test_bigint_pass_deadbeef0badf00d(uint64_t val) {
435         return val == 0xdeadbeef0badf00dULL;
436 }
437
438 """
439
440         if not DEBUG:
441             self.c_file_pfx += """
442 void *malloc(size_t size);
443 void free(void *ptr);
444
445 #define MALLOC(a, _) malloc(a)
446 #define do_MALLOC(a, _b, _c) malloc(a)
447 #define FREE(p) if ((unsigned long)(p) > 4096) { free(p); }
448 #define DO_ASSERT(a) (void)(a)
449 #define CHECK(a)
450 #define CHECK_ACCESS(p)
451 #define CHECK_INNER_FIELD_ACCESS_OR_NULL(v)
452 """
453         else:
454             self.c_file_pfx += """
455 extern int snprintf(char *str, size_t size, const char *format, ...);
456 typedef int32_t ssize_t;
457 ssize_t write(int fd, const void *buf, size_t count);
458 #define DEBUG_PRINT(...) do { \\
459         char debug_str[1024]; \\
460         int s_len = snprintf(debug_str, 1023, __VA_ARGS__); \\
461         write(2, debug_str, s_len); \\
462 } while (0);
463
464 // Always run a, then assert it is true:
465 #define DO_ASSERT(a) do { bool _assert_val = (a); assert(_assert_val); } while(0)
466 // Assert a is true or do nothing
467 #define CHECK(a) DO_ASSERT(a)
468
469 // Running a leak check across all the allocations and frees of the JDK is a mess,
470 // so instead we implement our own naive leak checker here, relying on the -wrap
471 // linker option to wrap malloc/calloc/realloc/free, tracking everyhing allocated
472 // and free'd in Rust or C across the generated bindings shared library.
473
474 #define BT_MAX 128
475 typedef struct allocation {
476         struct allocation* next;
477         void* ptr;
478         const char* struct_name;
479         int lineno;
480 } allocation;
481 static allocation* allocation_ll = NULL;
482 static allocation* freed_ll = NULL;
483
484 extern void* __real_malloc(size_t len);
485 extern void* __real_calloc(size_t nmemb, size_t len);
486 extern void* __real_aligned_alloc(size_t alignment, size_t size);
487 static void new_allocation(void* res, const char* struct_name, int lineno) {
488         allocation* new_alloc = __real_malloc(sizeof(allocation));
489         new_alloc->ptr = res;
490         new_alloc->struct_name = struct_name;
491         new_alloc->next = allocation_ll;
492         new_alloc->lineno = lineno;
493         allocation_ll = new_alloc;
494 }
495 static void* do_MALLOC(size_t len, const char* struct_name, int lineno) {
496         void* res = __real_malloc(len);
497         new_allocation(res, struct_name, lineno);
498         return res;
499 }
500 #define MALLOC(len, struct_name) do_MALLOC(len, struct_name, __LINE__)
501
502 void __real_free(void* ptr);
503 static void alloc_freed(void* ptr, int lineno) {
504         allocation* p = NULL;
505         allocation* it = allocation_ll;
506         while (it->ptr != ptr) {
507                 p = it; it = it->next;
508                 if (it == NULL) {
509                         p = NULL;
510                         it = freed_ll;
511                         while (it && it->ptr != ptr) { p = it; it = it->next; }
512                         if (it == NULL) {
513                                 DEBUG_PRINT("Tried to free unknown pointer %p at line %d.\\n", ptr, lineno);
514                         } else {
515                                 DEBUG_PRINT("Tried to free unknown pointer %p at line %d.\\n Possibly double-free from %s, allocated on line %d.", ptr, lineno, it->struct_name, it->lineno);
516                         }
517                         abort();
518                 }
519         }
520         if (p) { p->next = it->next; } else { allocation_ll = it->next; }
521         DO_ASSERT(it->ptr == ptr);
522         it->next = freed_ll;
523         freed_ll = it;
524 }
525 static void do_FREE(void* ptr, int lineno) {
526         if ((unsigned long)ptr <= 4096) return; // Rust loves to create pointers to the NULL page for dummys
527         alloc_freed(ptr, lineno);
528         __real_free(ptr);
529 }
530 #define FREE(ptr) do_FREE(ptr, __LINE__)
531
532 static void CHECK_ACCESS(const void* ptr) {
533         allocation* it = allocation_ll;
534         while (it->ptr != ptr) {
535                 it = it->next;
536                 if (it == NULL) {
537                         return; // addrsan should catch malloc-unknown and print more info than we have
538                 }
539         }
540 }
541 #define CHECK_INNER_FIELD_ACCESS_OR_NULL(v) \\
542         if (v.is_owned && v.inner != NULL) { \\
543                 const void *p = __unmangle_inner_ptr(v.inner); \\
544                 if (p != NULL) { \\
545                         CHECK_ACCESS(p); \\
546                 } \\
547         }
548
549 void* __wrap_malloc(size_t len) {
550         void* res = __real_malloc(len);
551         new_allocation(res, "malloc call", 0);
552         return res;
553 }
554 void* __wrap_calloc(size_t nmemb, size_t len) {
555         void* res = __real_calloc(nmemb, len);
556         new_allocation(res, "calloc call", 0);
557         return res;
558 }
559 void* __wrap_aligned_alloc(size_t alignment, size_t size) {
560         void* res = __real_aligned_alloc(alignment, size);
561         new_allocation(res, "aligned_alloc call", 0);
562         return res;
563 }
564 void __wrap_free(void* ptr) {
565         if (ptr == NULL) return;
566         alloc_freed(ptr, 0);
567         __real_free(ptr);
568 }
569
570 void* __real_realloc(void* ptr, size_t newlen);
571 void* __wrap_realloc(void* ptr, size_t len) {
572         if (ptr != NULL) alloc_freed(ptr, 0);
573         void* res = __real_realloc(ptr, len);
574         new_allocation(res, "realloc call", 0);
575         return res;
576 }
577 void __wrap_reallocarray(void* ptr, size_t new_sz) {
578         // Rust doesn't seem to use reallocarray currently
579         DO_ASSERT(false);
580 }
581
582 uint32_t __attribute__((export_name("TS_allocs_remaining"))) allocs_remaining() {
583         uint32_t count = 0;
584         for (allocation* a = allocation_ll; a != NULL; a = a->next) {
585                 count++;
586         }
587         return count;
588 }
589 void __attribute__((export_name("TS_print_leaks"))) print_leaks() {
590         for (allocation* a = allocation_ll; a != NULL; a = a->next) {
591                 DEBUG_PRINT("%s %p remains. Allocated on line %d\\n", a->struct_name, a->ptr, a->lineno);
592         }
593 }
594 """
595         self.c_file_pfx = self.c_file_pfx + """
596 // We assume that CVec_u8Z and u8slice are the same size and layout (and thus pointers to the two can be mixed)
597 _Static_assert(sizeof(LDKCVec_u8Z) == sizeof(LDKu8slice), "Vec<u8> and [u8] need to have been mapped identically");
598 _Static_assert(offsetof(LDKCVec_u8Z, data) == offsetof(LDKu8slice, data), "Vec<u8> and [u8] need to have been mapped identically");
599 _Static_assert(offsetof(LDKCVec_u8Z, datalen) == offsetof(LDKu8slice, datalen), "Vec<u8> and [u8] need to have been mapped identically");
600
601 _Static_assert(sizeof(void*) == 4, "Pointers mut be 32 bits");
602
603 #define DECL_ARR_TYPE(ty, name) \\
604         struct name##array { \\
605                 uint64_t arr_len; /* uint32_t would suffice but we want to align uint64_ts as well */ \\
606                 ty elems[]; \\
607         }; \\
608         typedef struct name##array * name##Array; \\
609         static inline name##Array init_##name##Array(size_t arr_len, int lineno) { \\
610                 name##Array arr = (name##Array)do_MALLOC(arr_len * sizeof(ty) + sizeof(uint64_t), #name" array init", lineno); \\
611                 arr->arr_len = arr_len; \\
612                 return arr; \\
613         }
614
615 DECL_ARR_TYPE(int64_t, int64_t);
616 DECL_ARR_TYPE(uint64_t, uint64_t);
617 DECL_ARR_TYPE(int8_t, int8_t);
618 DECL_ARR_TYPE(uint32_t, uint32_t);
619 DECL_ARR_TYPE(void*, ptr);
620 DECL_ARR_TYPE(char, char);
621 typedef charArray jstring;
622
623 static inline jstring str_ref_to_ts(const char* chars, size_t len) {
624         charArray arr = init_charArray(len, __LINE__);
625         memcpy(arr->elems, chars, len);
626         return arr;
627 }
628 static inline LDKStr str_ref_to_owned_c(const jstring str) {
629         char* newchars = MALLOC(str->arr_len + 1, "String chars");
630         memcpy(newchars, str->elems, str->arr_len);
631         newchars[str->arr_len] = 0;
632         LDKStr res = {
633                 .chars = newchars,
634                 .len = str->arr_len,
635                 .chars_is_owned = true
636         };
637         return res;
638 }
639
640 typedef bool jboolean;
641
642 uint32_t __attribute__((export_name("TS_malloc"))) TS_malloc(uint32_t size) {
643         return (uint32_t)MALLOC(size, "JS-Called malloc");
644 }
645 void __attribute__((export_name("TS_free"))) TS_free(uint32_t ptr) {
646         FREE((void*)ptr);
647 }
648
649 jstring __attribute__((export_name("TS_get_ldk_c_bindings_version"))) TS_get_ldk_c_bindings_version() {
650         const char *res = check_get_ldk_bindings_version();
651         if (res == NULL) return NULL;
652         return str_ref_to_ts(res, strlen(res));
653 }
654 jstring __attribute__((export_name("TS_get_ldk_version"))) get_ldk_version() {
655         const char *res = check_get_ldk_version();
656         if (res == NULL) return NULL;
657         return str_ref_to_ts(res, strlen(res));
658 }
659 #include "version.c"
660 """
661
662         self.c_version_file = """jstring __attribute__((export_name("TS_get_lib_version_string"))) TS_get_lib_version_string() {
663         return str_ref_to_ts("<git_version_ldk_garbagecollected>", strlen("<git_version_ldk_garbagecollected>"));
664 }"""
665
666         self.hu_struct_file_prefix = """
667 import { CommonBase, UInt5, WitnessVersion, UnqualifiedError } from './CommonBase.mjs';
668 import * as bindings from '../bindings.mjs'
669
670 """
671         self.hu_struct_file_suffix = ""
672         self.util_fn_pfx = self.hu_struct_file_prefix + "\nexport class UtilMethods extends CommonBase {\n"
673         self.util_fn_sfx = "}"
674         self.c_fn_ty_pfx = ""
675         self.file_ext = ".py"
676         self.ptr_c_ty = "uint64_t"
677         self.ptr_native_ty = "bigint"
678         self.u128_native_ty = "bigint"
679         self.usize_c_ty = "uint32_t"
680         self.usize_native_ty = "number"
681         self.native_zero_ptr = "0n"
682         self.unitary_enum_c_ty = "uint32_t"
683         self.ptr_arr = "ptrArray"
684         self.is_arr_some_check = ("", " != 0")
685         self.get_native_arr_len_call = ("", "->arr_len")
686
687     def bindings_footer(self):
688         return ""
689
690     def release_native_arr_ptr_call(self, ty_info, arr_var, arr_ptr_var):
691         return None
692     def create_native_arr_call(self, arr_len, ty_info):
693         if ty_info.c_ty == "ptrArray":
694             assert ty_info.rust_obj == "LDKCVec_U5Z" or (ty_info.subty is not None and ty_info.subty.c_ty.endswith("Array"))
695         return "init_" + ty_info.c_ty + "(" + arr_len + ", __LINE__)"
696     def set_native_arr_contents(self, arr_name, arr_len, ty_info):
697         if ty_info.c_ty == "int8_tArray":
698             return ("memcpy(" + arr_name + "->elems, ", ", " + arr_len + ")")
699         else:
700             assert False
701     def get_native_arr_contents(self, arr_name, dest_name, arr_len, ty_info, copy):
702         if ty_info.c_ty == "int8_tArray":
703             if copy:
704                 return "memcpy(" + dest_name + ", " + arr_name + "->elems, " + arr_len + "); FREE(" + arr_name + ")"
705         assert not copy
706         if ty_info.c_ty == "ptrArray":
707             return "(void*) " + arr_name + "->elems"
708         else:
709             return arr_name + "->elems"
710     def get_native_arr_elem(self, arr_name, idxc, ty_info):
711         assert False # Only called if above is None
712     def get_native_arr_ptr_call(self, ty_info):
713         if ty_info.subty is not None:
714             return "(" + ty_info.subty.c_ty + "*)(((uint8_t*)", ") + 8)"
715         return "(" + ty_info.c_ty + "*)(((uint8_t*)", ") + 8)"
716     def get_native_arr_entry_call(self, ty_info, arr_name, idxc, entry_access):
717         return None
718     def cleanup_native_arr_ref_contents(self, arr_name, dest_name, arr_len, ty_info):
719         if ty_info.c_ty == "int8_tArray":
720             return "FREE(" + arr_name + ");"
721         else:
722             return "FREE(" + arr_name + ")"
723
724     def map_hu_array_elems(self, arr_name, conv_name, arr_ty, elem_ty):
725         if elem_ty.rust_obj == "LDKU5":
726             return arr_name + " != null ? bindings.uint5ArrToBytes(" + arr_name + ") : null"
727         assert elem_ty.c_ty == "uint64_t" or elem_ty.c_ty.endswith("Array")
728         return arr_name + " != null ? " + arr_name + ".map(" + conv_name + " => " + elem_ty.from_hu_conv[0] + ") : null"
729
730     def str_ref_to_native_call(self, var_name, str_len):
731         return "str_ref_to_ts(" + var_name + ", " + str_len + ")"
732     def str_ref_to_c_call(self, var_name):
733         return "str_ref_to_owned_c(" + var_name + ")"
734     def str_to_hu_conv(self, var_name):
735         return "const " + var_name + "_conv: string = bindings.decodeString(" + var_name + ");"
736     def str_from_hu_conv(self, var_name):
737         return ("bindings.encodeString(" + var_name + ")", "")
738
739     def c_fn_name_define_pfx(self, fn_name, have_args):
740         return " __attribute__((export_name(\"TS_" + fn_name + "\"))) TS_" + fn_name + "("
741
742     def init_str(self):
743         return ""
744
745     def get_java_arr_len(self, arr_name):
746         return "bindings.getArrayLength(" + arr_name + ")"
747     def get_java_arr_elem(self, elem_ty, arr_name, idx):
748         if elem_ty.c_ty.endswith("Array") or elem_ty.c_ty == "uintptr_t":
749             return "bindings.getU32ArrayElem(" + arr_name + ", " + idx + ")"
750         elif elem_ty.c_ty == "uint64_t":
751             return "bindings.getU64ArrayElem(" + arr_name + ", " + idx + ")"
752         elif elem_ty.rust_obj == "LDKU5":
753             return "bindings.getU8ArrayElem(" + arr_name + ", " + idx + ")"
754         else:
755             assert False
756     def constr_hu_array(self, ty_info, arr_len):
757         return "new Array(" + arr_len + ").fill(null)"
758     def cleanup_converted_native_array(self, ty_info, arr_name):
759         return "bindings.freeWasmMemory(" + arr_name + ")"
760
761     def primitive_arr_from_hu(self, arr_ty, fixed_len, arr_name):
762         mapped_ty = arr_ty.subty
763         inner = arr_name
764         if arr_ty.rust_obj == "LDKU128":
765             return ("bindings.encodeUint128(" + inner + ")", "")
766         if fixed_len is not None:
767             assert mapped_ty.c_ty == "int8_t"
768             inner = "bindings.check_arr_len(" + arr_name + ", " + fixed_len + ")"
769         if mapped_ty.c_ty.endswith("Array"):
770             return ("bindings.encodeUint32Array(" + inner + ")", "")
771         elif mapped_ty.c_ty == "uint8_t" or mapped_ty.c_ty == "int8_t":
772             return ("bindings.encodeUint8Array(" + inner + ")", "")
773         elif mapped_ty.c_ty == "uint32_t":
774             return ("bindings.encodeUint32Array(" + inner + ")", "")
775         elif mapped_ty.c_ty == "int64_t" or mapped_ty.c_ty == "uint64_t":
776             return ("bindings.encodeUint64Array(" + inner + ")", "")
777         else:
778             print(mapped_ty.c_ty)
779             assert False
780
781     def primitive_arr_to_hu(self, arr_ty, fixed_len, arr_name, conv_name):
782         mapped_ty = arr_ty.subty
783         if arr_ty.rust_obj == "LDKU128":
784             return "const " + conv_name + ": bigint = bindings.decodeUint128(" + arr_name + ");"
785         elif mapped_ty.c_ty == "uint8_t" or mapped_ty.c_ty == "int8_t":
786             return "const " + conv_name + ": Uint8Array = bindings.decodeUint8Array(" + arr_name + ");"
787         elif mapped_ty.c_ty == "uint64_t" or mapped_ty.c_ty == "int64_t":
788             return "const " + conv_name + ": bigint[] = bindings.decodeUint64Array(" + arr_name + ");"
789         else:
790             assert False
791
792     def var_decl_statement(self, ty_string, var_name, statement):
793         return "const " + var_name + ": " + ty_string + " = " + statement
794
795     def java_arr_ty_str(self, elem_ty_str):
796         return "number"
797
798     def for_n_in_range(self, n, minimum, maximum):
799         return "for (var " + n + " = " + minimum + "; " + n + " < " + maximum + "; " + n + "++) {"
800     def for_n_in_arr(self, n, arr_name, arr_elem_ty):
801         return (arr_name + ".forEach((" + n + ": " + arr_elem_ty.java_hu_ty + ") => { ", " })")
802
803     def get_ptr(self, var):
804         return "CommonBase.get_ptr_of(" + var + ")"
805     def set_null_skip_free(self, var):
806         return "CommonBase.set_null_skip_free(" + var + ");"
807
808     def add_ref(self, holder, referent):
809         return "CommonBase.add_ref_from(" + holder + ", " + referent + ")"
810
811     def obj_defined(self, struct_names, folder):
812         with open(self.outdir + "/index.py", 'a') as index:
813             index.write(f"export * from './{folder}/{struct_names[0]}.mjs';\n")
814         with open(self.outdir + "/imports.py.part", 'a') as imports:
815             imports.write(f"import {{ {', '.join(struct_names)} }} from '../{folder}/{struct_names[0]}.mjs';\n")
816
817     def fully_qualified_hu_ty_path(self, ty):
818         return ty.java_hu_ty
819
820     def native_c_unitary_enum_map(self, struct_name, variants, enum_doc_comment):
821         out_c = "static inline LDK" + struct_name + " LDK" + struct_name + "_from_js(int32_t ord) {\n"
822         out_c = out_c + "\tswitch (ord) {\n"
823         ord_v = 0
824
825         out_typescript_enum_fields = ""
826
827         for var, var_docs in variants:
828             out_c = out_c + "\t\tcase %d: return %s;\n" % (ord_v, var)
829             ord_v = ord_v + 1
830             if var_docs is not None:
831                 var_docs_repld = var_docs.replace("\n", "\n\t")
832                 out_typescript_enum_fields += f"/**\n\t * {var_docs_repld}\n\t */\n"
833             out_typescript_enum_fields += f"\t{var},\n\t"
834         out_c = out_c + "\t}\n"
835         out_c = out_c + "\tabort();\n"
836         out_c = out_c + "}\n"
837
838         out_c = out_c + "static inline int32_t LDK" + struct_name + "_to_js(LDK" + struct_name + " val) {\n"
839         out_c = out_c + "\tswitch (val) {\n"
840         ord_v = 0
841         for var, _ in variants:
842             out_c = out_c + "\t\tcase " + var + ": return %d;\n" % ord_v
843             ord_v = ord_v + 1
844         out_c = out_c + "\t\tdefault: abort();\n"
845         out_c = out_c + "\t}\n"
846         out_c = out_c + "}\n"
847
848         # Note that this is *not* marked /* @internal */ as we re-expose it directly in enums/
849         enum_comment_formatted = enum_doc_comment.replace("\n", "\n * ")
850         out_typescript = f"""
851 /**
852  * {enum_comment_formatted}
853  */
854 export enum {struct_name} {{
855         {out_typescript_enum_fields}
856 }}
857 """
858         out_typescript_enum = f"export {{ {struct_name} }} from \"../bindings.mjs\";"
859         self.obj_defined([struct_name], "enums")
860         return (out_c, out_typescript_enum, out_typescript)
861
862     def c_unitary_enum_to_native_call(self, ty_info):
863         return (ty_info.rust_obj + "_to_js(", ")")
864     def native_unitary_enum_to_c_call(self, ty_info):
865         return (ty_info.rust_obj + "_from_js(", ")")
866
867     def native_c_map_trait(self, struct_name, field_var_conversions, flattened_field_var_conversions, field_function_lines, trait_doc_comment):
868         out_typescript_bindings = ""
869         super_instantiator = ""
870         bindings_instantiator = ""
871         pointer_to_adder = ""
872         impl_constructor_arguments = ""
873         for var in flattened_field_var_conversions:
874             if isinstance(var, ConvInfo):
875                 impl_constructor_arguments += f", {var.arg_name}: {var.java_hu_ty}"
876                 super_instantiator += first_to_lower(var.arg_name) + ", "
877                 if var.from_hu_conv is not None:
878                     bindings_instantiator += ", " + var.from_hu_conv[0]
879                     if var.from_hu_conv[1] != "":
880                         pointer_to_adder += "\t\t\t" + var.from_hu_conv[1] + ";\n"
881                 else:
882                     bindings_instantiator += ", " + first_to_lower(var.arg_name)
883             else:
884                 bindings_instantiator += ", " + first_to_lower(var[1]) + ".instance_idx!"
885                 super_instantiator += first_to_lower(var[1]) + "_impl, "
886                 pointer_to_adder += "\t\timpl_holder.held.ptrs_to.push(" + first_to_lower(var[1]) + ");\n"
887                 impl_constructor_arguments += f", {first_to_lower(var[1])}_impl: {var[0].replace('LDK', '')}Interface"
888
889         super_constructor_statements = ""
890         trait_constructor_arguments = ""
891         for var in field_var_conversions:
892             if isinstance(var, ConvInfo):
893                 trait_constructor_arguments += ", " + var.arg_name
894             else:
895                 super_constructor_statements += "\t\tconst " + first_to_lower(var[1]) + " = " + var[1] + ".new_impl(" + super_instantiator + ");\n"
896                 trait_constructor_arguments += ", " + first_to_lower(var[1]) + ".instance_idx!"
897                 for suparg in var[2]:
898                     if isinstance(suparg, ConvInfo):
899                         trait_constructor_arguments += ", " + suparg.arg_name
900                     else:
901                         trait_constructor_arguments += ", " + suparg[1]
902
903         # BUILD INTERFACE METHODS
904         out_java_interface = ""
905         out_interface_implementation_overrides = ""
906         java_methods = []
907         for fn_line in field_function_lines:
908             java_method_descriptor = ""
909             if fn_line.fn_name != "free" and fn_line.fn_name != "cloned":
910                 out_java_interface += "\t/**" + fn_line.docs.replace("\n", "\n\t * ") + "\n\t */\n"
911                 out_java_interface += "\t" + fn_line.fn_name + "("
912                 out_interface_implementation_overrides += f"\t\t\t{fn_line.fn_name} ("
913
914                 for idx, arg_conv_info in enumerate(fn_line.args_ty):
915                     if idx >= 1:
916                         out_java_interface += ", "
917                         out_interface_implementation_overrides += ", "
918                     out_java_interface += f"{arg_conv_info.arg_name}: {arg_conv_info.java_hu_ty}"
919                     out_interface_implementation_overrides += f"{arg_conv_info.arg_name}: {arg_conv_info.java_ty}"
920                     java_method_descriptor += arg_conv_info.java_fn_ty_arg
921                 out_java_interface += f"): {fn_line.ret_ty_info.java_hu_ty};\n"
922                 java_method_descriptor += ")" + fn_line.ret_ty_info.java_fn_ty_arg
923                 java_methods.append((fn_line.fn_name, java_method_descriptor))
924
925                 out_interface_implementation_overrides += f"): {fn_line.ret_ty_info.java_ty} {{\n"
926
927                 for arg_info in fn_line.args_ty:
928                     if arg_info.to_hu_conv is not None:
929                         out_interface_implementation_overrides += "\t\t\t\t" + arg_info.to_hu_conv.replace("\n", "\n\t\t\t\t") + "\n"
930
931                 if fn_line.ret_ty_info.java_ty != "void":
932                     out_interface_implementation_overrides += "\t\t\t\tconst ret: " + fn_line.ret_ty_info.java_hu_ty + " = arg." + fn_line.fn_name + "("
933                 else:
934                     out_interface_implementation_overrides += f"\t\t\t\targ." + fn_line.fn_name + "("
935
936                 for idx, arg_info in enumerate(fn_line.args_ty):
937                     if idx != 0:
938                         out_interface_implementation_overrides += ", "
939                     if arg_info.to_hu_conv_name is not None:
940                         out_interface_implementation_overrides += arg_info.to_hu_conv_name
941                     else:
942                         out_interface_implementation_overrides += arg_info.arg_name
943
944                 out_interface_implementation_overrides += ");\n"
945                 if fn_line.ret_ty_info.java_ty != "void":
946                     if fn_line.ret_ty_info.from_hu_conv is not None:
947                         out_interface_implementation_overrides += "\t\t\t\t" + f"const result: {fn_line.ret_ty_info.java_ty} = " + fn_line.ret_ty_info.from_hu_conv[0].replace("\n", "\n\t\t\t\t") + ";\n"
948                         if fn_line.ret_ty_info.from_hu_conv[1] != "":
949                             out_interface_implementation_overrides += "\t\t\t\t" + fn_line.ret_ty_info.from_hu_conv[1].replace("this", "impl_holder.held").replace("\n", "\n\t\t\t\t") + ";\n"
950                         #if fn_line.ret_ty_info.rust_obj in result_types:
951                         # XXX: We need to handle this in conversion logic so that its cross-language!
952                         # Avoid double-free by breaking the result - we should learn to clone these and then we can be safe instead
953                         #    out_interface_implementation_overrides = out_interface_implementation_overrides + "\t\t\t\tret.ptr = 0;\n"
954                         out_interface_implementation_overrides += "\t\t\t\treturn result;\n"
955                     else:
956                         out_interface_implementation_overrides += "\t\t\t\treturn ret;\n"
957                 out_interface_implementation_overrides += f"\t\t\t}},\n"
958
959         formatted_trait_docs = trait_doc_comment.replace("\n", "\n * ")
960         out_typescript_human = f"""
961 {self.hu_struct_file_prefix}
962
963 /** An implementation of {struct_name.replace("LDK","")} */
964 export interface {struct_name.replace("LDK", "")}Interface {{
965 {out_java_interface}}}
966
967 class {struct_name}Holder {{
968         held: {struct_name.replace("LDK", "")}|null = null;
969 }}
970
971 /**
972  * {formatted_trait_docs}
973  */
974 export class {struct_name.replace("LDK","")} extends CommonBase {{
975         /* @internal */
976         public bindings_instance: bindings.{struct_name}|null;
977
978         /* @internal */
979         public instance_idx?: number;
980
981         /* @internal */
982         constructor(_dummy: null, ptr: bigint) {{
983                 super(ptr, bindings.{struct_name.replace("LDK","")}_free);
984                 this.bindings_instance = null;
985         }}
986
987         /** Creates a new instance of {struct_name.replace("LDK","")} from a given implementation */
988         public static new_impl(arg: {struct_name.replace("LDK", "")}Interface{impl_constructor_arguments}): {struct_name.replace("LDK", "")} {{
989                 const impl_holder: {struct_name}Holder = new {struct_name}Holder();
990                 let structImplementation = {{
991 {out_interface_implementation_overrides}                }} as bindings.{struct_name};
992 {super_constructor_statements}          const ptr_idx: [bigint, number] = bindings.{struct_name}_new(structImplementation{bindings_instantiator});
993
994                 impl_holder.held = new {struct_name.replace("LDK", "")}(null, ptr_idx[0]);
995                 impl_holder.held.instance_idx = ptr_idx[1];
996                 impl_holder.held.bindings_instance = structImplementation;
997 {pointer_to_adder}              return impl_holder.held!;
998         }}
999
1000 """
1001         self.obj_defined([struct_name.replace("LDK", ""), struct_name.replace("LDK", "") + "Interface"], "structs")
1002
1003         out_typescript_bindings += "/* @internal */\nexport interface " + struct_name + " {\n"
1004         java_meths = []
1005         for fn_line in field_function_lines:
1006             if fn_line.fn_name != "free" and fn_line.fn_name != "cloned":
1007                 out_typescript_bindings += f"\t{fn_line.fn_name} ("
1008
1009                 for idx, arg_conv_info in enumerate(fn_line.args_ty):
1010                     if idx >= 1:
1011                         out_typescript_bindings = out_typescript_bindings + ", "
1012                     out_typescript_bindings += f"{arg_conv_info.arg_name}: {arg_conv_info.java_ty}"
1013
1014                 out_typescript_bindings += f"): {fn_line.ret_ty_info.java_ty};\n"
1015
1016         out_typescript_bindings += "}\n\n"
1017
1018         c_call_extra_args = ""
1019         out_typescript_bindings += f"/* @internal */\nexport function {struct_name}_new(impl: {struct_name}"
1020         for var in flattened_field_var_conversions:
1021             if isinstance(var, ConvInfo):
1022                 out_typescript_bindings += f", {var.arg_name}: {var.java_ty}"
1023                 c_call_extra_args += f", {var.arg_name}"
1024             else:
1025                 out_typescript_bindings += f", {var[1]}: number"
1026                 c_call_extra_args += f", {var[1]}"
1027
1028
1029         out_typescript_bindings += f"""): [bigint, number] {{
1030         if(!isWasmInitialized) {{
1031                 throw new Error("initializeWasm() must be awaited first!");
1032         }}
1033         var new_obj_idx = js_objs.length;
1034         for (var i = 0; i < js_objs.length; i++) {{
1035                 if (js_objs[i] == null || js_objs[i] == undefined) {{ new_obj_idx = i; break; }}
1036         }}
1037         js_objs[i] = new WeakRef(impl);
1038         return [wasm.TS_{struct_name}_new(i{c_call_extra_args}), i];
1039 }}
1040 """
1041
1042         # Now that we've written out our java code (and created java_meths), generate C
1043         out_c = "typedef struct " + struct_name + "_JCalls {\n"
1044         out_c += "\tatomic_size_t refcnt;\n"
1045         out_c += "\tuint32_t instance_ptr;\n"
1046         for var in flattened_field_var_conversions:
1047             if isinstance(var, ConvInfo):
1048                 # We're a regular ol' field
1049                 pass
1050             else:
1051                 # We're a supertrait
1052                 out_c = out_c + "\t" + var[0] + "_JCalls* " + var[1] + ";\n"
1053         out_c = out_c + "} " + struct_name + "_JCalls;\n"
1054
1055         for fn_line in field_function_lines:
1056             if fn_line.fn_name == "free":
1057                 out_c = out_c + "static void " + struct_name + "_JCalls_free(void* this_arg) {\n"
1058                 out_c = out_c + "\t" + struct_name + "_JCalls *j_calls = (" + struct_name + "_JCalls*) this_arg;\n"
1059                 out_c = out_c + "\tif (atomic_fetch_sub_explicit(&j_calls->refcnt, 1, memory_order_acquire) == 1) {\n"
1060                 out_c = out_c + "\t\tFREE(j_calls);\n"
1061                 out_c = out_c + "\t}\n}\n"
1062
1063         for idx, fn_line in enumerate(field_function_lines):
1064             if fn_line.fn_name != "free" and fn_line.fn_name != "cloned":
1065                 assert fn_line.ret_ty_info.ty_info.get_full_rust_ty()[1] == ""
1066                 out_c = out_c + fn_line.ret_ty_info.ty_info.get_full_rust_ty()[0] + " " + fn_line.fn_name + "_" + struct_name + "_jcall("
1067                 if fn_line.self_is_const:
1068                     out_c = out_c + "const void* this_arg"
1069                 else:
1070                     out_c = out_c + "void* this_arg"
1071
1072                 for idx, arg in enumerate(fn_line.args_ty):
1073                     out_c = out_c + ", " + arg.ty_info.get_full_rust_ty()[0] + " " + arg.arg_name + arg.ty_info.get_full_rust_ty()[1]
1074
1075                 out_c = out_c + ") {\n"
1076                 out_c = out_c + "\t" + struct_name + "_JCalls *j_calls = (" + struct_name + "_JCalls*) this_arg;\n"
1077
1078                 for arg_info in fn_line.args_ty:
1079                     if arg_info.ret_conv is not None:
1080                         out_c = out_c + "\t" + arg_info.ret_conv[0].replace('\n', '\n\t')
1081                         out_c = out_c + arg_info.arg_name
1082                         out_c = out_c + arg_info.ret_conv[1].replace('\n', '\n\t') + "\n"
1083
1084                 fn_suffix = ""
1085                 assert len(fn_line.args_ty) < 7
1086                 for arg_info in fn_line.args_ty:
1087                     if arg_info.c_ty == "uint64_t" or arg_info.c_ty == "int64_t":
1088                         fn_suffix += "b"
1089                     else:
1090                         fn_suffix += "u"
1091                 for i in range(0, 6 - len(fn_line.args_ty)):
1092                     fn_suffix += "u"
1093                 if fn_line.ret_ty_info.c_ty.endswith("Array"):
1094                     out_c += "\t" + fn_line.ret_ty_info.c_ty + " ret = (" + fn_line.ret_ty_info.c_ty + ")"
1095                     out_c += "js_invoke_function_" + fn_suffix + "(j_calls->instance_ptr, " + str(self.function_ptr_counter)
1096                 elif fn_line.ret_ty_info.java_ty == "void":
1097                     out_c = out_c + "\tjs_invoke_function_" + fn_suffix + "(j_calls->instance_ptr, " + str(self.function_ptr_counter)
1098                 elif fn_line.ret_ty_info.java_hu_ty == "string":
1099                     out_c += "\tjstring ret = (jstring)js_invoke_function_" + fn_suffix + "(j_calls->instance_ptr, " + str(self.function_ptr_counter)
1100                 elif fn_line.ret_ty_info.arg_conv is None:
1101                     out_c += "\treturn js_invoke_function_" + fn_suffix + "(j_calls->instance_ptr, " + str(self.function_ptr_counter)
1102                 else:
1103                     out_c += "\tuint64_t ret = js_invoke_function_" + fn_suffix + "(j_calls->instance_ptr, " + str(self.function_ptr_counter)
1104
1105                 self.function_ptrs[self.function_ptr_counter] = (struct_name, fn_line.fn_name)
1106                 self.function_ptr_counter += 1
1107
1108                 for idx, arg_info in enumerate(fn_line.args_ty):
1109                     if arg_info.ret_conv is not None:
1110                         if arg_info.c_ty.endswith("Array"):
1111                             out_c += ", (uint32_t)" + arg_info.ret_conv_name
1112                         else:
1113                             out_c += ", " + arg_info.ret_conv_name
1114                     else:
1115                         assert False # TODO: Would we need some conversion here?
1116                         out_c += ", (uint32_t)" + arg_info.arg_name
1117                 for i in range(0, 6 - len(fn_line.args_ty)):
1118                     out_c += ", 0"
1119                 out_c = out_c + ");\n"
1120                 if fn_line.ret_ty_info.arg_conv is not None:
1121                     out_c = out_c + "\t" + fn_line.ret_ty_info.arg_conv.replace("\n", "\n\t") + "\n\treturn " + fn_line.ret_ty_info.arg_conv_name + ";\n"
1122
1123                 out_c = out_c + "}\n"
1124
1125         # Write out a clone function whether we need one or not, as we use them in moving to rust
1126         out_c = out_c + "static void " + struct_name + "_JCalls_cloned(" + struct_name + "* new_obj) {\n"
1127         out_c = out_c + "\t" + struct_name + "_JCalls *j_calls = (" + struct_name + "_JCalls*) new_obj->this_arg;\n"
1128         out_c = out_c + "\tatomic_fetch_add_explicit(&j_calls->refcnt, 1, memory_order_release);\n"
1129         for var in field_var_conversions:
1130             if not isinstance(var, ConvInfo):
1131                 out_c = out_c + "\tatomic_fetch_add_explicit(&j_calls->" + var[1] + "->refcnt, 1, memory_order_release);\n"
1132         out_c = out_c + "}\n"
1133
1134         out_c = out_c + "static inline " + struct_name + " " + struct_name + "_init (JSValue o"
1135         for var in flattened_field_var_conversions:
1136             if isinstance(var, ConvInfo):
1137                 out_c = out_c + ", " + var.c_ty + " " + var.arg_name
1138             else:
1139                 out_c = out_c + ", JSValue " + var[1]
1140         out_c = out_c + ") {\n"
1141
1142         out_c = out_c + "\t" + struct_name + "_JCalls *calls = MALLOC(sizeof(" + struct_name + "_JCalls), \"" + struct_name + "_JCalls\");\n"
1143         out_c = out_c + "\tatomic_init(&calls->refcnt, 1);\n"
1144         out_c = out_c + "\tcalls->instance_ptr = o;\n"
1145
1146         for (fn_name, java_meth_descr) in java_meths:
1147             if fn_name != "free" and fn_name != "cloned":
1148                 out_c = out_c + "\tcalls->" + fn_name + "_meth = (*env)->GetMethodID(env, c, \"" + fn_name + "\", \"" + java_meth_descr + "\");\n"
1149                 out_c = out_c + "\tCHECK(calls->" + fn_name + "_meth != NULL);\n"
1150
1151         for var in flattened_field_var_conversions:
1152             if isinstance(var, ConvInfo) and var.arg_conv is not None:
1153                 out_c = out_c + "\n\t" + var.arg_conv.replace("\n", "\n\t") +"\n"
1154         out_c = out_c + "\n\t" + struct_name + " ret = {\n"
1155         out_c = out_c + "\t\t.this_arg = (void*) calls,\n"
1156         for fn_line in field_function_lines:
1157             if fn_line.fn_name != "free" and fn_line.fn_name != "cloned":
1158                 out_c = out_c + "\t\t." + fn_line.fn_name + " = " + fn_line.fn_name + "_" + struct_name + "_jcall,\n"
1159             elif fn_line.fn_name == "free":
1160                 out_c = out_c + "\t\t.free = " + struct_name + "_JCalls_free,\n"
1161             else:
1162                 out_c = out_c + "\t\t.cloned = " + struct_name + "_JCalls_cloned,\n"
1163         for var in field_var_conversions:
1164             if isinstance(var, ConvInfo):
1165                 if var.arg_conv_name is not None:
1166                     out_c = out_c + "\t\t." + var.arg_name + " = " + var.arg_conv_name + ",\n"
1167                     out_c = out_c + "\t\t.set_" + var.arg_name + " = NULL,\n"
1168                 else:
1169                     out_c = out_c + "\t\t." + var.var_name + " = " + var.var_name + ",\n"
1170                     out_c = out_c + "\t\t.set_" + var.var_name + " = NULL,\n"
1171             else:
1172                 out_c += "\t\t." + var[1] + " = " + var[0] + "_init(" + var[1]
1173                 for suparg in var[2]:
1174                     if isinstance(suparg, ConvInfo):
1175                         out_c += ", " + suparg.arg_name
1176                     else:
1177                         out_c += ", " + suparg[1]
1178                 out_c += "),\n"
1179         out_c = out_c + "\t};\n"
1180         for var in flattened_field_var_conversions:
1181             if not isinstance(var, ConvInfo):
1182                 out_c = out_c + "\tcalls->" + var[1] + " = ret." + var[1] + ".this_arg;\n"
1183         out_c = out_c + "\treturn ret;\n"
1184         out_c = out_c + "}\n"
1185
1186         out_c = out_c + self.c_fn_ty_pfx + "uint64_t " + self.c_fn_name_define_pfx(struct_name + "_new", True) + "JSValue o"
1187         for var in flattened_field_var_conversions:
1188             if isinstance(var, ConvInfo):
1189                 out_c = out_c + ", " + var.c_ty + " " + var.arg_name
1190             else:
1191                 out_c = out_c + ", JSValue " + var[1]
1192         out_c = out_c + ") {\n"
1193         out_c = out_c + "\t" + struct_name + " *res_ptr = MALLOC(sizeof(" + struct_name + "), \"" + struct_name + "\");\n"
1194         out_c = out_c + "\t*res_ptr = " + struct_name + "_init(o"
1195         for var in flattened_field_var_conversions:
1196             if isinstance(var, ConvInfo):
1197                 out_c = out_c + ", " + var.arg_name
1198             else:
1199                 out_c = out_c + ", " + var[1]
1200         out_c = out_c + ");\n"
1201         out_c = out_c + "\treturn tag_ptr(res_ptr, true);\n"
1202         out_c = out_c + "}\n"
1203
1204         return (out_typescript_bindings, out_typescript_human, out_c)
1205
1206     def trait_struct_inc_refcnt(self, ty_info):
1207         base_conv = "\nif (" + ty_info.var_name + "_conv.free == " + ty_info.rust_obj + "_JCalls_free) {\n"
1208         base_conv = base_conv + "\t// If this_arg is a JCalls struct, then we need to increment the refcnt in it.\n"
1209         base_conv = base_conv + "\t" + ty_info.rust_obj + "_JCalls_cloned(&" + ty_info.var_name + "_conv);\n}"
1210         return base_conv
1211
1212     def map_complex_enum(self, struct_name, variant_list, camel_to_snake, enum_doc_comment):
1213         bindings_type = struct_name.replace("LDK", "")
1214         java_hu_type = struct_name.replace("LDK", "").replace("COption", "Option")
1215
1216         out_java_enum = ""
1217         out_java = ""
1218         out_c = ""
1219
1220         out_java_enum += (self.hu_struct_file_prefix)
1221
1222         java_hu_class = "/**\n * " + enum_doc_comment.replace("\n", "\n * ") + "\n */\n"
1223         java_hu_class += "export class " + java_hu_type + " extends CommonBase {\n"
1224         java_hu_class += "\tprotected constructor(_dummy: null, ptr: bigint) { super(ptr, bindings." + bindings_type + "_free); }\n"
1225         java_hu_class += "\t/* @internal */\n"
1226         java_hu_class += f"\tpublic static constr_from_ptr(ptr: bigint): {java_hu_type} {{\n"
1227         java_hu_class += f"\t\tconst raw_ty: number = bindings." + struct_name + "_ty_from_ptr(ptr);\n"
1228         out_c += self.c_fn_ty_pfx + "uint32_t" + self.c_fn_name_define_pfx(struct_name + "_ty_from_ptr", True) + self.ptr_c_ty + " ptr) {\n"
1229         out_c += "\t" + struct_name + " *obj = (" + struct_name + "*)untag_ptr(ptr);\n"
1230         out_c += "\tswitch(obj->tag) {\n"
1231         java_hu_class += "\t\tswitch (raw_ty) {\n"
1232         java_hu_subclasses = ""
1233
1234         out_java += "/* @internal */\nexport class " + struct_name + " {\n"
1235         out_java += "\tprotected constructor() {}\n"
1236         var_idx = 0
1237         for var in variant_list:
1238             java_hu_subclasses += "/** A " + java_hu_type + " of type " + var.var_name + " */\n"
1239             java_hu_subclasses += "export class " + java_hu_type + "_" + var.var_name + " extends " + java_hu_type + " {\n"
1240             java_hu_class += f"\t\t\tcase {var_idx}: "
1241             java_hu_class += "return new " + java_hu_type + "_" + var.var_name + "(ptr);\n"
1242             out_c += f"\t\tcase {struct_name}_{var.var_name}: return {var_idx};\n"
1243             hu_conv_body = ""
1244             for idx, (field_ty, field_docs) in enumerate(var.fields):
1245                 if field_docs is not None:
1246                     java_hu_subclasses += "\t/**\n\t * " + field_docs.replace("\n", "\n\t * ") + "\n\t */\n"
1247                 java_hu_subclasses += "\tpublic " + field_ty.arg_name + f": {field_ty.java_hu_ty};\n"
1248                 if field_ty.to_hu_conv is not None:
1249                     hu_conv_body += f"\t\tconst {field_ty.arg_name}: {field_ty.java_ty} = bindings.{struct_name}_{var.var_name}_get_{field_ty.arg_name}(ptr);\n"
1250                     hu_conv_body += f"\t\t" + field_ty.to_hu_conv.replace("\n", "\n\t\t\t") + "\n"
1251                     hu_conv_body += f"\t\tthis." + field_ty.arg_name + " = " + field_ty.to_hu_conv_name + ";\n"
1252                 else:
1253                     hu_conv_body += f"\t\tthis.{field_ty.arg_name} = bindings.{struct_name}_{var.var_name}_get_{field_ty.arg_name}(ptr);\n"
1254             java_hu_subclasses += "\t/* @internal */\n"
1255             java_hu_subclasses += "\tpublic constructor(ptr: bigint) {\n\t\tsuper(null, ptr);\n"
1256             java_hu_subclasses = java_hu_subclasses + hu_conv_body
1257             java_hu_subclasses = java_hu_subclasses + "\t}\n}\n"
1258             var_idx += 1
1259         out_java += "}\n"
1260         java_hu_class += "\t\t\tdefault:\n\t\t\t\tthrow new Error('oops, this should be unreachable'); // Unreachable without extending the (internal) bindings interface\n\t\t}\n\t}\n\n"
1261         out_java += self.fn_call_body(struct_name + "_ty_from_ptr", "uint32_t", "number", "ptr: bigint", "ptr")
1262         out_c += ("\t\tdefault: abort();\n")
1263         out_c += ("\t}\n}\n")
1264
1265         for var in variant_list:
1266             for idx, (field_map, _) in enumerate(var.fields):
1267                 fn_name = f"{struct_name}_{var.var_name}_get_{field_map.arg_name}"
1268                 out_c += self.c_fn_ty_pfx + field_map.c_ty + self.c_fn_name_define_pfx(fn_name, True) + self.ptr_c_ty + " ptr) {\n"
1269                 out_c += "\t" + struct_name + " *obj = (" + struct_name + "*)untag_ptr(ptr);\n"
1270                 out_c += f"\tassert(obj->tag == {struct_name}_{var.var_name});\n"
1271                 if field_map.ret_conv is not None:
1272                     out_c += ("\t\t\t" + field_map.ret_conv[0].replace("\n", "\n\t\t\t"))
1273                     if var.tuple_variant:
1274                         out_c += "obj->" + camel_to_snake(var.var_name)
1275                     else:
1276                         out_c += "obj->" + camel_to_snake(var.var_name) + "." + field_map.arg_name
1277                     out_c += (field_map.ret_conv[1].replace("\n", "\n\t\t\t") + "\n")
1278                     out_c += "\treturn " + field_map.ret_conv_name + ";\n"
1279                 else:
1280                     if var.tuple_variant:
1281                         out_c += "\treturn " + "obj->" + camel_to_snake(var.var_name) + ";\n"
1282                     else:
1283                         out_c += "\treturn " + "obj->" + camel_to_snake(var.var_name) + "." + field_map.arg_name + ";\n"
1284                 out_c += "}\n"
1285                 out_java += self.fn_call_body(fn_name, field_map.c_ty, field_map.java_ty, "ptr: bigint", "ptr")
1286         out_java_enum += java_hu_class
1287         self.struct_file_suffixes[java_hu_type] = java_hu_subclasses
1288         self.obj_defined([java_hu_type], "structs")
1289         return (out_java, out_java_enum, out_c)
1290
1291     def map_opaque_struct(self, struct_name, struct_doc_comment):
1292         method_header = ""
1293
1294         hu_name = struct_name.replace("LDKC2Tuple", "TwoTuple").replace("LDKC3Tuple", "ThreeTuple").replace("LDK", "")
1295         out_opaque_struct_human = f"{self.hu_struct_file_prefix}"
1296         extra_docs = ""
1297         extra_body = ""
1298         if struct_name.startswith("LDKLocked") or struct_name.startswith("LDKReadOnly"):
1299             extra_docs = "\n\tThis type represents a lock and MUST BE MANUALLY FREE'd!" # XXX: There's a thing for this
1300             constructor_body = 'super(ptr, () => { throw new Error("Locks must be manually freed with free()"); });'
1301             extra_body = f"""
1302         /** Releases this lock */
1303         public free() {{
1304                 bindings.{struct_name.replace("LDK","")}_free(this.ptr);
1305                 CommonBase.set_null_skip_free(this);
1306         }}"""
1307         formatted_doc_comment = struct_doc_comment.replace("\n", "\n\t")
1308         out_opaque_struct_human += f"""
1309 class {hu_name} {{
1310         \"\"\"{extra_docs}
1311         {formatted_doc_comment}
1312         \"\"\"
1313         def __init__(_dummy: null, ptr: int):
1314                 self.ptr = ptr
1315
1316         def __del__(self):
1317                 bindings.{struct_name.replace("LDK","")}_free(self.ptr)
1318 {extra_body}
1319
1320 """
1321         self.obj_defined([hu_name], "structs")
1322         return out_opaque_struct_human
1323
1324     def map_tuple(self, struct_name):
1325         return self.map_opaque_struct(struct_name, "A Tuple")
1326
1327     def map_result(self, struct_name, res_map, err_map):
1328         human_ty = struct_name.replace("LDKCResult", "Result")
1329
1330         suffixes = f"export class {human_ty}_OK extends {human_ty} {{\n"
1331         if res_map.java_hu_ty != "void":
1332             suffixes += "\tpublic res: " + res_map.java_hu_ty + ";\n"
1333         suffixes += f"""
1334         /* @internal */
1335         public constructor(_dummy: null, ptr: bigint) {{
1336                 super(_dummy, ptr);
1337 """
1338         if res_map.java_hu_ty == "void":
1339             pass
1340         elif res_map.to_hu_conv is not None:
1341             suffixes += "\t\tconst res: " + res_map.java_ty + " = bindings." + struct_name.replace("LDK", "") + "_get_ok(ptr);\n"
1342             suffixes += "\t\t" + res_map.to_hu_conv.replace("\n", "\n\t\t")
1343             suffixes += "\n\t\tthis.res = " + res_map.to_hu_conv_name + ";\n"
1344         else:
1345             suffixes += "\t\tthis.res = bindings." + struct_name.replace("LDK", "") + "_get_ok(ptr);\n"
1346         suffixes += "\t}\n}\n"
1347
1348         suffixes += f"export class {human_ty}_Err extends {human_ty} {{\n"
1349         if err_map.java_hu_ty != "void":
1350             suffixes += "\tpublic err: " + err_map.java_hu_ty + ";\n"
1351         suffixes += f"""
1352         /* @internal */
1353         public constructor(_dummy: null, ptr: bigint) {{
1354                 super(_dummy, ptr);
1355 """
1356         if err_map.java_hu_ty == "void":
1357             pass
1358         elif err_map.to_hu_conv is not None:
1359             suffixes += "\t\tconst err: " + err_map.java_ty + " = bindings." + struct_name.replace("LDK", "") + "_get_err(ptr);\n"
1360             suffixes += "\t\t" + err_map.to_hu_conv.replace("\n", "\n\t\t")
1361             suffixes += "\n\t\tthis.err = " + err_map.to_hu_conv_name + ";\n"
1362         else:
1363             suffixes += "\t\tthis.err = bindings." + struct_name.replace("LDK", "") + "_get_err(ptr);\n"
1364         suffixes += "\t}\n}"
1365
1366         self.struct_file_suffixes[human_ty] = suffixes
1367         self.obj_defined([human_ty], "structs")
1368
1369         return f"""{self.hu_struct_file_prefix}
1370
1371 export class {human_ty} extends CommonBase {{
1372         protected constructor(_dummy: null, ptr: bigint) {{
1373                 super(ptr, bindings.{struct_name.replace("LDK","")}_free);
1374         }}
1375         /* @internal */
1376         public static constr_from_ptr(ptr: bigint): {human_ty} {{
1377                 if (bindings.{struct_name.replace("LDK", "")}_is_ok(ptr)) {{
1378                         return new {human_ty}_OK(null, ptr);
1379                 }} else {{
1380                         return new {human_ty}_Err(null, ptr);
1381                 }}
1382         }}
1383 """
1384
1385     def fn_call_body(self, method_name, return_c_ty, return_java_ty, method_argument_string, native_call_argument_string):
1386         has_return_value = return_c_ty != 'void'
1387         return_statement = 'return nativeResponseValue;'
1388         if not has_return_value:
1389             return_statement = '// debug statements here'
1390
1391         return f"""/* @internal */
1392 export function {method_name}({method_argument_string}): {return_java_ty} {{
1393         if(!isWasmInitialized) {{
1394                 throw new Error("initializeWasm() must be awaited first!");
1395         }}
1396         const nativeResponseValue = wasm.TS_{method_name}({native_call_argument_string});
1397         {return_statement}
1398 }}
1399 """
1400     def map_function(self, argument_types, c_call_string, method_name, meth_n, return_type_info, struct_meth, default_constructor_args, takes_self, takes_self_as_ref, args_known, type_mapping_generator, doc_comment):
1401         out_java = ""
1402         out_c = ""
1403         out_java_struct = None
1404
1405         out_java += ("\t")
1406         out_c += (self.c_fn_ty_pfx)
1407         out_c += (return_type_info.c_ty)
1408         out_java += (return_type_info.java_ty)
1409         if return_type_info.ret_conv is not None:
1410             ret_conv_pfx, ret_conv_sfx = return_type_info.ret_conv
1411         out_java += (" " + method_name + "(")
1412         out_c += (" "  + self.c_fn_name_define_pfx(method_name, True))
1413
1414         method_argument_string = ""
1415         native_call_argument_string = ""
1416         for idx, arg_conv_info in enumerate(argument_types):
1417             if idx != 0:
1418                 method_argument_string += (", ")
1419                 native_call_argument_string += ', '
1420                 out_c += (", ")
1421             if arg_conv_info.c_ty != "void":
1422                 out_c += (arg_conv_info.c_ty + " " + arg_conv_info.arg_name)
1423                 method_argument_string += f"{arg_conv_info.arg_name}: {arg_conv_info.java_ty}"
1424                 native_call_argument_string += arg_conv_info.arg_name
1425         out_java = self.fn_call_body(method_name, return_type_info.c_ty, return_type_info.java_ty, method_argument_string, native_call_argument_string)
1426
1427         out_java_struct = ""
1428         if doc_comment is not None:
1429             out_java_struct = "\t/**\n\t * " + doc_comment.replace("\n", "\n\t * ") + "\n\t */\n"
1430
1431         if not args_known:
1432             out_java_struct += ("\t// Skipped " + method_name + "\n")
1433         else:
1434             if not takes_self:
1435                 out_java_struct += (
1436                         "\tpublic static constructor_" + meth_n + "(")
1437             else:
1438                 out_java_struct += ("\tpublic " + meth_n + "(")
1439             for idx, arg in enumerate(argument_types):
1440                 if idx != 0:
1441                     if not takes_self or idx > 1:
1442                         out_java_struct += (", ")
1443                 elif takes_self:
1444                     continue
1445                 if arg.java_ty != "void":
1446                     if arg.arg_name in default_constructor_args:
1447                         for explode_idx, explode_arg in enumerate(default_constructor_args[arg.arg_name]):
1448                             if explode_idx != 0:
1449                                 out_java_struct += (", ")
1450                             out_java_struct += arg.arg_name + "_" + explode_arg.arg_name + ": " + explode_arg.java_hu_ty
1451                     else:
1452                         out_java_struct += arg.arg_name + ": " + arg.java_hu_ty
1453                         if arg.nullable:
1454                             out_java_struct += "|null"
1455
1456         out_c += (") {\n")
1457         if out_java_struct is not None:
1458             out_java_struct += "): " + return_type_info.java_hu_ty + " {\n"
1459         for info in argument_types:
1460             if info.arg_conv is not None:
1461                 out_c += ("\t" + info.arg_conv.replace('\n', "\n\t") + "\n")
1462         if return_type_info.ret_conv is not None:
1463             out_c += ("\t" + ret_conv_pfx.replace('\n', '\n\t'))
1464         elif return_type_info.c_ty != "void":
1465             out_c += ("\t" + return_type_info.c_ty + " ret_val = ")
1466         else:
1467             out_c += ("\t")
1468         if c_call_string is None:
1469             out_c += (method_name + "(")
1470         else:
1471             out_c += (c_call_string)
1472         for idx, info in enumerate(argument_types):
1473             if info.arg_conv_name is not None:
1474                 if idx != 0:
1475                     out_c += (", ")
1476                 elif c_call_string is not None:
1477                     continue
1478                 out_c += (info.arg_conv_name)
1479         out_c += (")")
1480         if return_type_info.ret_conv is not None:
1481             out_c += (ret_conv_sfx.replace('\n', '\n\t'))
1482         else:
1483             out_c += (";")
1484         for info in argument_types:
1485             if info.arg_conv_cleanup is not None:
1486                 out_c += ("\n\t" + info.arg_conv_cleanup.replace("\n", "\n\t"))
1487         if return_type_info.ret_conv is not None:
1488             out_c += ("\n\treturn " + return_type_info.ret_conv_name + ";")
1489         elif return_type_info.c_ty != "void":
1490             out_c += ("\n\treturn ret_val;")
1491         out_c += ("\n}\n\n")
1492
1493         if args_known:
1494             out_java_struct += ("\t\t")
1495             if return_type_info.java_ty != "void":
1496                 out_java_struct += "const ret: " + return_type_info.java_ty + " = "
1497             out_java_struct += ("bindings." + method_name + "(")
1498             for idx, info in enumerate(argument_types):
1499                 if idx != 0:
1500                     out_java_struct += (", ")
1501                 if idx == 0 and takes_self:
1502                     out_java_struct += ("this.ptr")
1503                 elif info.arg_name in default_constructor_args:
1504                     out_java_struct += ("bindings." + info.java_hu_ty + "_new(")
1505                     for explode_idx, explode_arg in enumerate(default_constructor_args[info.arg_name]):
1506                         if explode_idx != 0:
1507                             out_java_struct += (", ")
1508                         expl_arg_name = info.arg_name + "_" + explode_arg.arg_name
1509                         if explode_arg.from_hu_conv is not None:
1510                             out_java_struct += (
1511                                 explode_arg.from_hu_conv[0].replace(explode_arg.arg_name, expl_arg_name))
1512                         else:
1513                             out_java_struct += (expl_arg_name)
1514                     out_java_struct += (")")
1515                 elif info.from_hu_conv is not None:
1516                     out_java_struct += (info.from_hu_conv[0])
1517                 else:
1518                     out_java_struct += (info.arg_name)
1519             out_java_struct += (");\n")
1520             if return_type_info.to_hu_conv is not None:
1521                 if not takes_self:
1522                     out_java_struct += ("\t\t" + return_type_info.to_hu_conv.replace("\n", "\n\t\t").replace("this",
1523                                                                                                              return_type_info.to_hu_conv_name) + "\n")
1524                 else:
1525                     out_java_struct += ("\t\t" + return_type_info.to_hu_conv.replace("\n", "\n\t\t") + "\n")
1526
1527             for idx, info in enumerate(argument_types):
1528                 if idx == 0 and takes_self:
1529                     pass
1530                 elif info.arg_name in default_constructor_args:
1531                     for explode_arg in default_constructor_args[info.arg_name]:
1532                         expl_arg_name = info.arg_name + "_" + explode_arg.arg_name
1533                         if explode_arg.from_hu_conv is not None and return_type_info.to_hu_conv_name:
1534                             out_java_struct += ("\t\t" + explode_arg.from_hu_conv[1].replace(explode_arg.arg_name,
1535                                                                                              expl_arg_name).replace(
1536                                 "this", return_type_info.to_hu_conv_name) + ";\n")
1537                 elif info.from_hu_conv is not None and info.from_hu_conv[1] != "":
1538                     if not takes_self and return_type_info.to_hu_conv_name is not None:
1539                         out_java_struct += (
1540                                 "\t\t" + info.from_hu_conv[1].replace("this", return_type_info.to_hu_conv_name).replace("\n", "\n\t\t") + ";\n")
1541                     else:
1542                         out_java_struct += ("\t\t" + info.from_hu_conv[1].replace("\n", "\n\t\t") + ";\n")
1543
1544             if return_type_info.to_hu_conv_name is not None:
1545                 out_java_struct += ("\t\treturn " + return_type_info.to_hu_conv_name + ";\n")
1546             elif return_type_info.java_ty != "void" and return_type_info.rust_obj != "LDK" + struct_meth:
1547                 out_java_struct += ("\t\treturn ret;\n")
1548             out_java_struct += ("\t}\n\n")
1549
1550         return (out_java, out_c, out_java_struct)
1551
1552     def cleanup(self):
1553         for struct in self.struct_file_suffixes:
1554             with open(self.outdir + "/structs/" + struct + self.file_ext, "a") as src:
1555                 src.write(self.struct_file_suffixes[struct])
1556
1557         with open(self.outdir + "/bindings.py", "a") as bindings:
1558             bindings.write("""
1559
1560 js_invoke = function(obj_ptr: number, fn_id: number, arg1: bigint|number, arg2: bigint|number, arg3: bigint|number, arg4: bigint|number, arg5: bigint|number, arg6: bigint|number, arg7: bigint|number, arg8: bigint|number, arg9: bigint|number, arg10: bigint|number) {
1561         const weak: WeakRef<object>|undefined = js_objs[obj_ptr];
1562         if (weak == null || weak == undefined) {
1563                 console.error("Got function call on unknown/free'd JS object!");
1564                 throw new Error("Got function call on unknown/free'd JS object!");
1565         }
1566         const obj = weak.deref();
1567         if (obj == null || obj == undefined) {
1568                 console.error("Got function call on GC'd JS object!");
1569                 throw new Error("Got function call on GC'd JS object!");
1570         }
1571         var fn;
1572 """)
1573             bindings.write("\tswitch (fn_id) {\n")
1574             for f in self.function_ptrs:
1575                 bindings.write(f"\t\tcase {str(f)}: fn = Object.getOwnPropertyDescriptor(obj, \"{self.function_ptrs[f][1]}\"); break;\n")
1576
1577             bindings.write("""\t\tdefault:
1578                         console.error("Got unknown function call from C!");
1579                         throw new Error("Got unknown function call from C!");
1580         }
1581         if (fn == null || fn == undefined) {
1582                 console.error("Got function call on incorrect JS object!");
1583                 throw new Error("Got function call on incorrect JS object!");
1584         }
1585         const ret = fn.value.bind(obj)(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10);
1586         if (ret === undefined || ret === null) return BigInt(0);
1587         return BigInt(ret);
1588 }""")