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