Clone before passing to java + new clone upstream
[ldk-java] / genbindings.py
1 #!/usr/bin/env python3
2 import sys, re
3
4 if len(sys.argv) != 6:
5     print("USAGE: /path/to/lightning.h /path/to/bindings/output.java /path/to/bindings/ /path/to/bindings/output.c debug")
6     print("debug should be true or false and indicates whether to track allocations and ensure we don't leak")
7     sys.exit(1)
8
9 hu_struct_file_prefix = """package org.ldk.structs;
10
11 import org.ldk.impl.bindings;
12 import org.ldk.enums.*;
13 import org.ldk.util.*;
14 import java.util.Arrays;
15
16 @SuppressWarnings("unchecked") // We correctly assign various generic arrays
17 """
18
19 c_file_pfx = """#include \"org_ldk_impl_bindings.h\"
20 #include <rust_types.h>
21 #include <lightning.h>
22 #include <string.h>
23 #include <stdatomic.h>
24 """
25
26 if sys.argv[5] == "false":
27     c_file_pfx = c_file_pfx + """#define MALLOC(a, _) malloc(a)
28 #define FREE(p) if ((long)(p) > 1024) { free(p); }
29 #define DO_ASSERT(a) (void)(a)
30 #define CHECK(a)
31 """
32 else:
33     c_file_pfx = c_file_pfx + """#include <assert.h>
34 // Always run a, then assert it is true:
35 #define DO_ASSERT(a) do { bool _assert_val = (a); assert(_assert_val); } while(0)
36 // Assert a is true or do nothing
37 #define CHECK(a) DO_ASSERT(a)
38
39 // Running a leak check across all the allocations and frees of the JDK is a mess,
40 // so instead we implement our own naive leak checker here, relying on the -wrap
41 // linker option to wrap malloc/calloc/realloc/free, tracking everyhing allocated
42 // and free'd in Rust or C across the generated bindings shared library.
43 #include <threads.h>
44 #include <execinfo.h>
45 #include <unistd.h>
46 static mtx_t allocation_mtx;
47
48 void __attribute__((constructor)) init_mtx() {
49         DO_ASSERT(mtx_init(&allocation_mtx, mtx_plain) == thrd_success);
50 }
51
52 #define BT_MAX 128
53 typedef struct allocation {
54         struct allocation* next;
55         void* ptr;
56         const char* struct_name;
57         void* bt[BT_MAX];
58         int bt_len;
59 } allocation;
60 static allocation* allocation_ll = NULL;
61
62 void* __real_malloc(size_t len);
63 void* __real_calloc(size_t nmemb, size_t len);
64 static void new_allocation(void* res, const char* struct_name) {
65         allocation* new_alloc = __real_malloc(sizeof(allocation));
66         new_alloc->ptr = res;
67         new_alloc->struct_name = struct_name;
68         new_alloc->bt_len = backtrace(new_alloc->bt, BT_MAX);
69         DO_ASSERT(mtx_lock(&allocation_mtx) == thrd_success);
70         new_alloc->next = allocation_ll;
71         allocation_ll = new_alloc;
72         DO_ASSERT(mtx_unlock(&allocation_mtx) == thrd_success);
73 }
74 static void* MALLOC(size_t len, const char* struct_name) {
75         void* res = __real_malloc(len);
76         new_allocation(res, struct_name);
77         return res;
78 }
79 void __real_free(void* ptr);
80 static void alloc_freed(void* ptr) {
81         allocation* p = NULL;
82         DO_ASSERT(mtx_lock(&allocation_mtx) == thrd_success);
83         allocation* it = allocation_ll;
84         while (it->ptr != ptr) {
85                 p = it; it = it->next;
86                 if (it == NULL) {
87                         fprintf(stderr, "Tried to free unknown pointer %p at:\\n", ptr);
88                         void* bt[BT_MAX];
89                         int bt_len = backtrace(bt, BT_MAX);
90                         backtrace_symbols_fd(bt, bt_len, STDERR_FILENO);
91                         fprintf(stderr, "\\n\\n");
92                         DO_ASSERT(mtx_unlock(&allocation_mtx) == thrd_success);
93                         return; // addrsan should catch malloc-unknown and print more info than we have
94                 }
95         }
96         if (p) { p->next = it->next; } else { allocation_ll = it->next; }
97         DO_ASSERT(mtx_unlock(&allocation_mtx) == thrd_success);
98         DO_ASSERT(it->ptr == ptr);
99         __real_free(it);
100 }
101 static void FREE(void* ptr) {
102         if ((long)ptr < 1024) return; // Rust loves to create pointers to the NULL page for dummys
103         alloc_freed(ptr);
104         __real_free(ptr);
105 }
106
107 void* __wrap_malloc(size_t len) {
108         void* res = __real_malloc(len);
109         new_allocation(res, "malloc call");
110         return res;
111 }
112 void* __wrap_calloc(size_t nmemb, size_t len) {
113         void* res = __real_calloc(nmemb, len);
114         new_allocation(res, "calloc call");
115         return res;
116 }
117 void __wrap_free(void* ptr) {
118         alloc_freed(ptr);
119         __real_free(ptr);
120 }
121
122 void* __real_realloc(void* ptr, size_t newlen);
123 void* __wrap_realloc(void* ptr, size_t len) {
124         alloc_freed(ptr);
125         void* res = __real_realloc(ptr, len);
126         new_allocation(res, "realloc call");
127         return res;
128 }
129 void __wrap_reallocarray(void* ptr, size_t new_sz) {
130         // Rust doesn't seem to use reallocarray currently
131         assert(false);
132 }
133
134 void __attribute__((destructor)) check_leaks() {
135         for (allocation* a = allocation_ll; a != NULL; a = a->next) {
136                 fprintf(stderr, "%s %p remains:\\n", a->struct_name, a->ptr);
137                 backtrace_symbols_fd(a->bt, a->bt_len, STDERR_FILENO);
138                 fprintf(stderr, "\\n\\n");
139         }
140         DO_ASSERT(allocation_ll == NULL);
141 }
142 """
143
144 c_file = ""
145 def write_c(s):
146     global c_file
147     c_file += s
148
149 class TypeInfo:
150     def __init__(self, is_native_primitive, rust_obj, java_ty, java_fn_ty_arg, java_hu_ty, c_ty, passed_as_ptr, is_ptr, var_name, arr_len, arr_access, subty=None):
151         self.is_native_primitive = is_native_primitive
152         self.rust_obj = rust_obj
153         self.java_ty = java_ty
154         self.java_hu_ty = java_hu_ty
155         self.java_fn_ty_arg = java_fn_ty_arg
156         self.c_ty = c_ty
157         self.passed_as_ptr = passed_as_ptr
158         self.is_ptr = is_ptr
159         self.var_name = var_name
160         self.arr_len = arr_len
161         self.arr_access = arr_access
162         self.subty = subty
163         self.pass_by_ref = is_ptr
164
165 class ConvInfo:
166     def __init__(self, ty_info, arg_name, arg_conv, arg_conv_name, arg_conv_cleanup, ret_conv, ret_conv_name, to_hu_conv, to_hu_conv_name, from_hu_conv):
167         assert(ty_info.c_ty is not None)
168         assert(ty_info.java_ty is not None)
169         assert(arg_name is not None)
170         self.passed_as_ptr = ty_info.passed_as_ptr
171         self.rust_obj = ty_info.rust_obj
172         self.c_ty = ty_info.c_ty
173         self.java_ty = ty_info.java_ty
174         self.java_hu_ty = ty_info.java_hu_ty
175         self.java_fn_ty_arg = ty_info.java_fn_ty_arg
176         self.arg_name = arg_name
177         self.arg_conv = arg_conv
178         self.arg_conv_name = arg_conv_name
179         self.arg_conv_cleanup = arg_conv_cleanup
180         self.ret_conv = ret_conv
181         self.ret_conv_name = ret_conv_name
182         self.to_hu_conv = to_hu_conv
183         self.to_hu_conv_name = to_hu_conv_name
184         self.from_hu_conv = from_hu_conv
185
186     def print_ty(self):
187         write_c(self.c_ty)
188         out_java.write(self.java_ty)
189
190     def print_name(self):
191         if self.arg_name != "":
192             out_java.write(" " + self.arg_name)
193             write_c(" " + self.arg_name)
194         else:
195             out_java.write(" arg")
196             write_c(" arg")
197
198 def camel_to_snake(s):
199     # Convert camel case to snake case, in a way that appears to match cbindgen
200     con = "_"
201     ret = ""
202     lastchar = ""
203     lastund = False
204     for char in s:
205         if lastchar.isupper():
206             if not char.isupper() and not lastund:
207                 ret = ret + "_"
208                 lastund = True
209             else:
210                 lastund = False
211             ret = ret + lastchar.lower()
212         else:
213             ret = ret + lastchar
214             if char.isupper() and not lastund:
215                 ret = ret + "_"
216                 lastund = True
217             else:
218                 lastund = False
219         lastchar = char
220         if char.isnumeric():
221             lastund = True
222     return (ret + lastchar.lower()).strip("_")
223
224 unitary_enums = set()
225 complex_enums = set()
226 opaque_structs = set()
227 trait_structs = set()
228 result_types = set()
229 tuple_types = {}
230
231 def is_common_base_ext(struct_name):
232     return struct_name in complex_enums or struct_name in opaque_structs or struct_name in trait_structs or struct_name in result_types
233
234 var_is_arr_regex = re.compile("\(\*([A-za-z0-9_]*)\)\[([a-z0-9]*)\]")
235 var_ty_regex = re.compile("([A-za-z_0-9]*)(.*)")
236 java_c_types_none_allowed = True # Unset when we do the real pass that populates the above sets
237 def java_c_types(fn_arg, ret_arr_len):
238     fn_arg = fn_arg.strip()
239     if fn_arg.startswith("MUST_USE_RES "):
240         fn_arg = fn_arg[13:]
241     is_const = False
242     if fn_arg.startswith("const "):
243         fn_arg = fn_arg[6:]
244         is_const = True
245
246     is_ptr = False
247     take_by_ptr = False
248     rust_obj = None
249     arr_access = None
250     java_hu_ty = None
251     if fn_arg.startswith("LDKThirtyTwoBytes"):
252         fn_arg = "uint8_t (*" + fn_arg[18:] + ")[32]"
253         assert var_is_arr_regex.match(fn_arg[8:])
254         rust_obj = "LDKThirtyTwoBytes"
255         arr_access = "data"
256     elif fn_arg.startswith("LDKPublicKey"):
257         fn_arg = "uint8_t (*" + fn_arg[13:] + ")[33]"
258         assert var_is_arr_regex.match(fn_arg[8:])
259         rust_obj = "LDKPublicKey"
260         arr_access = "compressed_form"
261     elif fn_arg.startswith("LDKSecretKey"):
262         fn_arg = "uint8_t (*" + fn_arg[13:] + ")[32]"
263         assert var_is_arr_regex.match(fn_arg[8:])
264         rust_obj = "LDKSecretKey"
265         arr_access = "bytes"
266     elif fn_arg.startswith("LDKSignature"):
267         fn_arg = "uint8_t (*" + fn_arg[13:] + ")[64]"
268         assert var_is_arr_regex.match(fn_arg[8:])
269         rust_obj = "LDKSignature"
270         arr_access = "compact_form"
271     elif fn_arg.startswith("LDKThreeBytes"):
272         fn_arg = "uint8_t (*" + fn_arg[14:] + ")[3]"
273         assert var_is_arr_regex.match(fn_arg[8:])
274         rust_obj = "LDKThreeBytes"
275         arr_access = "data"
276     elif fn_arg.startswith("LDKFourBytes"):
277         fn_arg = "uint8_t (*" + fn_arg[13:] + ")[4]"
278         assert var_is_arr_regex.match(fn_arg[8:])
279         rust_obj = "LDKFourBytes"
280         arr_access = "data"
281     elif fn_arg.startswith("LDKSixteenBytes"):
282         fn_arg = "uint8_t (*" + fn_arg[16:] + ")[16]"
283         assert var_is_arr_regex.match(fn_arg[8:])
284         rust_obj = "LDKSixteenBytes"
285         arr_access = "data"
286     elif fn_arg.startswith("LDKTenBytes"):
287         fn_arg = "uint8_t (*" + fn_arg[12:] + ")[10]"
288         assert var_is_arr_regex.match(fn_arg[8:])
289         rust_obj = "LDKTenBytes"
290         arr_access = "data"
291     elif fn_arg.startswith("LDKu8slice"):
292         fn_arg = "uint8_t (*" + fn_arg[11:] + ")[datalen]"
293         assert var_is_arr_regex.match(fn_arg[8:])
294         rust_obj = "LDKu8slice"
295         arr_access = "data"
296     elif fn_arg.startswith("LDKCVecTempl_u8") or fn_arg.startswith("LDKCVec_u8Z"):
297         if fn_arg.startswith("LDKCVecTempl_u8"):
298             fn_arg = "uint8_t (*" + fn_arg[16:] + ")[datalen]"
299             rust_obj = "LDKCVecTempl_u8"
300             assert var_is_arr_regex.match(fn_arg[8:])
301         else:
302             fn_arg = "uint8_t (*" + fn_arg[12:] + ")[datalen]"
303             rust_obj = "LDKCVec_u8Z"
304             assert var_is_arr_regex.match(fn_arg[8:])
305         arr_access = "data"
306     elif fn_arg.startswith("LDKCVecTempl_") or fn_arg.startswith("LDKCVec_"):
307         is_ptr = False
308         if "*" in fn_arg:
309             fn_arg = fn_arg.replace("*", "")
310             is_ptr = True
311
312         if fn_arg.startswith("LDKCVec_"):
313             tyn = fn_arg[8:].split(" ")
314             assert tyn[0].endswith("Z")
315             if tyn[0] == "u64Z":
316                 new_arg = "uint64_t"
317             else:
318                 new_arg = "LDK" + tyn[0][:-1]
319             for a in tyn[1:]:
320                 new_arg = new_arg + " " + a
321             res = java_c_types(new_arg, ret_arr_len)
322         else:
323             res = java_c_types("LDK" + fn_arg[13:], ret_arr_len)
324         if res is None:
325             assert java_c_types_none_allowed
326             return None
327         if is_ptr:
328             res.pass_by_ref = True
329         if res.is_native_primitive or res.passed_as_ptr:
330             return TypeInfo(rust_obj=fn_arg.split(" ")[0], java_ty=res.java_ty + "[]", java_hu_ty=res.java_hu_ty + "[]",
331                 java_fn_ty_arg="[" + res.java_fn_ty_arg, c_ty=res.c_ty + "Array", passed_as_ptr=False, is_ptr=is_ptr,
332                 var_name=res.var_name, arr_len="datalen", arr_access="data", subty=res, is_native_primitive=False)
333         else:
334             return TypeInfo(rust_obj=fn_arg.split(" ")[0], java_ty=res.java_ty + "[]", java_hu_ty=res.java_hu_ty + "[]",
335                 java_fn_ty_arg="[" + res.java_fn_ty_arg, c_ty="jobjectArray", passed_as_ptr=False, is_ptr=is_ptr,
336                 var_name=res.var_name, arr_len="datalen", arr_access="data", subty=res, is_native_primitive=False)
337
338     is_primitive = False
339     arr_len = None
340     if fn_arg.startswith("void"):
341         java_ty = "void"
342         c_ty = "void"
343         fn_ty_arg = "V"
344         fn_arg = fn_arg[4:].strip()
345         is_primitive = True
346     elif fn_arg.startswith("bool"):
347         java_ty = "boolean"
348         c_ty = "jboolean"
349         fn_ty_arg = "Z"
350         fn_arg = fn_arg[4:].strip()
351         is_primitive = True
352     elif fn_arg.startswith("uint8_t"):
353         java_ty = "byte"
354         c_ty = "jbyte"
355         fn_ty_arg = "B"
356         fn_arg = fn_arg[7:].strip()
357         is_primitive = True
358     elif fn_arg.startswith("uint16_t"):
359         java_ty = "short"
360         c_ty = "jshort"
361         fn_ty_arg = "S"
362         fn_arg = fn_arg[8:].strip()
363         is_primitive = True
364     elif fn_arg.startswith("uint32_t"):
365         java_ty = "int"
366         c_ty = "jint"
367         fn_ty_arg = "I"
368         fn_arg = fn_arg[8:].strip()
369         is_primitive = True
370     elif fn_arg.startswith("uint64_t") or fn_arg.startswith("uintptr_t"):
371         java_ty = "long"
372         c_ty = "jlong"
373         fn_ty_arg = "J"
374         if fn_arg.startswith("uint64_t"):
375             fn_arg = fn_arg[8:].strip()
376         else:
377             fn_arg = fn_arg[9:].strip()
378         is_primitive = True
379     elif is_const and fn_arg.startswith("char *"):
380         java_ty = "String"
381         c_ty = "const char*"
382         fn_ty_arg = "Ljava/lang/String;"
383         fn_arg = fn_arg[6:].strip()
384     elif fn_arg.startswith("LDKStr"):
385         java_ty = "String"
386         c_ty = "jstring"
387         fn_ty_arg = "Ljava/lang/String;"
388         fn_arg = fn_arg[6:].strip()
389         arr_access = "chars"
390         arr_len = "len"
391     else:
392         ma = var_ty_regex.match(fn_arg)
393         if ma.group(1).strip() in unitary_enums:
394             java_ty = ma.group(1).strip()
395             c_ty = "jclass"
396             fn_ty_arg = "Lorg/ldk/enums/" + ma.group(1).strip() + ";"
397             fn_arg = ma.group(2).strip()
398             rust_obj = ma.group(1).strip()
399             take_by_ptr = True
400         elif ma.group(1).strip().startswith("LDKC2Tuple"):
401             java_ty = "long"
402             java_hu_ty = "TwoTuple<"
403             if not ma.group(1).strip() in tuple_types:
404                 assert java_c_types_none_allowed
405                 return None
406             for idx, ty_info in enumerate(tuple_types[ma.group(1).strip()][0]):
407                 if idx != 0:
408                     java_hu_ty = java_hu_ty + ", "
409                 if ty_info.is_native_primitive:
410                     java_hu_ty = java_hu_ty + ty_info.java_hu_ty.title() # If we're a primitive, capitalize the first letter
411                 else:
412                     java_hu_ty = java_hu_ty + ty_info.java_hu_ty
413             java_hu_ty = java_hu_ty + ">"
414             c_ty = "jlong"
415             fn_ty_arg = "J"
416             fn_arg = ma.group(2).strip()
417             rust_obj = ma.group(1).strip()
418             take_by_ptr = True
419         elif ma.group(1).strip().startswith("LDKC3Tuple"):
420             java_ty = "long"
421             java_hu_ty = "ThreeTuple<"
422             if not ma.group(1).strip() in tuple_types:
423                 assert java_c_types_none_allowed
424                 return None
425             for idx, ty_info in enumerate(tuple_types[ma.group(1).strip()][0]):
426                 if idx != 0:
427                     java_hu_ty = java_hu_ty + ", "
428                 if ty_info.is_native_primitive:
429                     java_hu_ty = java_hu_ty + ty_info.java_hu_ty.title() # If we're a primitive, capitalize the first letter
430                 else:
431                     java_hu_ty = java_hu_ty + ty_info.java_hu_ty
432             java_hu_ty = java_hu_ty + ">"
433             c_ty = "jlong"
434             fn_ty_arg = "J"
435             fn_arg = ma.group(2).strip()
436             rust_obj = ma.group(1).strip()
437             take_by_ptr = True
438         else:
439             java_ty = "long"
440             java_hu_ty = ma.group(1).strip().replace("LDKCResult", "Result").replace("LDK", "")
441             c_ty = "jlong"
442             fn_ty_arg = "J"
443             fn_arg = ma.group(2).strip()
444             rust_obj = ma.group(1).strip()
445             take_by_ptr = True
446
447     if fn_arg.startswith(" *") or fn_arg.startswith("*"):
448         fn_arg = fn_arg.replace("*", "").strip()
449         is_ptr = True
450         c_ty = "jlong"
451         java_ty = "long"
452         fn_ty_arg = "J"
453         is_primitive = False
454
455     var_is_arr = var_is_arr_regex.match(fn_arg)
456     if var_is_arr is not None or ret_arr_len is not None:
457         assert(not take_by_ptr)
458         assert(not is_ptr)
459         java_ty = java_ty + "[]"
460         c_ty = c_ty + "Array"
461         if var_is_arr is not None:
462             if var_is_arr.group(1) == "":
463                 return TypeInfo(rust_obj=rust_obj, java_ty=java_ty, java_hu_ty=java_ty, java_fn_ty_arg="[" + fn_ty_arg, c_ty=c_ty,
464                     passed_as_ptr=False, is_ptr=False, var_name="arg", arr_len=var_is_arr.group(2), arr_access=arr_access, is_native_primitive=False)
465             return TypeInfo(rust_obj=rust_obj, java_ty=java_ty, java_hu_ty=java_ty, java_fn_ty_arg="[" + fn_ty_arg, c_ty=c_ty,
466                 passed_as_ptr=False, is_ptr=False, var_name=var_is_arr.group(1), arr_len=var_is_arr.group(2), arr_access=arr_access, is_native_primitive=False)
467
468     if java_hu_ty is None:
469         java_hu_ty = java_ty
470     return TypeInfo(rust_obj=rust_obj, java_ty=java_ty, java_hu_ty=java_hu_ty, java_fn_ty_arg=fn_ty_arg, c_ty=c_ty, passed_as_ptr=is_ptr or take_by_ptr,
471         is_ptr=is_ptr, var_name=fn_arg, arr_len=arr_len, arr_access=arr_access, is_native_primitive=is_primitive)
472
473 fn_ptr_regex = re.compile("^extern const ([A-Za-z_0-9\* ]*) \(\*(.*)\)\((.*)\);$")
474 fn_ret_arr_regex = re.compile("(.*) \(\*(.*)\((.*)\)\)\[([0-9]*)\];$")
475 reg_fn_regex = re.compile("([A-Za-z_0-9\* ]* \*?)([a-zA-Z_0-9]*)\((.*)\);$")
476 clone_fns = set()
477 constructor_fns = {}
478 c_array_class_caches = set()
479 with open(sys.argv[1]) as in_h:
480     for line in in_h:
481         reg_fn = reg_fn_regex.match(line)
482         if reg_fn is not None:
483             if reg_fn.group(2).endswith("_clone"):
484                 clone_fns.add(reg_fn.group(2))
485             else:
486                 rty = java_c_types(reg_fn.group(1), None)
487                 if rty is not None and rty.rust_obj is not None and reg_fn.group(2) == rty.java_hu_ty + "_new":
488                     constructor_fns[rty.rust_obj] = reg_fn.group(3)
489             continue
490         arr_fn = fn_ret_arr_regex.match(line)
491         if arr_fn is not None:
492             if arr_fn.group(2).endswith("_clone"):
493                 clone_fns.add(arr_fn.group(2))
494             # No object constructors return arrays, as then they wouldn't be an object constructor
495             continue
496 java_c_types_none_allowed = False # C structs created by cbindgen are declared in dependency order
497
498 with open(sys.argv[1]) as in_h, open(sys.argv[2], "w") as out_java:
499     def map_type(fn_arg, print_void, ret_arr_len, is_free, holds_ref):
500         ty_info = java_c_types(fn_arg, ret_arr_len)
501         return map_type_with_info(ty_info, print_void, ret_arr_len, is_free, holds_ref)
502
503     def map_type_with_info(ty_info, print_void, ret_arr_len, is_free, holds_ref):
504         if ty_info.c_ty == "void":
505             if not print_void:
506                 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
507                     arg_conv = None, arg_conv_name = None, arg_conv_cleanup = None,
508                     ret_conv = None, ret_conv_name = None, to_hu_conv = None, to_hu_conv_name = None, from_hu_conv = None)
509         if ty_info.c_ty.endswith("Array"):
510             arr_len = ty_info.arr_len
511             if arr_len is not None:
512                 arr_name = ty_info.var_name
513             else:
514                 arr_name = "ret"
515                 arr_len = ret_arr_len
516             if ty_info.c_ty == "jbyteArray":
517                 ret_conv = ("jbyteArray " + arr_name + "_arr = (*_env)->NewByteArray(_env, " + arr_len + ");\n" + "(*_env)->SetByteArrayRegion(_env, " + arr_name + "_arr, 0, " + arr_len + ", ", "")
518                 arg_conv_cleanup = None
519                 if not arr_len.isdigit():
520                     arg_conv = ty_info.rust_obj + " " + arr_name + "_ref;\n"
521                     arg_conv = arg_conv + arr_name + "_ref." + ty_info.arr_access + " = (*_env)->GetByteArrayElements (_env, " + arr_name + ", NULL);\n"
522                     arg_conv = arg_conv + arr_name + "_ref." + arr_len + " = (*_env)->GetArrayLength (_env, " + arr_name + ");"
523                     arg_conv_cleanup = "(*_env)->ReleaseByteArrayElements(_env, " + arr_name + ", (int8_t*)" + arr_name + "_ref." + ty_info.arr_access + ", 0);"
524                     ret_conv = (ty_info.rust_obj + " " + arr_name + "_var = ", "")
525                     ret_conv = (ret_conv[0], ";\njbyteArray " + arr_name + "_arr = (*_env)->NewByteArray(_env, " + arr_name + "_var." + arr_len + ");\n")
526                     ret_conv = (ret_conv[0], ret_conv[1] + "(*_env)->SetByteArrayRegion(_env, " + arr_name + "_arr, 0, " + arr_name + "_var." + arr_len + ", " + arr_name + "_var." + ty_info.arr_access + ");")
527                     if not holds_ref and ty_info.rust_obj == "LDKCVec_u8Z":
528                         ret_conv = (ret_conv[0], ret_conv[1] + "\nCVec_u8Z_free(" + arr_name + "_var);")
529                 elif ty_info.rust_obj is not None:
530                     arg_conv = ty_info.rust_obj + " " + arr_name + "_ref;\n"
531                     arg_conv = arg_conv + "CHECK((*_env)->GetArrayLength (_env, " + arr_name + ") == " + arr_len + ");\n"
532                     arg_conv = arg_conv + "(*_env)->GetByteArrayRegion (_env, " + arr_name + ", 0, " + arr_len + ", " + arr_name + "_ref." + ty_info.arr_access + ");"
533                     ret_conv = (ret_conv[0], "." + ty_info.arr_access + ");")
534                 else:
535                     arg_conv = "unsigned char " + arr_name + "_arr[" + arr_len + "];\n"
536                     arg_conv = arg_conv + "CHECK((*_env)->GetArrayLength (_env, " + arr_name + ") == " + arr_len + ");\n"
537                     arg_conv = arg_conv + "(*_env)->GetByteArrayRegion (_env, " + arr_name + ", 0, " + arr_len + ", " + arr_name + "_arr);\n" + "unsigned char (*" + arr_name + "_ref)[" + arr_len + "] = &" + arr_name + "_arr;"
538                     ret_conv = (ret_conv[0] + "*", ");")
539                 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
540                     arg_conv = arg_conv, arg_conv_name = arr_name + "_ref", arg_conv_cleanup = arg_conv_cleanup,
541                     ret_conv = ret_conv, ret_conv_name = arr_name + "_arr", to_hu_conv = None, to_hu_conv_name = None, from_hu_conv = None)
542             else:
543                 assert not arr_len.isdigit() # fixed length arrays not implemented
544                 assert ty_info.java_ty[len(ty_info.java_ty) - 2:] == "[]"
545                 conv_name = "arr_conv_" + str(len(ty_info.java_hu_ty))
546                 idxc = chr(ord('a') + (len(ty_info.java_hu_ty) % 26))
547                 ty_info.subty.var_name = conv_name
548                 ty_info.subty.passed_as_ptr = False
549                 subty = map_type_with_info(ty_info.subty, False, None, is_free, holds_ref)
550                 if arr_name == "":
551                     arr_name = "arg"
552                 arg_conv = ty_info.rust_obj + " " + arr_name + "_constr;\n"
553                 arg_conv = arg_conv + arr_name + "_constr." + arr_len + " = (*_env)->GetArrayLength (_env, " + arr_name + ");\n"
554                 arg_conv = arg_conv + "if (" + arr_name + "_constr." + arr_len + " > 0)\n"
555                 if subty.rust_obj is None:
556                     szof = subty.c_ty
557                 else:
558                     szof = subty.rust_obj
559                 arg_conv = arg_conv + "\t" + arr_name + "_constr." + ty_info.arr_access + " = MALLOC(" + arr_name + "_constr." + arr_len + " * sizeof(" + szof + "), \"" + ty_info.rust_obj + " Elements\");\n"
560                 arg_conv = arg_conv + "else\n"
561                 arg_conv = arg_conv + "\t" + arr_name + "_constr." + ty_info.arr_access + " = NULL;\n"
562                 if not ty_info.java_ty[:len(ty_info.java_ty) - 2].endswith("[]"):
563                     arg_conv = arg_conv + ty_info.java_ty.strip("[]") + "* " + arr_name + "_vals = (*_env)->Get" + ty_info.subty.java_ty.title() + "ArrayElements (_env, " + arr_name + ", NULL);\n"
564                 arg_conv = arg_conv + "for (size_t " + idxc + " = 0; " + idxc + " < " + arr_name + "_constr." + arr_len + "; " + idxc + "++) {\n"
565                 if not ty_info.java_ty[:len(ty_info.java_ty) - 2].endswith("[]"):
566                     arg_conv = arg_conv + "\t" + ty_info.java_ty.strip("[]") + " " + conv_name + " = " + arr_name + "_vals[" + idxc + "];"
567                     if subty.arg_conv is not None:
568                         arg_conv = arg_conv + "\n\t" + subty.arg_conv.replace("\n", "\n\t")
569                 else:
570                     arg_conv = arg_conv + "\tjobject " + conv_name + " = (*_env)->GetObjectArrayElement(_env, " + arr_name + ", " + idxc + ");\n"
571                     arg_conv = arg_conv + "\t" + subty.arg_conv.replace("\n", "\n\t")
572                 arg_conv = arg_conv + "\n\t" + arr_name + "_constr." + ty_info.arr_access + "[" + idxc + "] = " + subty.arg_conv_name + ";\n}"
573                 if not ty_info.java_ty[:len(ty_info.java_ty) - 2].endswith("[]"):
574                     arg_conv = arg_conv + "\n(*_env)->Release" + ty_info.java_ty.strip("[]").title() + "ArrayElements (_env, " + arr_name + ", " + arr_name + "_vals, 0);"
575                 if ty_info.is_ptr:
576                     arg_conv_name = "&" + arr_name + "_constr"
577                 else:
578                     arg_conv_name = arr_name + "_constr"
579                 arg_conv_cleanup = None
580                 if ty_info.is_ptr:
581                     arg_conv_cleanup = "FREE(" + arr_name + "_constr." + ty_info.arr_access + ");"
582
583                 if arr_name == "arg":
584                     arr_name = "ret"
585                 ret_conv = (ty_info.rust_obj + " " + arr_name + "_var = ", "")
586                 if subty.ret_conv is None:
587                     ret_conv = ("DUMMY", "DUMMY")
588                 elif not ty_info.java_ty[:len(ty_info.java_ty) - 2].endswith("[]"):
589                     ret_conv = (ret_conv[0], ";\n" + ty_info.c_ty + " " + arr_name + "_arr = (*_env)->New" + ty_info.java_ty.strip("[]").title() + "Array(_env, " + arr_name + "_var." + arr_len + ");\n")
590                     ret_conv = (ret_conv[0], ret_conv[1] + subty.c_ty + " *" + arr_name + "_arr_ptr = (*_env)->GetPrimitiveArrayCritical(_env, " + arr_name + "_arr, NULL);\n")
591                     ret_conv = (ret_conv[0], ret_conv[1] + "for (size_t " + idxc + " = 0; " + idxc + " < " + arr_name + "_var." + arr_len + "; " + idxc + "++) {\n")
592                     ret_conv = (ret_conv[0], ret_conv[1] + "\t" + subty.ret_conv[0].replace("\n", "\n\t"))
593                     ret_conv = (ret_conv[0], ret_conv[1] + arr_name + "_var." + ty_info.arr_access + "[" + idxc + "]" + subty.ret_conv[1].replace("\n", "\n\t"))
594                     ret_conv = (ret_conv[0], ret_conv[1] + "\n\t" + arr_name + "_arr_ptr[" + idxc + "] = " + subty.ret_conv_name + ";\n")
595                     ret_conv = (ret_conv[0], ret_conv[1] + "}\n(*_env)->ReleasePrimitiveArrayCritical(_env, " + arr_name + "_arr, " + arr_name + "_arr_ptr, 0);")
596                 else:
597                     assert ty_info.java_fn_ty_arg.startswith("[")
598                     clz_var = ty_info.java_fn_ty_arg[1:].replace("[", "arr_of_")
599                     c_array_class_caches.add(clz_var)
600                     ret_conv = (ret_conv[0], ";\n" + ty_info.c_ty + " " + arr_name + "_arr = (*_env)->NewObjectArray(_env, " + arr_name + "_var." + arr_len + ", " + clz_var + "_clz, NULL);\n")
601                     ret_conv = (ret_conv[0], ret_conv[1] + "for (size_t " + idxc + " = 0; " + idxc + " < " + arr_name + "_var." + arr_len + "; " + idxc + "++) {\n")
602                     ret_conv = (ret_conv[0], ret_conv[1] + "\t" + subty.ret_conv[0].replace("\n", "\n\t"))
603                     ret_conv = (ret_conv[0], ret_conv[1] + arr_name + "_var." + ty_info.arr_access + "[" + idxc + "]" + subty.ret_conv[1].replace("\n", "\n\t"))
604                     ret_conv = (ret_conv[0], ret_conv[1] + "\n\t(*_env)->SetObjectArrayElement(_env, " + arr_name + "_arr, " + idxc + ", " + subty.ret_conv_name + ");\n")
605                     ret_conv = (ret_conv[0], ret_conv[1] + "}")
606                 if not holds_ref:
607                     if subty.rust_obj is not None and subty.rust_obj in opaque_structs:
608                         ret_conv = (ret_conv[0], ret_conv[1] + "\nFREE(" + arr_name + "_var." + ty_info.arr_access + ");")
609                     else:
610                         ret_conv = (ret_conv[0], ret_conv[1] + "\n" + ty_info.rust_obj.replace("LDK", "") + "_free(" + arr_name + "_var);")
611
612                 to_hu_conv = None
613                 to_hu_conv_name = None
614                 if subty.to_hu_conv is not None:
615                     to_hu_conv = ty_info.java_hu_ty + " " + conv_name + "_arr = new " + ty_info.subty.java_hu_ty.split("<")[0] + "[" + arr_name + ".length];\n"
616                     to_hu_conv = to_hu_conv + "for (int " + idxc + " = 0; " + idxc + " < " + arr_name + ".length; " + idxc + "++) {\n"
617                     to_hu_conv = to_hu_conv + "\t" + subty.java_ty + " " + conv_name + " = " + arr_name + "[" + idxc + "];\n"
618                     to_hu_conv = to_hu_conv + "\t" + subty.to_hu_conv.replace("\n", "\n\t") + "\n"
619                     to_hu_conv = to_hu_conv + "\t" + conv_name + "_arr[" + idxc + "] = " + subty.to_hu_conv_name + ";\n}"
620                     to_hu_conv_name = conv_name + "_arr"
621                 from_hu_conv = None
622                 if subty.from_hu_conv is not None:
623                     if subty.java_ty == "long" and subty.java_hu_ty != "long":
624                         from_hu_conv = ("Arrays.stream(" + arr_name + ").mapToLong(" + conv_name + " -> " + subty.from_hu_conv[0] + ").toArray()", "/* TODO 2 " + subty.java_hu_ty + "  */")
625                     elif subty.java_ty == "long":
626                         from_hu_conv = ("Arrays.stream(" + arr_name + ").map(" + conv_name + " -> " + subty.from_hu_conv[0] + ").toArray()", "/* TODO 2 " + subty.java_hu_ty + "  */")
627                     else:
628                         from_hu_conv = ("(" + ty_info.java_ty + ")Arrays.stream(" + arr_name + ").map(" + conv_name + " -> " + subty.from_hu_conv[0] + ").toArray()", "/* TODO 2 " + subty.java_hu_ty + "  */")
629
630                 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
631                     arg_conv = arg_conv, arg_conv_name = arg_conv_name, arg_conv_cleanup = arg_conv_cleanup,
632                     ret_conv = ret_conv, ret_conv_name = arr_name + "_arr", to_hu_conv = to_hu_conv, to_hu_conv_name = to_hu_conv_name, from_hu_conv = from_hu_conv)
633         elif ty_info.java_ty == "String":
634             if ty_info.arr_access is None:
635                 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
636                     arg_conv = None, arg_conv_name = None, arg_conv_cleanup = None,
637                     ret_conv = ("jstring " + ty_info.var_name + "_conv = (*_env)->NewStringUTF(_env, ", ");"), ret_conv_name = ty_info.var_name + "_conv",
638                     to_hu_conv = None, to_hu_conv_name = None, from_hu_conv = None)
639             else:
640                 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
641                     arg_conv = None, arg_conv_name = None, arg_conv_cleanup = None,
642                     ret_conv = ("LDKStr " + ty_info.var_name + "_str = ",
643                         ";\nchar* " + ty_info.var_name + "_buf = MALLOC(" + ty_info.var_name + "_str." + ty_info.arr_len + " + 1, \"str conv buf\");\n" +
644                         "memcpy(" + ty_info.var_name + "_buf, " + ty_info.var_name + "_str." + ty_info.arr_access + ", " + ty_info.var_name + "_str." + ty_info.arr_len + ");\n" +
645                         ty_info.var_name + "_buf[" + ty_info.var_name + "_str." + ty_info.arr_len + "] = 0;\n" +
646                         "jstring " + ty_info.var_name + "_conv = (*_env)->NewStringUTF(_env, " + ty_info.var_name + "_str." + ty_info.arr_access + ");\n" +
647                         "FREE(" + ty_info.var_name + "_buf);"),
648                     ret_conv_name = ty_info.var_name + "_conv", to_hu_conv = None, to_hu_conv_name = None, from_hu_conv = None)
649         elif ty_info.var_name == "" and not print_void:
650             # We don't have a parameter name, and want one, just call it arg
651             if ty_info.rust_obj is not None:
652                 assert(not is_free or ty_info.rust_obj not in opaque_structs)
653                 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
654                     arg_conv = ty_info.rust_obj + " arg_conv = *(" + ty_info.rust_obj + "*)arg;\nFREE((void*)arg);",
655                     arg_conv_name = "arg_conv", arg_conv_cleanup = None,
656                     ret_conv = None, ret_conv_name = None, to_hu_conv = "TODO 7", to_hu_conv_name = None, from_hu_conv = None)
657             else:
658                 assert(not is_free)
659                 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
660                     arg_conv = None, arg_conv_name = "arg", arg_conv_cleanup = None,
661                     ret_conv = None, ret_conv_name = None, to_hu_conv = "TODO 8", to_hu_conv_name = None, from_hu_conv = None)
662         elif ty_info.rust_obj is None:
663             return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
664                 arg_conv = None, arg_conv_name = ty_info.var_name, arg_conv_cleanup = None,
665                 ret_conv = None, ret_conv_name = None, to_hu_conv = None, to_hu_conv_name = None, from_hu_conv = None)
666         else:
667             if ty_info.var_name == "":
668                 ty_info.var_name = "ret"
669
670             if ty_info.rust_obj in opaque_structs:
671                 opaque_arg_conv = ty_info.rust_obj + " " + ty_info.var_name + "_conv;\n"
672                 opaque_arg_conv = opaque_arg_conv + ty_info.var_name + "_conv.inner = (void*)(" + ty_info.var_name + " & (~1));\n"
673                 if holds_ref:
674                     opaque_arg_conv = opaque_arg_conv + ty_info.var_name + "_conv.is_owned = false;"
675                 else:
676                     opaque_arg_conv = opaque_arg_conv + ty_info.var_name + "_conv.is_owned = (" + ty_info.var_name + " & 1) || (" + ty_info.var_name + " == 0);"
677                 if not ty_info.is_ptr and not is_free and not ty_info.pass_by_ref and not holds_ref:
678                     if (ty_info.java_hu_ty + "_clone") in clone_fns:
679                         # TODO: This is a bit too naive, even with the checks above, we really need to know if rust wants a ref or not, not just if its pass as a ptr.
680                         opaque_arg_conv = opaque_arg_conv + "\nif (" + ty_info.var_name + "_conv.inner != NULL)\n"
681                         opaque_arg_conv = opaque_arg_conv + "\t" + ty_info.var_name + "_conv = " + ty_info.java_hu_ty + "_clone(&" + ty_info.var_name + "_conv);"
682                     elif ty_info.passed_as_ptr:
683                         opaque_arg_conv = opaque_arg_conv + "\n// Warning: we may need a move here but can't clone!"
684
685                 opaque_ret_conv_suf = ";\n"
686                 if not holds_ref and ty_info.is_ptr and (ty_info.java_hu_ty + "_clone") in clone_fns: # is_ptr, not holds_ref implies passing a pointed-to value to java, which needs copied
687                     opaque_ret_conv_suf = opaque_ret_conv_suf + "if (" + ty_info.var_name + "->inner != NULL)\n"
688                     opaque_ret_conv_suf = opaque_ret_conv_suf + "\t" + ty_info.var_name + "_var = " + ty_info.java_hu_ty + "_clone(" + ty_info.var_name + ");\n"
689                 elif not holds_ref and ty_info.is_ptr:
690                     opaque_ret_conv_suf = opaque_ret_conv_suf + "// Warning: we may need a move here but can't clone!\n"
691
692                 opaque_ret_conv_suf = opaque_ret_conv_suf + "CHECK((((long)" + ty_info.var_name + "_var.inner) & 1) == 0); // We rely on a free low bit, malloc guarantees this.\n"
693                 opaque_ret_conv_suf = opaque_ret_conv_suf + "CHECK((((long)&" + ty_info.var_name + "_var) & 1) == 0); // We rely on a free low bit, pointer alignment guarantees this.\n"
694                 if holds_ref or ty_info.is_ptr:
695                     opaque_ret_conv_suf = opaque_ret_conv_suf + "long " + ty_info.var_name + "_ref = (long)" + ty_info.var_name + "_var.inner & ~1;"
696                 else:
697                     opaque_ret_conv_suf = opaque_ret_conv_suf + "long " + ty_info.var_name + "_ref = (long)" + ty_info.var_name + "_var.inner;\n"
698                     opaque_ret_conv_suf = opaque_ret_conv_suf + "if (" + ty_info.var_name + "_var.is_owned) {\n"
699                     opaque_ret_conv_suf = opaque_ret_conv_suf + "\t" + ty_info.var_name + "_ref |= 1;\n"
700                     opaque_ret_conv_suf = opaque_ret_conv_suf + "}"
701
702                 if ty_info.is_ptr:
703                     return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
704                         arg_conv = opaque_arg_conv, arg_conv_name = "&" + ty_info.var_name + "_conv", arg_conv_cleanup = None,
705                         ret_conv = (ty_info.rust_obj + " " + ty_info.var_name + "_var = *", opaque_ret_conv_suf),
706                         ret_conv_name = ty_info.var_name + "_ref",
707                         to_hu_conv = ty_info.java_hu_ty + " " + ty_info.var_name + "_hu_conv = new " + ty_info.java_hu_ty + "(null, " + ty_info.var_name + ");",
708                         to_hu_conv_name = ty_info.var_name + "_hu_conv",
709                         from_hu_conv = (ty_info.var_name + " == null ? 0 : " + ty_info.var_name + ".ptr & ~1", "this.ptrs_to.add(" + ty_info.var_name + ")"))
710                 else:
711                     return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
712                         arg_conv = opaque_arg_conv, arg_conv_name = ty_info.var_name + "_conv", arg_conv_cleanup = None,
713                         ret_conv = (ty_info.rust_obj + " " + ty_info.var_name + "_var = ", opaque_ret_conv_suf),
714                         ret_conv_name = ty_info.var_name + "_ref",
715                         to_hu_conv = ty_info.java_hu_ty + " " + ty_info.var_name + "_hu_conv = new " + ty_info.java_hu_ty + "(null, " + ty_info.var_name + ");",
716                         to_hu_conv_name = ty_info.var_name + "_hu_conv",
717                         from_hu_conv = (ty_info.var_name + " == null ? 0 : " + ty_info.var_name + ".ptr & ~1", "this.ptrs_to.add(" + ty_info.var_name + ")"))
718
719             if not ty_info.is_ptr:
720                 if ty_info.rust_obj in unitary_enums:
721                     return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
722                         arg_conv = ty_info.rust_obj + " " + ty_info.var_name + "_conv = " + ty_info.rust_obj + "_from_java(_env, " + ty_info.var_name + ");",
723                         arg_conv_name = ty_info.var_name + "_conv",
724                         arg_conv_cleanup = None,
725                         ret_conv = ("jclass " + ty_info.var_name + "_conv = " + ty_info.rust_obj + "_to_java(_env, ", ");"),
726                         ret_conv_name = ty_info.var_name + "_conv", to_hu_conv = None, to_hu_conv_name = None, from_hu_conv = None)
727                 base_conv = ty_info.rust_obj + " " + ty_info.var_name + "_conv = *(" + ty_info.rust_obj + "*)" + ty_info.var_name + ";";
728                 if ty_info.rust_obj in trait_structs:
729                     if not is_free:
730                         base_conv = base_conv + "\nif (" + ty_info.var_name + "_conv.free == " + ty_info.rust_obj + "_JCalls_free) {\n"
731                         base_conv = base_conv + "\t// If this_arg is a JCalls struct, then we need to increment the refcnt in it.\n"
732                         base_conv = base_conv + "\t" + ty_info.rust_obj + "_JCalls_clone(" + ty_info.var_name + "_conv.this_arg);\n}"
733                     else:
734                         base_conv = base_conv + "\n" + "FREE((void*)" + ty_info.var_name + ");"
735                     return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
736                         arg_conv = base_conv, arg_conv_name = ty_info.var_name + "_conv", arg_conv_cleanup = None,
737                         ret_conv = (ty_info.rust_obj + "* ret = MALLOC(sizeof(" + ty_info.rust_obj + "), \"" + ty_info.rust_obj + "\");\n*ret = ", ";"),
738                         ret_conv_name = "(long)ret",
739                         to_hu_conv = ty_info.java_hu_ty + " ret_hu_conv = new " + ty_info.java_hu_ty + "(null, ret);\nret_hu_conv.ptrs_to.add(this);",
740                         to_hu_conv_name = "ret_hu_conv",
741                         from_hu_conv = (ty_info.var_name + " == null ? 0 : " + ty_info.var_name + ".ptr", "this.ptrs_to.add(" + ty_info.var_name + ")"))
742                 if ty_info.rust_obj != "LDKu8slice" and ty_info.rust_obj != "LDKTransaction":
743                     # Don't bother free'ing slices passed in - Rust doesn't auto-free the
744                     # underlying unlike Vecs, and it gives Java more freedom.
745                     base_conv = base_conv + "\nFREE((void*)" + ty_info.var_name + ");";
746                 if ty_info.rust_obj in complex_enums:
747                     ret_conv = ("long " + ty_info.var_name + "_ref = (long)&", ";")
748                     if not holds_ref:
749                         ret_conv = (ty_info.rust_obj + " *" + ty_info.var_name + "_copy = MALLOC(sizeof(" + ty_info.rust_obj + "), \"" + ty_info.rust_obj + "\");\n", "")
750                         if not ty_info.passed_as_ptr:
751                             # We use passed_as_ptr as a flag to detect if we're copying a Vec.
752                             if (ty_info.java_hu_ty + "_clone") in clone_fns:
753                                 ret_conv = (ret_conv[0] + "*" + ty_info.var_name + "_copy = " + ty_info.java_hu_ty + "_clone(&", ");\n")
754                             else:
755                                 ret_conv = (ret_conv[0] + "*" + ty_info.var_name + "_copy = ", "; // XXX: We likely need to clone here, but no _clone fn is available!\n")
756                         else:
757                             ret_conv = (ret_conv[0] + "*" + ty_info.var_name + "_copy = ", ";\n")
758                         ret_conv = (ret_conv[0], ret_conv[1] + "long " + ty_info.var_name + "_ref = (long)" + ty_info.var_name + "_copy;")
759                     return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
760                         arg_conv = base_conv, arg_conv_name = ty_info.var_name + "_conv", arg_conv_cleanup = None,
761                         ret_conv = ret_conv, ret_conv_name = ty_info.var_name + "_ref",
762                         to_hu_conv = ty_info.java_hu_ty + " " + ty_info.var_name + "_hu_conv = " + ty_info.java_hu_ty + ".constr_from_ptr(" + ty_info.var_name + ");\n" + ty_info.var_name + "_hu_conv.ptrs_to.add(this);",
763                         to_hu_conv_name = ty_info.var_name + "_hu_conv", from_hu_conv = (ty_info.var_name + ".ptr", ""))
764                 if ty_info.rust_obj in result_types:
765                     assert not ty_info.is_ptr and not holds_ref # Otherwise we shouldn't be MALLOC'ing
766                     ret_conv = (ty_info.rust_obj + "* " + ty_info.var_name + "_conv = MALLOC(sizeof(" + ty_info.rust_obj + "), \"" + ty_info.rust_obj + "\");\n*" + ty_info.var_name + "_conv = ", ";")
767                     return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
768                         arg_conv = base_conv, arg_conv_name = ty_info.var_name + "_conv", arg_conv_cleanup = None,
769                         ret_conv = ret_conv, ret_conv_name = "(long)" + ty_info.var_name + "_conv",
770                         to_hu_conv = ty_info.java_hu_ty + " " + ty_info.var_name + "_hu_conv = " + ty_info.java_hu_ty + ".constr_from_ptr(" + ty_info.var_name + ");\n" + ty_info.var_name + "_hu_conv.ptrs_to.add(this);",
771                         to_hu_conv_name = ty_info.var_name + "_hu_conv", from_hu_conv = (ty_info.var_name + " != null ? " + ty_info.var_name + ".ptr : 0", ""))
772                 if ty_info.rust_obj in tuple_types:
773                     from_hu_conv = "bindings." + tuple_types[ty_info.rust_obj][1].replace("LDK", "") + "_new("
774                     to_hu_conv_pfx = ""
775                     to_hu_conv_sfx = ty_info.java_hu_ty + " " + ty_info.var_name + "_conv = new " + ty_info.java_hu_ty + "("
776                     for idx, conv in enumerate(tuple_types[ty_info.rust_obj][0]):
777                         if idx != 0:
778                             to_hu_conv_sfx = to_hu_conv_sfx + ", "
779                             from_hu_conv = from_hu_conv + ", "
780                         conv.var_name = ty_info.var_name + "_" + chr(idx + ord("a"))
781                         conv_map = map_type_with_info(conv, False, None, is_free, holds_ref)
782                         to_hu_conv_pfx = to_hu_conv_pfx + conv.java_ty + " " + ty_info.var_name + "_" + chr(idx + ord("a")) + " = " + "bindings." + tuple_types[ty_info.rust_obj][1] + "_get_" + chr(idx + ord("a")) + "(" + ty_info.var_name + ");\n"
783                         if conv_map.to_hu_conv is not None:
784                             to_hu_conv_pfx = to_hu_conv_pfx + conv_map.to_hu_conv + ";\n"
785                             to_hu_conv_sfx = to_hu_conv_sfx + conv_map.to_hu_conv_name
786                         else:
787                             to_hu_conv_sfx = to_hu_conv_sfx + ty_info.var_name + "_" + chr(idx + ord("a"))
788                         if conv_map.from_hu_conv is not None:
789                             from_hu_conv = from_hu_conv + conv_map.from_hu_conv[0].replace(ty_info.var_name + "_" + chr(idx + ord("a")), ty_info.var_name + "." + chr(idx + ord("a")))
790                             if conv_map.from_hu_conv[1] != "":
791                                 from_hu_conv = from_hu_conv + "/*XXX: " + conv_map.from_hu_conv[1] + "*/"
792                         else:
793                             from_hu_conv = from_hu_conv + ty_info.var_name + "." + chr(idx + ord("a"))
794
795                     if not ty_info.is_ptr and not holds_ref:
796                         return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
797                             arg_conv = base_conv, arg_conv_name = ty_info.var_name + "_conv", arg_conv_cleanup = None,
798
799                             ret_conv = (ty_info.rust_obj + "* " + ty_info.var_name + "_ref = MALLOC(sizeof(" + ty_info.rust_obj + "), \"" + ty_info.rust_obj + "\");\n*" + ty_info.var_name + "_ref = ", ";"),
800                             ret_conv_name = "(long)" + ty_info.var_name + "_ref",
801                             to_hu_conv = to_hu_conv_pfx + to_hu_conv_sfx + ");", to_hu_conv_name = ty_info.var_name + "_conv", from_hu_conv = (from_hu_conv + ")", ""))
802                     return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
803                         arg_conv = base_conv, arg_conv_name = ty_info.var_name + "_conv", arg_conv_cleanup = None,
804                         ret_conv = ("long " + ty_info.var_name + "_ref = (long)&", ";"), ret_conv_name = ty_info.var_name + "_ref",
805                         to_hu_conv = to_hu_conv_pfx + to_hu_conv_sfx + ");", to_hu_conv_name = ty_info.var_name + "_conv", from_hu_conv = (from_hu_conv + ")", ""))
806
807                 # The manually-defined types - TxOut and Transaction
808                 assert ty_info.rust_obj == "LDKTransaction" or ty_info.rust_obj == "LDKTxOut"
809                 if ty_info.rust_obj == "LDKTransaction":
810                     return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
811                         arg_conv = base_conv, arg_conv_name = ty_info.var_name + "_conv", arg_conv_cleanup = None,
812                         ret_conv = ("LDKTransaction *" + ty_info.var_name + "_copy = MALLOC(sizeof(LDKTransaction), \"LDKTransaction\");\n*" + ty_info.var_name + "_copy = ", ";\nlong " + ty_info.var_name + "_ref = (long)" + ty_info.var_name + "_copy;"),
813                         ret_conv_name = ty_info.var_name + "_ref",
814                         to_hu_conv = ty_info.java_hu_ty + " " + ty_info.var_name + "_conv = new " +ty_info.java_hu_ty + "(null, " + ty_info.var_name + ");",
815                         to_hu_conv_name = ty_info.var_name + "_conv", from_hu_conv = (ty_info.var_name + ".ptr", ""))
816                 elif ty_info.rust_obj == "LDKTxOut":
817                     return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
818                         arg_conv = base_conv, arg_conv_name = ty_info.var_name + "_conv", arg_conv_cleanup = None,
819                         ret_conv = ("long " + ty_info.var_name + "_ref = (long)&", ";"), ret_conv_name = ty_info.var_name + "_ref",
820                         to_hu_conv = ty_info.java_hu_ty + " " + ty_info.var_name + "_conv = new " +ty_info.java_hu_ty + "(null, " + ty_info.var_name + ");",
821                         to_hu_conv_name = ty_info.var_name + "_conv", from_hu_conv = (ty_info.var_name + ".ptr", ""))
822             elif ty_info.is_ptr:
823                 assert(not is_free)
824                 if ty_info.rust_obj in complex_enums:
825                     return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
826                         arg_conv = ty_info.rust_obj + "* " + ty_info.var_name + "_conv = (" + ty_info.rust_obj + "*)" + ty_info.var_name + ";",
827                         arg_conv_name = ty_info.var_name + "_conv", arg_conv_cleanup = None,
828                         ret_conv = ("long ret_" + ty_info.var_name + " = (long)", ";"), ret_conv_name = "ret_" + ty_info.var_name,
829                         to_hu_conv = ty_info.java_hu_ty + " " + ty_info.var_name + "_hu_conv = " + ty_info.java_hu_ty + ".constr_from_ptr(" + ty_info.var_name + ");",
830                         to_hu_conv_name = ty_info.var_name + "_hu_conv",
831                         from_hu_conv = (ty_info.var_name + " == null ? 0 : " + ty_info.var_name + ".ptr & ~1", "this.ptrs_to.add(" + ty_info.var_name + ")"))
832                 elif ty_info.rust_obj in trait_structs:
833                     return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
834                         arg_conv = ty_info.rust_obj + "* " + ty_info.var_name + "_conv = (" + ty_info.rust_obj + "*)" + ty_info.var_name + ";",
835                         arg_conv_name = ty_info.var_name + "_conv", arg_conv_cleanup = None,
836                         ret_conv = ("long ret_" + ty_info.var_name + " = (long)", ";"), ret_conv_name = "ret_" + ty_info.var_name,
837                         to_hu_conv = ty_info.java_hu_ty + " ret_hu_conv = new " + ty_info.java_hu_ty + "(null, ret);\nret_hu_conv.ptrs_to.add(this);",
838                         to_hu_conv_name = "ret_hu_conv",
839                         from_hu_conv = (ty_info.var_name + " == null ? 0 : " + ty_info.var_name + ".ptr", "this.ptrs_to.add(" + ty_info.var_name + ")"))
840                 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
841                     arg_conv = ty_info.rust_obj + "* " + ty_info.var_name + "_conv = (" + ty_info.rust_obj + "*)" + ty_info.var_name + ";",
842                     arg_conv_name = ty_info.var_name + "_conv", arg_conv_cleanup = None,
843                     ret_conv = ("long ret_" + ty_info.var_name + " = (long)", ";"), ret_conv_name = "ret_" + ty_info.var_name,
844                     to_hu_conv = "TODO 3", to_hu_conv_name = None, from_hu_conv = None) # its a pointer, no conv needed
845             assert False # We should have handled every case by now.
846
847     def map_fn(line, re_match, ret_arr_len, c_call_string):
848         out_java.write("\t// " + line)
849         out_java.write("\tpublic static native ")
850         write_c("JNIEXPORT ")
851
852         is_free = re_match.group(2).endswith("_free")
853         struct_meth = re_match.group(2).split("_")[0]
854
855         ret_info = map_type(re_match.group(1), True, ret_arr_len, False, False)
856         ret_info.print_ty()
857
858         if ret_info.ret_conv is not None:
859             ret_conv_pfx, ret_conv_sfx = ret_info.ret_conv
860
861         out_java.write(" " + re_match.group(2) + "(")
862         write_c(" JNICALL Java_org_ldk_impl_bindings_" + re_match.group(2).replace('_', '_1') + "(JNIEnv * _env, jclass _b")
863
864         arg_names = []
865         default_constructor_args = {}
866         takes_self = False
867         args_known = not ret_info.passed_as_ptr or ret_info.rust_obj in opaque_structs or ret_info.rust_obj in trait_structs or ret_info.rust_obj in complex_enums or ret_info.rust_obj in result_types
868         for idx, arg in enumerate(re_match.group(3).split(',')):
869             if idx != 0:
870                 out_java.write(", ")
871             if arg != "void":
872                 write_c(", ")
873             arg_conv_info = map_type(arg, False, None, is_free, False)
874             if arg_conv_info.c_ty != "void":
875                 arg_conv_info.print_ty()
876                 arg_conv_info.print_name()
877             if arg_conv_info.arg_name == "this_ptr" or arg_conv_info.arg_name == "this_arg":
878                 takes_self = True
879             if arg_conv_info.arg_conv is not None and "Warning" in arg_conv_info.arg_conv:
880                 if arg_conv_info.rust_obj in constructor_fns:
881                     assert not is_free
882                     for explode_arg in constructor_fns[arg_conv_info.rust_obj].split(','):
883                         explode_arg_conv = map_type(explode_arg, False, None, False, False)
884                         if explode_arg_conv.c_ty == "void":
885                             # We actually want to handle this case, but for now its only used in NetGraphMsgHandler::new()
886                             # which ends up resulting in a redundant constructor - both without arguments for the NetworkGraph.
887                             args_known = False
888                         assert explode_arg_conv.arg_name != "this_ptr"
889                         assert explode_arg_conv.arg_name != "this_arg"
890                         if explode_arg_conv.passed_as_ptr and not explode_arg_conv.rust_obj in trait_structs:
891                             args_known = False
892                         if not arg_conv_info.arg_name in default_constructor_args:
893                             default_constructor_args[arg_conv_info.arg_name] = []
894                         default_constructor_args[arg_conv_info.arg_name].append(explode_arg_conv)
895                 else:
896                     args_known = False
897             arg_names.append(arg_conv_info)
898
899         out_java_struct = None
900         if ("LDK" + struct_meth in opaque_structs or "LDK" + struct_meth in trait_structs) and not is_free:
901             out_java_struct = open(sys.argv[3] + "/structs/" + struct_meth + ".java", "a")
902             if not args_known:
903                 out_java_struct.write("\t// Skipped " + re_match.group(2) + "\n")
904                 out_java_struct.close()
905                 out_java_struct = None
906             else:
907                 meth_n = re_match.group(2)[len(struct_meth) + 1:]
908                 if ret_info.rust_obj == "LDK" + struct_meth:
909                     out_java_struct.write("\tpublic static " + ret_info.java_hu_ty + " constructor_" + meth_n + "(")
910                 else:
911                     out_java_struct.write("\tpublic " + ret_info.java_hu_ty + " " + meth_n + "(")
912                 for idx, arg in enumerate(arg_names):
913                     if idx != 0:
914                         if not takes_self or idx > 1:
915                             out_java_struct.write(", ")
916                     if arg.java_ty != "void" and arg.arg_name != "this_ptr" and arg.arg_name != "this_arg":
917                         if arg.arg_name in default_constructor_args:
918                             for explode_idx, explode_arg in enumerate(default_constructor_args[arg.arg_name]):
919                                 if explode_idx != 0:
920                                     out_java_struct.write(", ")
921                                 assert explode_arg.rust_obj in opaque_structs or explode_arg.rust_obj in trait_structs
922                                 out_java_struct.write(explode_arg.java_hu_ty + " " + arg.arg_name + "_" + explode_arg.arg_name)
923                         else:
924                             out_java_struct.write(arg.java_hu_ty + " " + arg.arg_name)
925
926
927         out_java.write(");\n")
928         write_c(") {\n")
929         if out_java_struct is not None:
930             out_java_struct.write(") {\n")
931
932         for info in arg_names:
933             if info.arg_conv is not None:
934                 write_c("\t" + info.arg_conv.replace('\n', "\n\t") + "\n")
935
936         if ret_info.ret_conv is not None:
937             write_c("\t" + ret_conv_pfx.replace('\n', '\n\t'))
938         elif ret_info.c_ty != "void":
939             write_c("\t" + ret_info.c_ty + " ret_val = ")
940         else:
941             write_c("\t")
942
943         if c_call_string is None:
944             write_c(re_match.group(2) + "(")
945         else:
946             write_c(c_call_string)
947         for idx, info in enumerate(arg_names):
948             if info.arg_conv_name is not None:
949                 if idx != 0:
950                     write_c(", ")
951                 elif c_call_string is not None:
952                     continue
953                 write_c(info.arg_conv_name)
954         write_c(")")
955         if ret_info.ret_conv is not None:
956             write_c(ret_conv_sfx.replace('\n', '\n\t'))
957         else:
958             write_c(";")
959         for info in arg_names:
960             if info.arg_conv_cleanup is not None:
961                 write_c("\n\t" + info.arg_conv_cleanup.replace("\n", "\n\t"))
962         if ret_info.ret_conv is not None:
963             write_c("\n\treturn " + ret_info.ret_conv_name + ";")
964         elif ret_info.c_ty != "void":
965             write_c("\n\treturn ret_val;")
966         write_c("\n}\n\n")
967         if out_java_struct is not None:
968             out_java_struct.write("\t\t")
969             if ret_info.java_ty != "void":
970                 out_java_struct.write(ret_info.java_ty + " ret = ")
971             out_java_struct.write("bindings." + re_match.group(2) + "(")
972             for idx, info in enumerate(arg_names):
973                 if idx != 0:
974                     out_java_struct.write(", ")
975                 if info.arg_name == "this_ptr" or info.arg_name == "this_arg":
976                     out_java_struct.write("this.ptr")
977                 elif info.arg_name in default_constructor_args:
978                     out_java_struct.write("bindings." + info.java_hu_ty + "_new(")
979                     for explode_idx, explode_arg in enumerate(default_constructor_args[info.arg_name]):
980                         if explode_idx != 0:
981                             out_java_struct.write(", ")
982                         expl_arg_name = info.arg_name + "_" + explode_arg.arg_name
983                         out_java_struct.write(explode_arg.from_hu_conv[0].replace(explode_arg.arg_name, expl_arg_name))
984                     out_java_struct.write(")")
985                 elif info.from_hu_conv is not None:
986                     out_java_struct.write(info.from_hu_conv[0])
987                 else:
988                     out_java_struct.write(info.arg_name)
989             out_java_struct.write(");\n")
990             if ret_info.to_hu_conv is not None:
991                 out_java_struct.write("\t\t" + ret_info.to_hu_conv.replace("\n", "\n\t\t") + "\n")
992
993             for info in arg_names:
994                 if info.arg_name == "this_ptr" or info.arg_name == "this_arg":
995                     pass
996                 elif info.arg_name in default_constructor_args:
997                     for explode_arg in default_constructor_args[info.arg_name]:
998                         expl_arg_name = info.arg_name + "_" + explode_arg.arg_name
999                         out_java_struct.write("\t\t" + explode_arg.from_hu_conv[1].replace(explode_arg.arg_name, expl_arg_name).replace("this", ret_info.to_hu_conv_name) + ";\n")
1000                 elif info.from_hu_conv is not None and info.from_hu_conv[1] != "":
1001                     if ret_info.rust_obj == "LDK" + struct_meth and ret_info.to_hu_conv_name is not None:
1002                         out_java_struct.write("\t\t" + info.from_hu_conv[1].replace("this", ret_info.to_hu_conv_name) + ";\n")
1003                     else:
1004                         out_java_struct.write("\t\t" + info.from_hu_conv[1] + ";\n")
1005
1006             if ret_info.to_hu_conv_name is not None:
1007                 out_java_struct.write("\t\treturn " + ret_info.to_hu_conv_name + ";\n")
1008             elif ret_info.java_ty != "void" and ret_info.rust_obj != "LDK" + struct_meth:
1009                 out_java_struct.write("\t\treturn ret;\n")
1010             out_java_struct.write("\t}\n\n")
1011             out_java_struct.close()
1012
1013     def map_unitary_enum(struct_name, field_lines):
1014         with open(sys.argv[3] + "/enums/" + struct_name + ".java", "w") as out_java_enum:
1015             out_java_enum.write("package org.ldk.enums;\n\n")
1016             unitary_enums.add(struct_name)
1017             write_c("static inline " + struct_name + " " + struct_name + "_from_java(JNIEnv *env, jclass val) {\n")
1018             write_c("\tswitch ((*env)->CallIntMethod(env, val, ordinal_meth)) {\n")
1019             ord_v = 0
1020             for idx, struct_line in enumerate(field_lines):
1021                 if idx == 0:
1022                     out_java_enum.write("public enum " + struct_name + " {\n")
1023                 elif idx == len(field_lines) - 3:
1024                     assert(struct_line.endswith("_Sentinel,"))
1025                 elif idx == len(field_lines) - 2:
1026                     out_java_enum.write("\t; static native void init();\n")
1027                     out_java_enum.write("\tstatic { init(); }\n")
1028                     out_java_enum.write("}")
1029                     out_java.write("\tstatic { " + struct_name + ".values(); /* Force enum statics to run */ }\n")
1030                 elif idx == len(field_lines) - 1:
1031                     assert(struct_line == "")
1032                 else:
1033                     out_java_enum.write(struct_line + "\n")
1034                     write_c("\t\tcase %d: return %s;\n" % (ord_v, struct_line.strip().strip(",")))
1035                     ord_v = ord_v + 1
1036             write_c("\t}\n")
1037             write_c("\tabort();\n")
1038             write_c("}\n")
1039
1040             ord_v = 0
1041             write_c("static jclass " + struct_name + "_class = NULL;\n")
1042             for idx, struct_line in enumerate(field_lines):
1043                 if idx > 0 and idx < len(field_lines) - 3:
1044                     variant = struct_line.strip().strip(",")
1045                     write_c("static jfieldID " + struct_name + "_" + variant + " = NULL;\n")
1046             write_c("JNIEXPORT void JNICALL Java_org_ldk_enums_" + struct_name.replace("_", "_1") + "_init (JNIEnv * env, jclass clz) {\n")
1047             write_c("\t" + struct_name + "_class = (*env)->NewGlobalRef(env, clz);\n")
1048             write_c("\tCHECK(" + struct_name + "_class != NULL);\n")
1049             for idx, struct_line in enumerate(field_lines):
1050                 if idx > 0 and idx < len(field_lines) - 3:
1051                     variant = struct_line.strip().strip(",")
1052                     write_c("\t" + struct_name + "_" + variant + " = (*env)->GetStaticFieldID(env, " + struct_name + "_class, \"" + variant + "\", \"Lorg/ldk/enums/" + struct_name + ";\");\n")
1053                     write_c("\tCHECK(" + struct_name + "_" + variant + " != NULL);\n")
1054             write_c("}\n")
1055             write_c("static inline jclass " + struct_name + "_to_java(JNIEnv *env, " + struct_name + " val) {\n")
1056             write_c("\tswitch (val) {\n")
1057             for idx, struct_line in enumerate(field_lines):
1058                 if idx > 0 and idx < len(field_lines) - 3:
1059                     variant = struct_line.strip().strip(",")
1060                     write_c("\t\tcase " + variant + ":\n")
1061                     write_c("\t\t\treturn (*env)->GetStaticObjectField(env, " + struct_name + "_class, " + struct_name + "_" + variant + ");\n")
1062                     ord_v = ord_v + 1
1063             write_c("\t\tdefault: abort();\n")
1064             write_c("\t}\n")
1065             write_c("}\n\n")
1066
1067     def map_complex_enum(struct_name, union_enum_items):
1068         java_hu_type = struct_name.replace("LDK", "")
1069         complex_enums.add(struct_name)
1070         with open(sys.argv[3] + "/structs/" + java_hu_type + ".java", "w") as out_java_enum:
1071             out_java_enum.write(hu_struct_file_prefix)
1072             out_java_enum.write("public class " + java_hu_type + " extends CommonBase {\n")
1073             out_java_enum.write("\tprivate " + java_hu_type + "(Object _dummy, long ptr) { super(ptr); }\n")
1074             out_java_enum.write("\t@Override @SuppressWarnings(\"deprecation\")\n")
1075             out_java_enum.write("\tprotected void finalize() throws Throwable {\n")
1076             out_java_enum.write("\t\tsuper.finalize();\n")
1077             out_java_enum.write("\t\tif (ptr != 0) { bindings." + java_hu_type + "_free(ptr); }\n")
1078             out_java_enum.write("\t}\n")
1079             out_java_enum.write("\tstatic " + java_hu_type + " constr_from_ptr(long ptr) {\n")
1080             out_java_enum.write("\t\tbindings." + struct_name + " raw_val = bindings." + struct_name + "_ref_from_ptr(ptr);\n")
1081             java_hu_subclasses = ""
1082
1083             tag_field_lines = union_enum_items["field_lines"]
1084             init_meth_jty_strs = {}
1085             for idx, struct_line in enumerate(tag_field_lines):
1086                 if idx == 0:
1087                     out_java.write("\tpublic static class " + struct_name + " {\n")
1088                     out_java.write("\t\tprivate " + struct_name + "() {}\n")
1089                 elif idx == len(tag_field_lines) - 3:
1090                     assert(struct_line.endswith("_Sentinel,"))
1091                 elif idx == len(tag_field_lines) - 2:
1092                     out_java.write("\t\tstatic native void init();\n")
1093                     out_java.write("\t}\n")
1094                 elif idx == len(tag_field_lines) - 1:
1095                     assert(struct_line == "")
1096                 else:
1097                     var_name = struct_line.strip(' ,')[len(struct_name) + 1:]
1098                     out_java.write("\t\tpublic final static class " + var_name + " extends " + struct_name + " {\n")
1099                     java_hu_subclasses = java_hu_subclasses + "\tpublic final static class " + var_name + " extends " + java_hu_type + " {\n"
1100                     out_java_enum.write("\t\tif (raw_val.getClass() == bindings." + struct_name + "." + var_name + ".class) {\n")
1101                     out_java_enum.write("\t\t\treturn new " + var_name + "(ptr, (bindings." + struct_name + "." + var_name + ")raw_val);\n")
1102                     write_c("static jclass " + struct_name + "_" + var_name + "_class = NULL;\n")
1103                     write_c("static jmethodID " + struct_name + "_" + var_name + "_meth = NULL;\n")
1104                     init_meth_jty_str = ""
1105                     init_meth_params = ""
1106                     init_meth_body = ""
1107                     hu_conv_body = ""
1108                     if "LDK" + var_name in union_enum_items:
1109                         enum_var_lines = union_enum_items["LDK" + var_name]
1110                         for idx, field in enumerate(enum_var_lines):
1111                             if idx != 0 and idx < len(enum_var_lines) - 2:
1112                                 field_ty = map_type(field.strip(' ;'), False, None, False, True)
1113                                 out_java.write("\t\t\tpublic " + field_ty.java_ty + " " + field_ty.arg_name + ";\n")
1114                                 java_hu_subclasses = java_hu_subclasses + "\t\tpublic final " + field_ty.java_hu_ty + " " + field_ty.arg_name + ";\n"
1115                                 if field_ty.to_hu_conv is not None:
1116                                     hu_conv_body = hu_conv_body + "\t\t\t" + field_ty.java_ty + " " + field_ty.arg_name + " = obj." + field_ty.arg_name + ";\n"
1117                                     hu_conv_body = hu_conv_body + "\t\t\t" + field_ty.to_hu_conv.replace("\n", "\n\t\t\t") + "\n"
1118                                     hu_conv_body = hu_conv_body + "\t\t\tthis." + field_ty.arg_name + " = " + field_ty.to_hu_conv_name + ";\n"
1119                                 else:
1120                                     hu_conv_body = hu_conv_body + "\t\t\tthis." + field_ty.arg_name + " = obj." + field_ty.arg_name + ";\n"
1121                                 init_meth_jty_str = init_meth_jty_str + field_ty.java_fn_ty_arg
1122                                 if idx > 1:
1123                                     init_meth_params = init_meth_params + ", "
1124                                 init_meth_params = init_meth_params + field_ty.java_ty + " " + field_ty.arg_name
1125                                 init_meth_body = init_meth_body + "this." + field_ty.arg_name + " = " + field_ty.arg_name + "; "
1126                         out_java.write("\t\t\t" + var_name + "(" + init_meth_params + ") { ")
1127                         out_java.write(init_meth_body)
1128                         out_java.write("}\n")
1129                     out_java.write("\t\t}\n")
1130                     out_java_enum.write("\t\t}\n")
1131                     java_hu_subclasses = java_hu_subclasses + "\t\tprivate " + var_name + "(long ptr, bindings." + struct_name + "." + var_name + " obj) {\n\t\t\tsuper(null, ptr);\n"
1132                     java_hu_subclasses = java_hu_subclasses + hu_conv_body
1133                     java_hu_subclasses = java_hu_subclasses + "\t\t}\n\t}\n"
1134                     init_meth_jty_strs[var_name] = init_meth_jty_str
1135             out_java_enum.write("\t\tassert false; return null; // Unreachable without extending the (internal) bindings interface\n\t}\n\n")
1136             out_java_enum.write(java_hu_subclasses)
1137             out_java.write("\tstatic { " + struct_name + ".init(); }\n")
1138             out_java.write("\tpublic static native " + struct_name + " " + struct_name + "_ref_from_ptr(long ptr);\n");
1139
1140             write_c("JNIEXPORT void JNICALL Java_org_ldk_impl_bindings_00024" + struct_name.replace("_", "_1") + "_init (JNIEnv * env, jclass _a) {\n")
1141             for idx, struct_line in enumerate(tag_field_lines):
1142                 if idx != 0 and idx < len(tag_field_lines) - 3:
1143                     var_name = struct_line.strip(' ,')[len(struct_name) + 1:]
1144                     write_c("\t" + struct_name + "_" + var_name + "_class =\n")
1145                     write_c("\t\t(*env)->NewGlobalRef(env, (*env)->FindClass(env, \"Lorg/ldk/impl/bindings$" + struct_name + "$" + var_name + ";\"));\n")
1146                     write_c("\tCHECK(" + struct_name + "_" + var_name + "_class != NULL);\n")
1147                     write_c("\t" + struct_name + "_" + var_name + "_meth = (*env)->GetMethodID(env, " + struct_name + "_" + var_name + "_class, \"<init>\", \"(" + init_meth_jty_strs[var_name] + ")V\");\n")
1148                     write_c("\tCHECK(" + struct_name + "_" + var_name + "_meth != NULL);\n")
1149             write_c("}\n")
1150             write_c("JNIEXPORT jobject JNICALL Java_org_ldk_impl_bindings_" + struct_name.replace("_", "_1") + "_1ref_1from_1ptr (JNIEnv * _env, jclass _c, jlong ptr) {\n")
1151             write_c("\t" + struct_name + " *obj = (" + struct_name + "*)ptr;\n")
1152             write_c("\tswitch(obj->tag) {\n")
1153             for idx, struct_line in enumerate(tag_field_lines):
1154                 if idx != 0 and idx < len(tag_field_lines) - 3:
1155                     var_name = struct_line.strip(' ,')[len(struct_name) + 1:]
1156                     write_c("\t\tcase " + struct_name + "_" + var_name + ": {\n")
1157                     c_params_text = ""
1158                     if "LDK" + var_name in union_enum_items:
1159                         enum_var_lines = union_enum_items["LDK" + var_name]
1160                         for idx, field in enumerate(enum_var_lines):
1161                             if idx != 0 and idx < len(enum_var_lines) - 2:
1162                                 field_map = map_type(field.strip(' ;'), False, None, False, True)
1163                                 if field_map.ret_conv is not None:
1164                                     write_c("\t\t\t" + field_map.ret_conv[0].replace("\n", "\n\t\t\t"))
1165                                     write_c("obj->" + camel_to_snake(var_name) + "." + field_map.arg_name)
1166                                     write_c(field_map.ret_conv[1].replace("\n", "\n\t\t\t") + "\n")
1167                                     c_params_text = c_params_text + ", " + field_map.ret_conv_name
1168                                 else:
1169                                     c_params_text = c_params_text + ", obj->" + camel_to_snake(var_name) + "." + field_map.arg_name
1170                     write_c("\t\t\treturn (*_env)->NewObject(_env, " + struct_name + "_" + var_name + "_class, " + struct_name + "_" + var_name + "_meth" + c_params_text + ");\n")
1171                     write_c("\t\t}\n")
1172             write_c("\t\tdefault: abort();\n")
1173             write_c("\t}\n}\n")
1174             out_java_enum.write("}\n")
1175
1176     def map_trait(struct_name, field_var_lines, trait_fn_lines):
1177         with open(sys.argv[3] + "/structs/" + struct_name.replace("LDK","") + ".java", "w") as out_java_trait:
1178             write_c("typedef struct " + struct_name + "_JCalls {\n")
1179             write_c("\tatomic_size_t refcnt;\n")
1180             write_c("\tJavaVM *vm;\n")
1181             write_c("\tjweak o;\n")
1182             field_var_convs = []
1183             for var_line in field_var_lines:
1184                 if var_line.group(1) in trait_structs:
1185                     write_c("\t" + var_line.group(1) + "_JCalls* " + var_line.group(2) + ";\n")
1186                     field_var_convs.append(None)
1187                 else:
1188                     field_var_convs.append(map_type(var_line.group(1) + " " + var_line.group(2), False, None, False, False))
1189             for fn_line in trait_fn_lines:
1190                 if fn_line.group(2) != "free" and fn_line.group(2) != "clone":
1191                     write_c("\tjmethodID " + fn_line.group(2) + "_meth;\n")
1192             write_c("} " + struct_name + "_JCalls;\n")
1193
1194             out_java_trait.write(hu_struct_file_prefix)
1195             out_java_trait.write("public class " + struct_name.replace("LDK","") + " extends CommonBase {\n")
1196             out_java_trait.write("\tfinal bindings." + struct_name + " bindings_instance;\n")
1197             out_java_trait.write("\t" + struct_name.replace("LDK", "") + "(Object _dummy, long ptr) { super(ptr); bindings_instance = null; }\n")
1198             out_java_trait.write("\tprivate " + struct_name.replace("LDK", "") + "(bindings." + struct_name + " arg")
1199             for idx, var_line in enumerate(field_var_lines):
1200                 if var_line.group(1) in trait_structs:
1201                     out_java_trait.write(", bindings." + var_line.group(1) + " " + var_line.group(2))
1202                 else:
1203                     out_java_trait.write(", " + field_var_convs[idx].java_hu_ty + " " + var_line.group(2))
1204             out_java_trait.write(") {\n")
1205             out_java_trait.write("\t\tsuper(bindings." + struct_name + "_new(arg")
1206             for idx, var_line in enumerate(field_var_lines):
1207                 if var_line.group(1) in trait_structs:
1208                     out_java_trait.write(", " + var_line.group(2))
1209                 elif field_var_convs[idx].from_hu_conv is not None:
1210                     out_java_trait.write(", " + field_var_convs[idx].from_hu_conv[0])
1211                 else:
1212                     out_java_trait.write(", " + var_line.group(2))
1213             out_java_trait.write("));\n")
1214             out_java_trait.write("\t\tthis.ptrs_to.add(arg);\n")
1215             for idx, var_line in enumerate(field_var_lines):
1216                 if var_line.group(1) in trait_structs:
1217                     out_java_trait.write("\t\tthis.ptrs_to.add(" + var_line.group(2) + ");\n")
1218                 elif field_var_convs[idx].from_hu_conv is not None and field_var_convs[idx].from_hu_conv[1] != "":
1219                     out_java_trait.write("\t\t" + field_var_convs[idx].from_hu_conv[1] + ";\n")
1220             out_java_trait.write("\t\tthis.bindings_instance = arg;\n")
1221             out_java_trait.write("\t}\n")
1222             out_java_trait.write("\t@Override @SuppressWarnings(\"deprecation\")\n")
1223             out_java_trait.write("\tprotected void finalize() throws Throwable {\n")
1224             out_java_trait.write("\t\tif (ptr != 0) { bindings." + struct_name.replace("LDK","") + "_free(ptr); } super.finalize();\n")
1225             out_java_trait.write("\t}\n\n")
1226
1227             java_trait_constr = "\tpublic " + struct_name.replace("LDK", "") + "(" + struct_name.replace("LDK", "") + "Interface arg"
1228             for idx, var_line in enumerate(field_var_lines):
1229                 if var_line.group(1) in trait_structs:
1230                     # Ideally we'd be able to take any instance of the interface, but our C code can only represent
1231                     # Java-implemented version, so we require users pass a Java implementation here :/
1232                     java_trait_constr = java_trait_constr + ", " + var_line.group(1).replace("LDK", "") + "." + var_line.group(1).replace("LDK", "") + "Interface " + var_line.group(2)
1233                 else:
1234                     java_trait_constr = java_trait_constr + ", " + field_var_convs[idx].java_hu_ty + " " + var_line.group(2)
1235             java_trait_constr = java_trait_constr + ") {\n\t\tthis(new bindings." + struct_name + "() {\n"
1236             out_java_trait.write("\tpublic static interface " + struct_name.replace("LDK", "") + "Interface {\n")
1237             out_java.write("\tpublic interface " + struct_name + " {\n")
1238             java_meths = []
1239             for fn_line in trait_fn_lines:
1240                 java_meth_descr = "("
1241                 if fn_line.group(2) != "free" and fn_line.group(2) != "clone":
1242                     ret_ty_info = map_type(fn_line.group(1), True, None, False, False)
1243
1244                     out_java.write("\t\t " + ret_ty_info.java_ty + " " + fn_line.group(2) + "(")
1245                     java_trait_constr = java_trait_constr + "\t\t\t@Override public " + ret_ty_info.java_ty + " " + fn_line.group(2) + "("
1246                     out_java_trait.write("\t\t" + ret_ty_info.java_hu_ty + " " + fn_line.group(2) + "(")
1247                     is_const = fn_line.group(3) is not None
1248                     write_c(fn_line.group(1) + fn_line.group(2) + "_jcall(")
1249                     if is_const:
1250                         write_c("const void* this_arg")
1251                     else:
1252                         write_c("void* this_arg")
1253
1254                     arg_names = []
1255                     for idx, arg in enumerate(fn_line.group(4).split(',')):
1256                         if arg == "":
1257                             continue
1258                         if idx >= 2:
1259                             out_java.write(", ")
1260                             java_trait_constr = java_trait_constr + ", "
1261                             out_java_trait.write(", ")
1262                         write_c(", ")
1263                         arg_conv_info = map_type(arg, True, None, False, False)
1264                         write_c(arg.strip())
1265                         out_java.write(arg_conv_info.java_ty + " " + arg_conv_info.arg_name)
1266                         out_java_trait.write(arg_conv_info.java_hu_ty + " " + arg_conv_info.arg_name)
1267                         java_trait_constr = java_trait_constr + arg_conv_info.java_ty + " " + arg_conv_info.arg_name
1268                         arg_names.append(arg_conv_info)
1269                         java_meth_descr = java_meth_descr + arg_conv_info.java_fn_ty_arg
1270                     java_meth_descr = java_meth_descr + ")" + ret_ty_info.java_fn_ty_arg
1271                     java_meths.append(java_meth_descr)
1272
1273                     out_java.write(");\n")
1274                     out_java_trait.write(");\n")
1275                     java_trait_constr = java_trait_constr + ") {\n"
1276                     write_c(") {\n")
1277                     write_c("\t" + struct_name + "_JCalls *j_calls = (" + struct_name + "_JCalls*) this_arg;\n")
1278                     write_c("\tJNIEnv *_env;\n")
1279                     write_c("\tDO_ASSERT((*j_calls->vm)->GetEnv(j_calls->vm, (void**)&_env, JNI_VERSION_1_8) == JNI_OK);\n")
1280
1281                     for arg_info in arg_names:
1282                         if arg_info.ret_conv is not None:
1283                             write_c("\t" + arg_info.ret_conv[0].replace('\n', '\n\t'));
1284                             write_c(arg_info.arg_name)
1285                             write_c(arg_info.ret_conv[1].replace('\n', '\n\t') + "\n")
1286                         if arg_info.to_hu_conv is not None:
1287                             java_trait_constr = java_trait_constr + "\t\t\t\t" + arg_info.to_hu_conv.replace("\n", "\n\t\t\t\t") + "\n"
1288
1289                     write_c("\tjobject obj = (*_env)->NewLocalRef(_env, j_calls->o);\n\tCHECK(obj != NULL);\n")
1290                     if ret_ty_info.c_ty.endswith("Array"):
1291                         write_c("\t" + ret_ty_info.c_ty + " arg = (*_env)->CallObjectMethod(_env, obj, j_calls->" + fn_line.group(2) + "_meth")
1292                     elif not ret_ty_info.passed_as_ptr:
1293                         write_c("\treturn (*_env)->Call" + ret_ty_info.java_ty.title() + "Method(_env, obj, j_calls->" + fn_line.group(2) + "_meth")
1294                     else:
1295                         write_c("\t" + fn_line.group(1).strip() + "* ret = (" + fn_line.group(1).strip() + "*)(*_env)->CallLongMethod(_env, obj, j_calls->" + fn_line.group(2) + "_meth");
1296                     if ret_ty_info.java_ty != "void":
1297                         java_trait_constr = java_trait_constr + "\t\t\t\t" + ret_ty_info.java_hu_ty + " ret = arg." + fn_line.group(2) + "("
1298                     else:
1299                         java_trait_constr = java_trait_constr + "\t\t\t\targ." + fn_line.group(2) + "("
1300
1301                     for idx, arg_info in enumerate(arg_names):
1302                         if arg_info.ret_conv is not None:
1303                             write_c(", " + arg_info.ret_conv_name)
1304                         else:
1305                             write_c(", " + arg_info.arg_name)
1306                         if idx != 0:
1307                             java_trait_constr = java_trait_constr + ", "
1308                         if arg_info.to_hu_conv_name is not None:
1309                             java_trait_constr = java_trait_constr + arg_info.to_hu_conv_name
1310                         else:
1311                             java_trait_constr = java_trait_constr + arg_info.arg_name
1312                     write_c(");\n");
1313                     if ret_ty_info.arg_conv is not None:
1314                         write_c("\t" + ret_ty_info.arg_conv.replace("\n", "\n\t") + "\n\treturn " + ret_ty_info.arg_conv_name + ";\n")
1315
1316                     write_c("}\n")
1317                     java_trait_constr = java_trait_constr + ");\n"
1318                     if ret_ty_info.java_ty != "void":
1319                         if ret_ty_info.from_hu_conv is not None:
1320                             java_trait_constr = java_trait_constr + "\t\t\t\t" + ret_ty_info.java_ty + " result = " + ret_ty_info.from_hu_conv[0] + ";\n"
1321                             if ret_ty_info.from_hu_conv[1] != "":
1322                                 java_trait_constr = java_trait_constr + "\t\t\t\t//TODO: May need to call: " + ret_ty_info.from_hu_conv[1] + ";\n"
1323                             if is_common_base_ext(ret_ty_info.rust_obj):
1324                                 java_trait_constr = java_trait_constr + "\t\t\t\tret.ptr = 0;\n"
1325                             java_trait_constr = java_trait_constr + "\t\t\t\treturn result;\n"
1326                         else:
1327                             java_trait_constr = java_trait_constr + "\t\t\t\treturn ret;\n"
1328                     java_trait_constr = java_trait_constr + "\t\t\t}\n"
1329                 elif fn_line.group(2) == "free":
1330                     write_c("static void " + struct_name + "_JCalls_free(void* this_arg) {\n")
1331                     write_c("\t" + struct_name + "_JCalls *j_calls = (" + struct_name + "_JCalls*) this_arg;\n")
1332                     write_c("\tif (atomic_fetch_sub_explicit(&j_calls->refcnt, 1, memory_order_acquire) == 1) {\n")
1333                     write_c("\t\tJNIEnv *env;\n")
1334                     write_c("\t\tDO_ASSERT((*j_calls->vm)->GetEnv(j_calls->vm, (void**)&env, JNI_VERSION_1_8) == JNI_OK);\n")
1335                     write_c("\t\t(*env)->DeleteWeakGlobalRef(env, j_calls->o);\n")
1336                     write_c("\t\tFREE(j_calls);\n")
1337                     write_c("\t}\n}\n")
1338             java_trait_constr = java_trait_constr + "\t\t}"
1339             for var_line in field_var_lines:
1340                 if var_line.group(1) in trait_structs:
1341                     java_trait_constr = java_trait_constr + ", new " + var_line.group(2) + "(" + var_line.group(2) + ").bindings_instance"
1342                 else:
1343                     java_trait_constr = java_trait_constr + ", " + var_line.group(2)
1344             out_java_trait.write("\t}\n")
1345             out_java_trait.write(java_trait_constr + ");\n\t}\n")
1346
1347             # Write out a clone function whether we need one or not, as we use them in moving to rust
1348             write_c("static void* " + struct_name + "_JCalls_clone(const void* this_arg) {\n")
1349             write_c("\t" + struct_name + "_JCalls *j_calls = (" + struct_name + "_JCalls*) this_arg;\n")
1350             write_c("\tatomic_fetch_add_explicit(&j_calls->refcnt, 1, memory_order_release);\n")
1351             for var_line in field_var_lines:
1352                 if var_line.group(1) in trait_structs:
1353                     write_c("\tatomic_fetch_add_explicit(&j_calls->" + var_line.group(2) + "->refcnt, 1, memory_order_release);\n")
1354             write_c("\treturn (void*) this_arg;\n")
1355             write_c("}\n")
1356
1357             out_java.write("\t}\n")
1358
1359             out_java.write("\tpublic static native long " + struct_name + "_new(" + struct_name + " impl")
1360             write_c("static inline " + struct_name + " " + struct_name + "_init (JNIEnv * env, jclass _a, jobject o")
1361             for idx, var_line in enumerate(field_var_lines):
1362                 if var_line.group(1) in trait_structs:
1363                     out_java.write(", " + var_line.group(1) + " " + var_line.group(2))
1364                     write_c(", jobject " + var_line.group(2))
1365                 else:
1366                     out_java.write(", " + field_var_convs[idx].java_ty + " " + var_line.group(2))
1367                     write_c(", " + field_var_convs[idx].c_ty + " " + var_line.group(2))
1368             out_java.write(");\n")
1369             write_c(") {\n")
1370
1371             write_c("\tjclass c = (*env)->GetObjectClass(env, o);\n")
1372             write_c("\tCHECK(c != NULL);\n")
1373             write_c("\t" + struct_name + "_JCalls *calls = MALLOC(sizeof(" + struct_name + "_JCalls), \"" + struct_name + "_JCalls\");\n")
1374             write_c("\tatomic_init(&calls->refcnt, 1);\n")
1375             write_c("\tDO_ASSERT((*env)->GetJavaVM(env, &calls->vm) == 0);\n")
1376             write_c("\tcalls->o = (*env)->NewWeakGlobalRef(env, o);\n")
1377             for (fn_line, java_meth_descr) in zip(trait_fn_lines, java_meths):
1378                 if fn_line.group(2) != "free" and fn_line.group(2) != "clone":
1379                     write_c("\tcalls->" + fn_line.group(2) + "_meth = (*env)->GetMethodID(env, c, \"" + fn_line.group(2) + "\", \"" + java_meth_descr + "\");\n")
1380                     write_c("\tCHECK(calls->" + fn_line.group(2) + "_meth != NULL);\n")
1381             for idx, var_line in enumerate(field_var_lines):
1382                 if field_var_convs[idx] is not None and field_var_convs[idx].arg_conv is not None:
1383                     write_c("\n\t" + field_var_convs[idx].arg_conv.replace("\n", "\n\t") +"\n")
1384             write_c("\n\t" + struct_name + " ret = {\n")
1385             write_c("\t\t.this_arg = (void*) calls,\n")
1386             for fn_line in trait_fn_lines:
1387                 if fn_line.group(2) != "free" and fn_line.group(2) != "clone":
1388                     write_c("\t\t." + fn_line.group(2) + " = " + fn_line.group(2) + "_jcall,\n")
1389                 elif fn_line.group(2) == "free":
1390                     write_c("\t\t.free = " + struct_name + "_JCalls_free,\n")
1391                 else:
1392                     clone_fns.add(struct_name + "_clone")
1393                     write_c("\t\t.clone = " + struct_name + "_JCalls_clone,\n")
1394             for idx, var_line in enumerate(field_var_lines):
1395                 if var_line.group(1) in trait_structs:
1396                     write_c("\t\t." + var_line.group(2) + " = " + var_line.group(1) + "_init(env, _a, " + var_line.group(2) + "),\n")
1397                 elif field_var_convs[idx].arg_conv_name is not None:
1398                     write_c("\t\t." + var_line.group(2) + " = " + field_var_convs[idx].arg_conv_name + ",\n")
1399                     write_c("\t\t.set_" + var_line.group(2) + " = NULL,\n")
1400                 else:
1401                     write_c("\t\t." + var_line.group(2) + " = " + var_line.group(2) + ",\n")
1402                     write_c("\t\t.set_" + var_line.group(2) + " = NULL,\n")
1403             write_c("\t};\n")
1404             for var_line in field_var_lines:
1405                 if var_line.group(1) in trait_structs:
1406                     write_c("\tcalls->" + var_line.group(2) + " = ret." + var_line.group(2) + ".this_arg;\n")
1407             write_c("\treturn ret;\n")
1408             write_c("}\n")
1409
1410             write_c("JNIEXPORT long JNICALL Java_org_ldk_impl_bindings_" + struct_name.replace("_", "_1") + "_1new (JNIEnv * env, jclass _a, jobject o")
1411             for idx, var_line in enumerate(field_var_lines):
1412                 if var_line.group(1) in trait_structs:
1413                     write_c(", jobject " + var_line.group(2))
1414                 else:
1415                     write_c(", " + field_var_convs[idx].c_ty + " " + var_line.group(2))
1416             write_c(") {\n")
1417             write_c("\t" + struct_name + " *res_ptr = MALLOC(sizeof(" + struct_name + "), \"" + struct_name + "\");\n")
1418             write_c("\t*res_ptr = " + struct_name + "_init(env, _a, o")
1419             for var_line in field_var_lines:
1420                 write_c(", " + var_line.group(2))
1421             write_c(");\n")
1422             write_c("\treturn (long)res_ptr;\n")
1423             write_c("}\n")
1424
1425             out_java.write("\tpublic static native " + struct_name + " " + struct_name + "_get_obj_from_jcalls(long val);\n")
1426             write_c("JNIEXPORT jobject JNICALL Java_org_ldk_impl_bindings_" + struct_name.replace("_", "_1") + "_1get_1obj_1from_1jcalls (JNIEnv * env, jclass _a, jlong val) {\n")
1427             write_c("\tjobject ret = (*env)->NewLocalRef(env, ((" + struct_name + "_JCalls*)val)->o);\n")
1428             write_c("\tCHECK(ret != NULL);\n")
1429             write_c("\treturn ret;\n")
1430             write_c("}\n")
1431
1432         for fn_line in trait_fn_lines:
1433             # For now, just disable enabling the _call_log - we don't know how to inverse-map String
1434             is_log = fn_line.group(2) == "log" and struct_name == "LDKLogger"
1435             if fn_line.group(2) != "free" and fn_line.group(2) != "clone" and fn_line.group(2) != "eq" and not is_log:
1436                 dummy_line = fn_line.group(1) + struct_name.replace("LDK", "") + "_" + fn_line.group(2) + " " + struct_name + "* this_arg" + fn_line.group(4) + "\n"
1437                 map_fn(dummy_line, re.compile("([A-Za-z_0-9]*) *([A-Za-z_0-9]*) *(.*)").match(dummy_line), None, "(this_arg_conv->" + fn_line.group(2) + ")(this_arg_conv->this_arg")
1438         for idx, var_line in enumerate(field_var_lines):
1439             if var_line.group(1) not in trait_structs:
1440                 write_c(var_line.group(1) + " " + struct_name + "_set_get_" + var_line.group(2) + "(" + struct_name + "* this_arg) {\n")
1441                 write_c("\tif (this_arg->set_" + var_line.group(2) + " != NULL)\n")
1442                 write_c("\t\tthis_arg->set_" + var_line.group(2) + "(this_arg);\n")
1443                 write_c("\treturn this_arg->" + var_line.group(2) + ";\n")
1444                 write_c("}\n")
1445                 dummy_line = var_line.group(1) + " " + struct_name.replace("LDK", "") + "_get_" + var_line.group(2) + " " + struct_name + "* this_arg" + fn_line.group(4) + "\n"
1446                 map_fn(dummy_line, re.compile("([A-Za-z_0-9]*) *([A-Za-z_0-9]*) *(.*)").match(dummy_line), None, struct_name + "_set_get_" + var_line.group(2) + "(this_arg_conv")
1447
1448     out_java.write("""package org.ldk.impl;
1449 import org.ldk.enums.*;
1450
1451 public class bindings {
1452         public static class VecOrSliceDef {
1453                 public long dataptr;
1454                 public long datalen;
1455                 public long stride;
1456                 public VecOrSliceDef(long dataptr, long datalen, long stride) {
1457                         this.dataptr = dataptr; this.datalen = datalen; this.stride = stride;
1458                 }
1459         }
1460         static {
1461                 System.loadLibrary(\"lightningjni\");
1462                 init(java.lang.Enum.class, VecOrSliceDef.class);
1463                 init_class_cache();
1464         }
1465         static native void init(java.lang.Class c, java.lang.Class slicedef);
1466         static native void init_class_cache();
1467
1468         public static native boolean deref_bool(long ptr);
1469         public static native long deref_long(long ptr);
1470         public static native void free_heap_ptr(long ptr);
1471         public static native byte[] read_bytes(long ptr, long len);
1472         public static native byte[] get_u8_slice_bytes(long slice_ptr);
1473         public static native long bytes_to_u8_vec(byte[] bytes);
1474         public static native long new_txpointer_copy_data(byte[] txdata);
1475         public static native void txpointer_free(long ptr);
1476         public static native byte[] txpointer_get_buffer(long ptr);
1477         public static native long vec_slice_len(long vec);
1478         public static native long new_empty_slice_vec();
1479
1480 """)
1481     write_c("""
1482 static jmethodID ordinal_meth = NULL;
1483 static jmethodID slicedef_meth = NULL;
1484 static jclass slicedef_cls = NULL;
1485 JNIEXPORT void Java_org_ldk_impl_bindings_init(JNIEnv * env, jclass _b, jclass enum_class, jclass slicedef_class) {
1486         ordinal_meth = (*env)->GetMethodID(env, enum_class, "ordinal", "()I");
1487         CHECK(ordinal_meth != NULL);
1488         slicedef_meth = (*env)->GetMethodID(env, slicedef_class, "<init>", "(JJJ)V");
1489         CHECK(slicedef_meth != NULL);
1490         slicedef_cls = (*env)->NewGlobalRef(env, slicedef_class);
1491         CHECK(slicedef_cls != NULL);
1492 }
1493
1494 JNIEXPORT jboolean JNICALL Java_org_ldk_impl_bindings_deref_1bool (JNIEnv * env, jclass _a, jlong ptr) {
1495         return *((bool*)ptr);
1496 }
1497 JNIEXPORT jlong JNICALL Java_org_ldk_impl_bindings_deref_1long (JNIEnv * env, jclass _a, jlong ptr) {
1498         return *((long*)ptr);
1499 }
1500 JNIEXPORT void JNICALL Java_org_ldk_impl_bindings_free_1heap_1ptr (JNIEnv * env, jclass _a, jlong ptr) {
1501         FREE((void*)ptr);
1502 }
1503 JNIEXPORT jbyteArray JNICALL Java_org_ldk_impl_bindings_read_1bytes (JNIEnv * _env, jclass _b, jlong ptr, jlong len) {
1504         jbyteArray ret_arr = (*_env)->NewByteArray(_env, len);
1505         (*_env)->SetByteArrayRegion(_env, ret_arr, 0, len, (unsigned char*)ptr);
1506         return ret_arr;
1507 }
1508 JNIEXPORT jbyteArray JNICALL Java_org_ldk_impl_bindings_get_1u8_1slice_1bytes (JNIEnv * _env, jclass _b, jlong slice_ptr) {
1509         LDKu8slice *slice = (LDKu8slice*)slice_ptr;
1510         jbyteArray ret_arr = (*_env)->NewByteArray(_env, slice->datalen);
1511         (*_env)->SetByteArrayRegion(_env, ret_arr, 0, slice->datalen, slice->data);
1512         return ret_arr;
1513 }
1514 JNIEXPORT long JNICALL Java_org_ldk_impl_bindings_bytes_1to_1u8_1vec (JNIEnv * _env, jclass _b, jbyteArray bytes) {
1515         LDKCVec_u8Z *vec = (LDKCVec_u8Z*)MALLOC(sizeof(LDKCVec_u8Z), "LDKCVec_u8");
1516         vec->datalen = (*_env)->GetArrayLength(_env, bytes);
1517         vec->data = (uint8_t*)MALLOC(vec->datalen, "LDKCVec_u8Z Bytes");
1518         (*_env)->GetByteArrayRegion (_env, bytes, 0, vec->datalen, vec->data);
1519         return (long)vec;
1520 }
1521 JNIEXPORT jbyteArray JNICALL Java_org_ldk_impl_bindings_txpointer_1get_1buffer (JNIEnv * env, jclass _b, jlong ptr) {
1522         LDKTransaction *txdata = (LDKTransaction*)ptr;
1523         LDKu8slice slice;
1524         slice.data = txdata->data;
1525         slice.datalen = txdata->datalen;
1526         return Java_org_ldk_impl_bindings_get_1u8_1slice_1bytes(env, _b, (long)&slice);
1527 }
1528 JNIEXPORT long JNICALL Java_org_ldk_impl_bindings_new_1txpointer_1copy_1data (JNIEnv * env, jclass _b, jbyteArray bytes) {
1529         LDKTransaction *txdata = (LDKTransaction*)MALLOC(sizeof(LDKTransaction), "LDKTransaction");
1530         txdata->datalen = (*env)->GetArrayLength(env, bytes);
1531         txdata->data = (uint8_t*)MALLOC(txdata->datalen, "Tx Data Bytes");
1532         txdata->data_is_owned = false;
1533         (*env)->GetByteArrayRegion (env, bytes, 0, txdata->datalen, txdata->data);
1534         return (long)txdata;
1535 }
1536 JNIEXPORT void JNICALL Java_org_ldk_impl_bindings_txpointer_1free (JNIEnv * env, jclass _b, jlong ptr) {
1537         LDKTransaction *tx = (LDKTransaction*)ptr;
1538         tx->data_is_owned = true;
1539         Transaction_free(*tx);
1540         FREE((void*)ptr);
1541 }
1542 JNIEXPORT jlong JNICALL Java_org_ldk_impl_bindings_vec_1slice_1len (JNIEnv * env, jclass _a, jlong ptr) {
1543         // Check offsets of a few Vec types are all consistent as we're meant to be generic across types
1544         _Static_assert(offsetof(LDKCVec_u8Z, datalen) == offsetof(LDKCVec_SignatureZ, datalen), "Vec<*> needs to be mapped identically");
1545         _Static_assert(offsetof(LDKCVec_u8Z, datalen) == offsetof(LDKCVec_MessageSendEventZ, datalen), "Vec<*> needs to be mapped identically");
1546         _Static_assert(offsetof(LDKCVec_u8Z, datalen) == offsetof(LDKCVec_EventZ, datalen), "Vec<*> needs to be mapped identically");
1547         _Static_assert(offsetof(LDKCVec_u8Z, datalen) == offsetof(LDKCVec_C2Tuple_usizeTransactionZZ, datalen), "Vec<*> needs to be mapped identically");
1548         LDKCVec_u8Z *vec = (LDKCVec_u8Z*)ptr;
1549         return (long)vec->datalen;
1550 }
1551 JNIEXPORT long JNICALL Java_org_ldk_impl_bindings_new_1empty_1slice_1vec (JNIEnv * _env, jclass _b) {
1552         // Check sizes of a few Vec types are all consistent as we're meant to be generic across types
1553         _Static_assert(sizeof(LDKCVec_u8Z) == sizeof(LDKCVec_SignatureZ), "Vec<*> needs to be mapped identically");
1554         _Static_assert(sizeof(LDKCVec_u8Z) == sizeof(LDKCVec_MessageSendEventZ), "Vec<*> needs to be mapped identically");
1555         _Static_assert(sizeof(LDKCVec_u8Z) == sizeof(LDKCVec_EventZ), "Vec<*> needs to be mapped identically");
1556         _Static_assert(sizeof(LDKCVec_u8Z) == sizeof(LDKCVec_C2Tuple_usizeTransactionZZ), "Vec<*> needs to be mapped identically");
1557         LDKCVec_u8Z *vec = (LDKCVec_u8Z*)MALLOC(sizeof(LDKCVec_u8Z), "Empty LDKCVec");
1558         vec->data = NULL;
1559         vec->datalen = 0;
1560         return (long)vec;
1561 }
1562
1563 // We assume that CVec_u8Z and u8slice are the same size and layout (and thus pointers to the two can be mixed)
1564 _Static_assert(sizeof(LDKCVec_u8Z) == sizeof(LDKu8slice), "Vec<u8> and [u8] need to have been mapped identically");
1565 _Static_assert(offsetof(LDKCVec_u8Z, data) == offsetof(LDKu8slice, data), "Vec<u8> and [u8] need to have been mapped identically");
1566 _Static_assert(offsetof(LDKCVec_u8Z, datalen) == offsetof(LDKu8slice, datalen), "Vec<u8> and [u8] need to have been mapped identically");
1567
1568 """)
1569
1570     with open(sys.argv[3] + "/structs/CommonBase.java", "a") as out_java_struct:
1571         out_java_struct.write("""package org.ldk.structs;
1572 import java.util.LinkedList;
1573 class CommonBase {
1574         long ptr;
1575         LinkedList<Object> ptrs_to = new LinkedList();
1576         protected CommonBase(long ptr) { this.ptr = ptr; }
1577         public long _test_only_get_ptr() { return this.ptr; }
1578 }
1579 """)
1580
1581     in_block_comment = False
1582     cur_block_obj = None
1583
1584     const_val_regex = re.compile("^extern const ([A-Za-z_0-9]*) ([A-Za-z_0-9]*);$")
1585
1586     line_indicates_result_regex = re.compile("^   (LDKCResultPtr_[A-Za-z_0-9]*) contents;$")
1587     line_indicates_vec_regex = re.compile("^   ([A-Za-z_0-9]*) \*data;$")
1588     line_indicates_opaque_regex = re.compile("^   bool is_owned;$")
1589     line_indicates_trait_regex = re.compile("^   ([A-Za-z_0-9]* \*?)\(\*([A-Za-z_0-9]*)\)\((const )?void \*this_arg(.*)\);$")
1590     assert(line_indicates_trait_regex.match("   uintptr_t (*send_data)(void *this_arg, LDKu8slice data, bool resume_read);"))
1591     assert(line_indicates_trait_regex.match("   LDKCVec_MessageSendEventZ (*get_and_clear_pending_msg_events)(const void *this_arg);"))
1592     assert(line_indicates_trait_regex.match("   void *(*clone)(const void *this_arg);"))
1593     line_field_var_regex = re.compile("^   ([A-Za-z_0-9]*) ([A-Za-z_0-9]*);$")
1594     assert(line_field_var_regex.match("   LDKMessageSendEventsProvider MessageSendEventsProvider;"))
1595     assert(line_field_var_regex.match("   LDKChannelPublicKeys pubkeys;"))
1596     struct_name_regex = re.compile("^typedef (struct|enum|union) (MUST_USE_STRUCT )?(LDK[A-Za-z_0-9]*) {$")
1597     assert(struct_name_regex.match("typedef struct LDKCVecTempl_u8 {"))
1598     assert(struct_name_regex.match("typedef enum LDKNetwork {"))
1599     struct_alias_regex = re.compile("^typedef (LDK[A-Za-z_0-9]*) (LDK[A-Za-z_0-9]*);$")
1600     assert(struct_alias_regex.match("typedef LDKCResultTempl_bool__PeerHandleError LDKCResult_boolPeerHandleErrorZ;"))
1601
1602     result_templ_structs = set()
1603     union_enum_items = {}
1604     result_ptr_struct_items = {}
1605     for line in in_h:
1606         if in_block_comment:
1607             if line.endswith("*/\n"):
1608                 in_block_comment = False
1609         elif cur_block_obj is not None:
1610             cur_block_obj  = cur_block_obj + line
1611             if line.startswith("} "):
1612                 field_lines = []
1613                 struct_name = None
1614                 vec_ty = None
1615                 obj_lines = cur_block_obj.split("\n")
1616                 is_opaque = False
1617                 result_contents = None
1618                 is_unitary_enum = False
1619                 is_union_enum = False
1620                 is_union = False
1621                 is_tuple = False
1622                 trait_fn_lines = []
1623                 field_var_lines = []
1624
1625                 for idx, struct_line in enumerate(obj_lines):
1626                     if struct_line.strip().startswith("/*"):
1627                         in_block_comment = True
1628                     if in_block_comment:
1629                         if struct_line.endswith("*/"):
1630                             in_block_comment = False
1631                     else:
1632                         struct_name_match = struct_name_regex.match(struct_line)
1633                         if struct_name_match is not None:
1634                             struct_name = struct_name_match.group(3)
1635                             if struct_name_match.group(1) == "enum":
1636                                 if not struct_name.endswith("_Tag"):
1637                                     is_unitary_enum = True
1638                                 else:
1639                                     is_union_enum = True
1640                             elif struct_name_match.group(1) == "union":
1641                                 is_union = True
1642                         if line_indicates_opaque_regex.match(struct_line):
1643                             is_opaque = True
1644                         result_match = line_indicates_result_regex.match(struct_line)
1645                         if result_match is not None:
1646                             result_contents = result_match.group(1)
1647                         vec_ty_match = line_indicates_vec_regex.match(struct_line)
1648                         if vec_ty_match is not None and struct_name.startswith("LDKCVecTempl_"):
1649                             vec_ty = vec_ty_match.group(1)
1650                         elif struct_name.startswith("LDKC2TupleTempl_") or struct_name.startswith("LDKC3TupleTempl_"):
1651                             is_tuple = True
1652                         trait_fn_match = line_indicates_trait_regex.match(struct_line)
1653                         if trait_fn_match is not None:
1654                             trait_fn_lines.append(trait_fn_match)
1655                         field_var_match = line_field_var_regex.match(struct_line)
1656                         if field_var_match is not None:
1657                             field_var_lines.append(field_var_match)
1658                         field_lines.append(struct_line)
1659
1660                 assert(struct_name is not None)
1661                 assert(len(trait_fn_lines) == 0 or not (is_opaque or is_unitary_enum or is_union_enum or is_union or result_contents is not None or vec_ty is not None))
1662                 assert(not is_opaque or not (len(trait_fn_lines) != 0 or is_unitary_enum or is_union_enum or is_union or result_contents is not None or vec_ty is not None))
1663                 assert(not is_unitary_enum or not (len(trait_fn_lines) != 0 or is_opaque or is_union_enum or is_union or result_contents is not None or vec_ty is not None))
1664                 assert(not is_union_enum or not (len(trait_fn_lines) != 0 or is_unitary_enum or is_opaque or is_union or result_contents is not None or vec_ty is not None))
1665                 assert(not is_union or not (len(trait_fn_lines) != 0 or is_unitary_enum or is_union_enum or is_opaque or result_contents is not None or vec_ty is not None))
1666                 assert(result_contents is None or not (len(trait_fn_lines) != 0 or is_unitary_enum or is_union_enum or is_opaque or is_union or vec_ty is not None))
1667                 assert(vec_ty is None or not (len(trait_fn_lines) != 0 or is_unitary_enum or is_union_enum or is_opaque or is_union or result_contents is not None))
1668
1669                 if is_opaque:
1670                     opaque_structs.add(struct_name)
1671                     with open(sys.argv[3] + "/structs/" + struct_name.replace("LDK","") + ".java", "w") as out_java_struct:
1672                         out_java_struct.write(hu_struct_file_prefix)
1673                         out_java_struct.write("public class " + struct_name.replace("LDK","") + " extends CommonBase")
1674                         if struct_name.startswith("LDKLocked"):
1675                             out_java_struct.write(" implements AutoCloseable")
1676                         out_java_struct.write(" {\n")
1677                         out_java_struct.write("\t" + struct_name.replace("LDK", "") + "(Object _dummy, long ptr) { super(ptr); }\n")
1678                         if struct_name.startswith("LDKLocked"):
1679                             out_java_struct.write("\t@Override public void close() {\n")
1680                         else:
1681                             out_java_struct.write("\t@Override @SuppressWarnings(\"deprecation\")\n")
1682                             out_java_struct.write("\tprotected void finalize() throws Throwable {\n")
1683                             out_java_struct.write("\t\tsuper.finalize();\n")
1684                         out_java_struct.write("\t\tif (ptr != 0) { bindings." + struct_name.replace("LDK","") + "_free(ptr); }\n")
1685                         out_java_struct.write("\t}\n\n")
1686                 elif result_contents is not None:
1687                     result_templ_structs.add(struct_name)
1688                     assert result_contents in result_ptr_struct_items
1689                 elif struct_name.startswith("LDKCResultPtr_"):
1690                     for line in field_lines:
1691                         if line.endswith("*result;"):
1692                             res_ty = line[:-8].strip()
1693                         elif line.endswith("*err;"):
1694                             err_ty = line[:-5].strip()
1695                     result_ptr_struct_items[struct_name] = (res_ty, err_ty)
1696                 elif is_tuple:
1697                     out_java.write("\tpublic static native long " + struct_name + "_new(")
1698                     write_c("JNIEXPORT jlong JNICALL Java_org_ldk_impl_bindings_" + struct_name.replace("_", "_1") + "_1new(JNIEnv *_env, jclass _b")
1699                     ty_list = []
1700                     for idx, line in enumerate(field_lines):
1701                         if idx != 0 and idx < len(field_lines) - 2:
1702                             ty_info = java_c_types(line.strip(';'), None)
1703                             if idx != 1:
1704                                 out_java.write(", ")
1705                             e = chr(ord('a') + idx - 1)
1706                             out_java.write(ty_info.java_ty + " " + e)
1707                             write_c(", " + ty_info.c_ty + " " + e)
1708                             ty_list.append(ty_info)
1709                     tuple_types[struct_name] = (ty_list, struct_name)
1710                     out_java.write(");\n")
1711                     write_c(") {\n")
1712                     write_c("\t" + struct_name + "* ret = MALLOC(sizeof(" + struct_name + "), \"" + struct_name + "\");\n")
1713                     for idx, line in enumerate(field_lines):
1714                         if idx != 0 and idx < len(field_lines) - 2:
1715                             ty_info = map_type(line.strip(';'), False, None, False, False)
1716                             e = chr(ord('a') + idx - 1)
1717                             if ty_info.arg_conv is not None:
1718                                 write_c("\t" + ty_info.arg_conv.replace("\n", "\n\t"))
1719                                 write_c("\n\tret->" + e + " = " + ty_info.arg_conv_name + ";\n")
1720                             else:
1721                                 write_c("\tret->" + e + " = " + e + ";\n")
1722                             if ty_info.arg_conv_cleanup is not None:
1723                                 write_c("\t//TODO: Really need to call " + ty_info.arg_conv_cleanup + " here\n")
1724                     write_c("\treturn (long)ret;\n")
1725                     write_c("}\n")
1726                 elif vec_ty is not None:
1727                     if vec_ty in opaque_structs:
1728                         out_java.write("\tpublic static native long[] " + struct_name + "_arr_info(long vec_ptr);\n")
1729                         write_c("JNIEXPORT jlongArray JNICALL Java_org_ldk_impl_bindings_" + struct_name.replace("_", "_1") + "_1arr_1info(JNIEnv *env, jclass _b, jlong ptr) {\n")
1730                     else:
1731                         out_java.write("\tpublic static native VecOrSliceDef " + struct_name + "_arr_info(long vec_ptr);\n")
1732                         write_c("JNIEXPORT jobject JNICALL Java_org_ldk_impl_bindings_" + struct_name.replace("_", "_1") + "_1arr_1info(JNIEnv *env, jclass _b, jlong ptr) {\n")
1733                     write_c("\t" + struct_name + " *vec = (" + struct_name + "*)ptr;\n")
1734                     if vec_ty in opaque_structs:
1735                         write_c("\tjlongArray ret = (*env)->NewLongArray(env, vec->datalen);\n")
1736                         write_c("\tjlong *ret_elems = (*env)->GetPrimitiveArrayCritical(env, ret, NULL);\n")
1737                         write_c("\tfor (size_t i = 0; i < vec->datalen; i++) {\n")
1738                         write_c("\t\tCHECK((((long)vec->data[i].inner) & 1) == 0);\n")
1739                         write_c("\t\tret_elems[i] = (long)vec->data[i].inner | (vec->data[i].is_owned ? 1 : 0);\n")
1740                         write_c("\t}\n")
1741                         write_c("\t(*env)->ReleasePrimitiveArrayCritical(env, ret, ret_elems, 0);\n")
1742                         write_c("\treturn ret;\n")
1743                     else:
1744                         write_c("\treturn (*env)->NewObject(env, slicedef_cls, slicedef_meth, (long)vec->data, (long)vec->datalen, sizeof(" + vec_ty + "));\n")
1745                     write_c("}\n")
1746
1747                     ty_info = map_type(vec_ty + " arr_elem", False, None, False, False)
1748                     if len(ty_info.java_fn_ty_arg) == 1: # ie we're a primitive of some form
1749                         out_java.write("\tpublic static native long " + struct_name + "_new(" + ty_info.java_ty + "[] elems);\n")
1750                         write_c("JNIEXPORT jlong JNICALL Java_org_ldk_impl_bindings_" + struct_name.replace("_", "_1") + "_1new(JNIEnv *env, jclass _b, j" + ty_info.java_ty + "Array elems){\n")
1751                         write_c("\t" + struct_name + " *ret = MALLOC(sizeof(" + struct_name + "), \"" + struct_name + "\");\n")
1752                         write_c("\tret->datalen = (*env)->GetArrayLength(env, elems);\n")
1753                         write_c("\tif (ret->datalen == 0) {\n")
1754                         write_c("\t\tret->data = NULL;\n")
1755                         write_c("\t} else {\n")
1756                         write_c("\t\tret->data = MALLOC(sizeof(" + vec_ty + ") * ret->datalen, \"" + struct_name + " Data\");\n")
1757                         write_c("\t\t" + ty_info.c_ty + " *java_elems = (*env)->GetPrimitiveArrayCritical(env, elems, NULL);\n")
1758                         write_c("\t\tfor (size_t i = 0; i < ret->datalen; i++) {\n")
1759                         if ty_info.arg_conv is not None:
1760                             write_c("\t\t\t" + ty_info.c_ty + " arr_elem = java_elems[i];\n")
1761                             write_c("\t\t\t" + ty_info.arg_conv.replace("\n", "\n\t\t\t") + "\n")
1762                             write_c("\t\t\tret->data[i] = " + ty_info.arg_conv_name + ";\n")
1763                             assert ty_info.arg_conv_cleanup is None
1764                         else:
1765                             write_c("\t\t\tret->data[i] = java_elems[i];\n")
1766                         write_c("\t\t}\n")
1767                         write_c("\t\t(*env)->ReleasePrimitiveArrayCritical(env, elems, java_elems, 0);\n")
1768                         write_c("\t}\n")
1769                         write_c("\treturn (long)ret;\n")
1770                         write_c("}\n")
1771                 elif is_union_enum:
1772                     assert(struct_name.endswith("_Tag"))
1773                     struct_name = struct_name[:-4]
1774                     union_enum_items[struct_name] = {"field_lines": field_lines}
1775                 elif struct_name.endswith("_Body") and struct_name.split("_")[0] in union_enum_items:
1776                     enum_var_name = struct_name.split("_")
1777                     union_enum_items[enum_var_name[0]][enum_var_name[1]] = field_lines
1778                 elif struct_name in union_enum_items:
1779                     map_complex_enum(struct_name, union_enum_items[struct_name])
1780                 elif is_unitary_enum:
1781                     map_unitary_enum(struct_name, field_lines)
1782                 elif len(trait_fn_lines) > 0:
1783                     trait_structs.add(struct_name)
1784                     map_trait(struct_name, field_var_lines, trait_fn_lines)
1785                 elif struct_name == "LDKTxOut":
1786                     with open(sys.argv[3] + "/structs/TxOut.java", "w") as out_java_struct:
1787                         out_java_struct.write(hu_struct_file_prefix)
1788                         out_java_struct.write("public class TxOut extends CommonBase{\n")
1789                         out_java_struct.write("\tTxOut(java.lang.Object _dummy, long ptr) { super(ptr); }\n")
1790                         out_java_struct.write("\tlong to_c_ptr() { return 0; }\n")
1791                         # TODO: TxOut body
1792                         out_java_struct.write("}")
1793                 elif struct_name == "LDKTransaction":
1794                     with open(sys.argv[3] + "/structs/Transaction.java", "w") as out_java_struct:
1795                         out_java_struct.write(hu_struct_file_prefix)
1796                         out_java_struct.write("public class Transaction extends CommonBase{\n")
1797                         out_java_struct.write("\tTransaction(java.lang.Object _dummy, long ptr) { super(ptr); }\n")
1798                         out_java_struct.write("\tpublic Transaction(byte[] data) { super(bindings.new_txpointer_copy_data(data)); }\n")
1799                         out_java_struct.write("\t@Override public void finalize() throws Throwable { super.finalize(); bindings.txpointer_free(ptr); }\n")
1800                         out_java_struct.write("\tpublic byte[] get_contents() { return bindings.txpointer_get_buffer(ptr); }\n")
1801                         # TODO: Transaction body
1802                         out_java_struct.write("}")
1803                 else:
1804                     pass # Everything remaining is a byte[] or some form
1805                 cur_block_obj = None
1806         else:
1807             fn_ptr = fn_ptr_regex.match(line)
1808             fn_ret_arr = fn_ret_arr_regex.match(line)
1809             reg_fn = reg_fn_regex.match(line)
1810             const_val = const_val_regex.match(line)
1811
1812             if line.startswith("#include <"):
1813                 pass
1814             elif line.startswith("/*"):
1815                 #out_java.write("\t" + line)
1816                 if not line.endswith("*/\n"):
1817                     in_block_comment = True
1818             elif line.startswith("typedef enum "):
1819                 cur_block_obj = line
1820             elif line.startswith("typedef struct "):
1821                 cur_block_obj = line
1822             elif line.startswith("typedef union "):
1823                 cur_block_obj = line
1824             elif line.startswith("typedef "):
1825                 alias_match =  struct_alias_regex.match(line)
1826                 if alias_match.group(1) in tuple_types:
1827                     tuple_types[alias_match.group(2)] = (tuple_types[alias_match.group(1)][0], alias_match.group(2))
1828                     tuple_types[alias_match.group(1)] = (tuple_types[alias_match.group(1)][0], alias_match.group(2))
1829                     for idx, ty_info in enumerate(tuple_types[alias_match.group(1)][0]):
1830                         e = chr(ord('a') + idx)
1831                         out_java.write("\tpublic static native " + ty_info.java_ty + " " + alias_match.group(2) + "_get_" + e + "(long ptr);\n")
1832                         write_c("JNIEXPORT " + ty_info.c_ty + " JNICALL Java_org_ldk_impl_bindings_" + alias_match.group(2).replace("_", "_1") + "_1get_1" + e + "(JNIEnv *_env, jclass _b, jlong ptr) {\n")
1833                         write_c("\t" + alias_match.group(1) + " *tuple = (" + alias_match.group(1) + "*)ptr;\n")
1834                         conv_info = map_type_with_info(ty_info, False, None, False, True)
1835                         if conv_info.ret_conv is not None:
1836                             write_c("\t" + conv_info.ret_conv[0].replace("\n", "\n\t") + "tuple->" + e + conv_info.ret_conv[1].replace("\n", "\n\t") + "\n")
1837                             write_c("\treturn " + conv_info.ret_conv_name + ";\n")
1838                         else:
1839                             write_c("\treturn tuple->" + e + ";\n")
1840                         write_c("}\n")
1841                 elif alias_match.group(1) in result_templ_structs:
1842                     result_types.add(alias_match.group(2))
1843                     human_ty = alias_match.group(2).replace("LDKCResult", "Result")
1844                     with open(sys.argv[3] + "/structs/" + human_ty + ".java", "w") as out_java_struct:
1845                         out_java_struct.write(hu_struct_file_prefix)
1846                         out_java_struct.write("public class " + human_ty + " extends CommonBase {\n")
1847                         out_java_struct.write("\tprivate " + human_ty + "(Object _dummy, long ptr) { super(ptr); }\n")
1848                         out_java_struct.write("\tprotected void finalize() throws Throwable {\n")
1849                         out_java_struct.write("\t\tif (ptr != 0) { bindings." + alias_match.group(2).replace("LDK","") + "_free(ptr); } super.finalize();\n")
1850                         out_java_struct.write("\t}\n\n")
1851                         out_java_struct.write("\tstatic " + human_ty + " constr_from_ptr(long ptr) {\n")
1852                         out_java_struct.write("\t\tif (bindings." + alias_match.group(2) + "_result_ok(ptr)) {\n")
1853                         out_java_struct.write("\t\t\treturn new " + human_ty + "_OK(null, ptr);\n")
1854                         out_java_struct.write("\t\t} else {\n")
1855                         out_java_struct.write("\t\t\treturn new " + human_ty + "_Err(null, ptr);\n")
1856                         out_java_struct.write("\t\t}\n")
1857                         out_java_struct.write("\t}\n")
1858
1859                         contents_ty = alias_match.group(1).replace("LDKCResultTempl", "LDKCResultPtr")
1860                         res_ty, err_ty = result_ptr_struct_items[contents_ty]
1861                         res_map = map_type(res_ty + " res", True, None, False, True)
1862                         err_map = map_type(err_ty + " err", True, None, False, True)
1863
1864                         out_java.write("\tpublic static native boolean " + alias_match.group(2) + "_result_ok(long arg);\n")
1865                         write_c("JNIEXPORT jboolean JNICALL Java_org_ldk_impl_bindings_" + alias_match.group(2).replace("_", "_1") + "_1result_1ok (JNIEnv * env, jclass _a, jlong arg) {\n")
1866                         write_c("\treturn ((" + alias_match.group(2) + "*)arg)->result_ok;\n")
1867                         write_c("}\n")
1868
1869                         out_java.write("\tpublic static native " + res_map.java_ty + " " + alias_match.group(2) + "_get_ok(long arg);\n")
1870                         write_c("JNIEXPORT " + res_map.c_ty + " JNICALL Java_org_ldk_impl_bindings_" + alias_match.group(2).replace("_", "_1") + "_1get_1ok (JNIEnv * _env, jclass _a, jlong arg) {\n")
1871                         write_c("\t" + alias_match.group(2) + " *val = (" + alias_match.group(2) + "*)arg;\n")
1872                         write_c("\tCHECK(val->result_ok);\n\t")
1873                         out_java_struct.write("\tpublic static final class " + human_ty + "_OK extends " + human_ty + " {\n")
1874                         if res_map.ret_conv is not None:
1875                             write_c(res_map.ret_conv[0].replace("\n", "\n\t") + "(*val->contents.result)")
1876                             write_c(res_map.ret_conv[1].replace("\n", "\n\t") + "\n\treturn " + res_map.ret_conv_name)
1877                         else:
1878                             write_c("return *val->contents.result")
1879                         write_c(";\n}\n")
1880
1881                         out_java_struct.write("\t\tpublic final " + res_map.java_hu_ty + " res;\n")
1882                         out_java_struct.write("\t\tprivate " + human_ty + "_OK(Object _dummy, long ptr) {\n")
1883                         out_java_struct.write("\t\t\tsuper(_dummy, ptr);\n")
1884                         if res_map.to_hu_conv is not None:
1885                             out_java_struct.write("\t\t\t" + res_map.java_ty + " res = bindings." + alias_match.group(2) + "_get_ok(ptr);\n")
1886                             out_java_struct.write("\t\t\t" + res_map.to_hu_conv.replace("\n", "\n\t\t\t"))
1887                             out_java_struct.write("\n\t\t\tthis.res = " + res_map.to_hu_conv_name + ";\n")
1888                         else:
1889                             out_java_struct.write("\t\t\tthis.res = bindings." + alias_match.group(2) + "_get_ok(ptr);\n")
1890                         out_java_struct.write("\t\t}\n")
1891                         if alias_match.group(2).startswith("LDKCResult_None"):
1892                             out_java_struct.write("\t\tpublic " + human_ty + "_OK() {\n\t\t\tthis(null, bindings.C" + human_ty + "_ok());\n")
1893                         else:
1894                             out_java_struct.write("\t\tpublic " + human_ty + "_OK(" + res_map.java_hu_ty + " res) {\n")
1895                             if res_map.from_hu_conv is not None:
1896                                 out_java_struct.write("\t\t\tthis(null, bindings.C" + human_ty + "_ok(" + res_map.from_hu_conv[0] + "));\n")
1897                                 if res_map.from_hu_conv[1] != "":
1898                                     out_java_struct.write("\t\t\t" + res_map.from_hu_conv[1] + ";\n")
1899                             else:
1900                                 out_java_struct.write("\t\t\tthis(null, bindings.C" + human_ty + "_ok(res));\n")
1901                         out_java_struct.write("\t\t}\n\t}\n\n")
1902
1903                         out_java.write("\tpublic static native " + err_map.java_ty + " " + alias_match.group(2) + "_get_err(long arg);\n")
1904                         write_c("JNIEXPORT " + err_map.c_ty + " JNICALL Java_org_ldk_impl_bindings_" + alias_match.group(2).replace("_", "_1") + "_1get_1err (JNIEnv * _env, jclass _a, jlong arg) {\n")
1905                         write_c("\t" + alias_match.group(2) + " *val = (" + alias_match.group(2) + "*)arg;\n")
1906                         write_c("\tCHECK(!val->result_ok);\n\t")
1907                         out_java_struct.write("\tpublic static final class " + human_ty + "_Err extends " + human_ty + " {\n")
1908                         if err_map.ret_conv is not None:
1909                             write_c(err_map.ret_conv[0].replace("\n", "\n\t") + "(*val->contents.err)")
1910                             write_c(err_map.ret_conv[1].replace("\n", "\n\t") + "\n\treturn " + err_map.ret_conv_name)
1911                         else:
1912                             write_c("return *val->contents.err")
1913                         write_c(";\n}\n")
1914
1915                         out_java_struct.write("\t\tpublic final " + err_map.java_hu_ty + " err;\n")
1916                         out_java_struct.write("\t\tprivate " + human_ty + "_Err(Object _dummy, long ptr) {\n")
1917                         out_java_struct.write("\t\t\tsuper(_dummy, ptr);\n")
1918                         if err_map.to_hu_conv is not None:
1919                             out_java_struct.write("\t\t\t" + err_map.java_ty + " err = bindings." + alias_match.group(2) + "_get_err(ptr);\n")
1920                             out_java_struct.write("\t\t\t" + err_map.to_hu_conv.replace("\n", "\n\t\t\t"))
1921                             out_java_struct.write("\n\t\t\tthis.err = " + err_map.to_hu_conv_name + ";\n")
1922                         else:
1923                             out_java_struct.write("\t\t\tthis.err = bindings." + alias_match.group(2) + "_get_err(ptr);\n")
1924                         out_java_struct.write("\t\t}\n")
1925
1926                         if alias_match.group(2).endswith("NoneZ"):
1927                             out_java_struct.write("\t\tpublic " + human_ty + "_Err() {\n\t\t\tthis(null, bindings.C" + human_ty + "_err());\n")
1928                         else:
1929                             out_java_struct.write("\t\tpublic " + human_ty + "_Err(" + err_map.java_hu_ty + " err) {\n")
1930                             if err_map.from_hu_conv is not None:
1931                                 out_java_struct.write("\t\t\tthis(null, bindings.C" + human_ty + "_err(" + err_map.from_hu_conv[0] + "));\n")
1932                                 if err_map.from_hu_conv[1] != "":
1933                                     out_java_struct.write("\t\t\t" + err_map.from_hu_conv[1] + ";\n")
1934                             else:
1935                                 out_java_struct.write("\t\t\tthis(null, bindings.C" + human_ty + "_err(err));\n")
1936                         out_java_struct.write("\t\t}\n\t}\n}\n")
1937             elif fn_ptr is not None:
1938                 map_fn(line, fn_ptr, None, None)
1939             elif fn_ret_arr is not None:
1940                 map_fn(line, fn_ret_arr, fn_ret_arr.group(4), None)
1941             elif reg_fn is not None:
1942                 map_fn(line, reg_fn, None, None)
1943             elif const_val_regex is not None:
1944                 # TODO Map const variables
1945                 pass
1946             else:
1947                 assert(line == "\n")
1948
1949     out_java.write("}\n")
1950     for struct_name in opaque_structs:
1951         with open(sys.argv[3] + "/structs/" + struct_name.replace("LDK","") + ".java", "a") as out_java_struct:
1952             out_java_struct.write("}\n")
1953     for struct_name in trait_structs:
1954         with open(sys.argv[3] + "/structs/" + struct_name.replace("LDK","") + ".java", "a") as out_java_struct:
1955             out_java_struct.write("}\n")
1956 with open(sys.argv[4], "w") as out_c:
1957     out_c.write(c_file_pfx)
1958     for ty in c_array_class_caches:
1959         if ty + "_clz" in c_file:
1960             out_c.write("static jclass " + ty + "_clz = NULL;\n")
1961     out_c.write("JNIEXPORT void Java_org_ldk_impl_bindings_init_1class_1cache(JNIEnv * env, jclass _b) {\n")
1962     for ty in c_array_class_caches:
1963         if ty + "_clz" in c_file:
1964             out_c.write("\t" + ty + "_clz = (*env)->FindClass(env, \"" + ty.replace("arr_of_", "[") + "\");\n")
1965             out_c.write("\tCHECK(" + ty + "_clz != NULL);\n")
1966             out_c.write("\t" + ty + "_clz = (*env)->NewGlobalRef(env, " + ty + "_clz);\n")
1967     out_c.write("}\n")
1968     out_c.write(c_file)