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