]> git.bitcoin.ninja Git - ldk-java/blob - java_strings.py
b0c100e7fa6fc82e89eb1823593e7dbdab4305a2
[ldk-java] / java_strings.py
1 from bindingstypes import *
2 from enum import Enum
3 import sys
4
5 class Target(Enum):
6     JAVA = 1,
7     ANDROID = 2
8     MACOS = 3
9
10 class Consts:
11     def __init__(self, DEBUG: bool, target: Target, **kwargs):
12         self.target = target
13         self.c_array_class_caches = set()
14         self.c_type_map = dict(
15             bool = ['boolean'],
16             uint8_t = ['byte'],
17             uint16_t = ['short'],
18             uint32_t = ['int'],
19             uint64_t = ['long'],
20             int64_t = ['long'],
21             double = ['double'],
22         )
23         self.java_type_map = dict(
24             String = "String"
25         )
26         self.java_hu_type_map = dict(
27             String = "String"
28         )
29
30         self.to_hu_conv_templates = dict(
31             ptr = '{human_type} {var_name}_hu_conv = null; if ({var_name} < 0 || {var_name} > 4096) { {var_name}_hu_conv = new {human_type}(null, {var_name}); }',
32             default = '{human_type} {var_name}_hu_conv = null; if ({var_name} < 0 || {var_name} > 4096) { {var_name}_hu_conv = new {human_type}(null, {var_name}); }'
33         )
34
35         self.bindings_header = """package org.ldk.impl;
36 import org.ldk.enums.*;
37 import org.ldk.impl.version;
38 import java.io.File;
39 import java.io.InputStream;
40 import java.io.IOException;
41 import java.nio.file.Files;
42 import java.nio.file.Path;
43 import java.nio.file.StandardCopyOption;
44
45 public class bindings {
46         static {
47                 try {
48                         // Try to load natively first, this works on Android and in testing.
49                         System.loadLibrary(\"lightningjni\");
50                 } catch (UnsatisfiedLinkError system_load_err) {
51                         // Otherwise try to load from the library jar.
52                         File tmpdir = new File(System.getProperty("java.io.tmpdir"), "ldk-java-nativelib");
53                         tmpdir.mkdir(); // If it fails to create, assume it was there already
54                         tmpdir.deleteOnExit();
55                         String libname = "liblightningjni_" + System.getProperty("os.name").replaceAll(" ", "") +
56                                 "-" + System.getProperty("os.arch").replaceAll(" ", "") + ".nativelib";
57                         try (InputStream is = bindings.class.getResourceAsStream("/" + libname)) {
58                                 Path libpath = new File(tmpdir.toPath().toString(), "liblightningjni.so").toPath();
59                                 Files.copy(is, libpath, StandardCopyOption.REPLACE_EXISTING);
60                                 Runtime.getRuntime().load(libpath.toString());
61                         } catch (Exception e) {
62                                 System.err.println("Failed to load LDK native library.");
63                                 System.err.println("System LDK native library load failed with: " + system_load_err);
64                                 System.err.println("Resource-based LDK native library load failed with: " + e);
65                                 throw new IllegalArgumentException(e);
66                         }
67                 }
68                 init(java.lang.Enum.class);
69                 init_class_cache();
70                 if (!get_lib_version_string().equals(version.get_ldk_java_bindings_version()))
71                         throw new IllegalArgumentException("Compiled LDK library and LDK class failes do not match");
72                 // Fetching the LDK versions from C also checks that the header and binaries match
73                 System.err.println("Loaded LDK-Java Bindings " + version.get_ldk_java_bindings_version() + " with LDK " + get_ldk_version() + " and LDK-C-Bindings " + get_ldk_c_bindings_version());
74         }
75         public static void run_statics() { /* Useful to force the statics to run */ }
76         static native void init(java.lang.Class c);
77         static native void init_class_cache();
78         static native String get_lib_version_string();
79
80         public static native String get_ldk_c_bindings_version();
81         public static native String get_ldk_version();
82
83 """
84         self.bindings_version_file = """package org.ldk.impl;
85
86 public class version {
87         public static String get_ldk_java_bindings_version() {
88                 return "<git_version_ldk_garbagecollected>";
89         }
90 }"""
91
92         self.util_fn_pfx = """package org.ldk.structs;
93 import org.ldk.impl.bindings;
94 import org.ldk.enums.*;
95 import org.ldk.util.*;
96 import java.util.Arrays;
97 import java.lang.ref.Reference;
98 import javax.annotation.Nullable;
99
100 public class UtilMethods {
101 """
102         self.util_fn_sfx = "}"
103         self.common_base = """package org.ldk.structs;
104 import java.util.LinkedList;
105 class CommonBase {
106         long ptr;
107         LinkedList<Object> ptrs_to = new LinkedList();
108         protected CommonBase(long ptr) { assert ptr < 0 || ptr > 4096; this.ptr = ptr; }
109 }
110 """
111
112         self.txout_defn = """public class TxOut extends CommonBase {
113         /** The script_pubkey in this output */
114         public final byte[] script_pubkey;
115         /** The value, in satoshis, of this output */
116         public final long value;
117
118         TxOut(java.lang.Object _dummy, long ptr) {
119                 super(ptr);
120                 this.script_pubkey = bindings.TxOut_get_script_pubkey(ptr);
121                 this.value = bindings.TxOut_get_value(ptr);
122         }
123         public TxOut(long value, byte[] script_pubkey) {
124                 super(bindings.TxOut_new(script_pubkey, value));
125                 this.script_pubkey = bindings.TxOut_get_script_pubkey(ptr);
126                 this.value = bindings.TxOut_get_value(ptr);
127         }
128
129         @Override @SuppressWarnings(\"deprecation\")
130         protected void finalize() throws Throwable {
131                 super.finalize();
132                 if (ptr != 0) { bindings.TxOut_free(ptr); }
133         }
134 }"""
135
136         self.txin_defn = """public class TxIn extends CommonBase {
137         /** The witness in this input, in serialized form */
138         public final byte[] witness;
139         /** The script_sig in this input */
140         public final byte[] script_sig;
141         /** The transaction output's sequence number */
142         public final int sequence;
143         /** The txid this input is spending */
144         public final byte[] previous_txid;
145         /** The output index within the spent transaction of the output this input is spending */
146         public final int previous_vout;
147
148         TxIn(java.lang.Object _dummy, long ptr) {
149                 super(ptr);
150                 this.witness = bindings.TxIn_get_witness(ptr);
151                 this.script_sig = bindings.TxIn_get_script_sig(ptr);
152                 this.sequence = bindings.TxIn_get_sequence(ptr);
153                 this.previous_txid = bindings.TxIn_get_previous_txid(ptr);
154                 this.previous_vout = bindings.TxIn_get_previous_vout(ptr);
155         }
156         /** Constructs a new TxIn, note that previous_txid must be exactly 32 bytes */
157         public TxIn(byte[] witness, byte[] script_sig, int sequence, byte[] previous_txid, int previous_vout) {
158                 this(null, bindings.TxIn_new(witness, script_sig, sequence, previous_txid, previous_vout));
159         }
160
161         @Override @SuppressWarnings(\"deprecation\")
162         protected void finalize() throws Throwable {
163                 super.finalize();
164                 if (ptr != 0) { bindings.TxIn_free(ptr); }
165         }
166 }"""
167
168         self.scalar_defn = """public class BigEndianScalar extends CommonBase {
169         /** The bytes of the scalar value, in big endian */
170         public final byte[] scalar_bytes;
171
172         BigEndianScalar(java.lang.Object _dummy, long ptr) {
173                 super(ptr);
174                 this.scalar_bytes = bindings.BigEndianScalar_get_bytes(ptr);
175         }
176         public BigEndianScalar(byte[] scalar_bytes) {
177                 super(bindings.BigEndianScalar_new(scalar_bytes));
178                 this.scalar_bytes = bindings.BigEndianScalar_get_bytes(ptr);
179         }
180
181         @Override @SuppressWarnings(\"deprecation\")
182         protected void finalize() throws Throwable {
183                 super.finalize();
184                 if (ptr != 0) { bindings.BigEndianScalar_free(ptr); }
185         }
186 }"""
187
188         self.witness_program_defn = """public class WitnessProgram extends CommonBase {
189         /** The witness program bytes themselves */
190         public final byte[] program;
191         /** The witness version */
192         public final WitnessVersion version;
193
194         WitnessProgram(java.lang.Object _dummy, long ptr) {
195                 super(ptr);
196                 this.program = bindings.WitnessProgram_get_program(ptr);
197                 this.version = new WitnessVersion(bindings.WitnessProgram_get_version(ptr));
198         }
199         static byte check_args(byte[] program, WitnessVersion version) {
200                 if (program.length < 2 || program.length > 40) throw new IllegalArgumentException();
201                 if (version.getVal() == 0 && program.length != 20 && program.length != 32) throw new IllegalArgumentException();
202                 return version.getVal();
203         }
204         public WitnessProgram(byte[] program, WitnessVersion version) {
205                 super(bindings.WitnessProgram_new(check_args(program, version), program));
206                 this.program = bindings.WitnessProgram_get_program(ptr);
207                 this.version = new WitnessVersion(bindings.WitnessProgram_get_version(ptr));
208         }
209
210         @Override @SuppressWarnings(\"deprecation\")
211         protected void finalize() throws Throwable {
212                 super.finalize();
213                 if (ptr != 0) { bindings.WitnessProgram_free(ptr); }
214         }
215 }"""
216
217         self.c_file_pfx = """#include <jni.h>
218 // On OSX jlong (ie long long) is not equivalent to int64_t, so we override here
219 #define int64_t jlong
220 #include \"org_ldk_impl_bindings.h\"
221 #include <lightning.h>
222 #include <string.h>
223 #include <stdatomic.h>
224 #include <stdlib.h>
225
226 #define LIKELY(v) __builtin_expect(!!(v), 1)
227 #define UNLIKELY(v) __builtin_expect(!!(v), 0)
228
229 """
230
231         if self.target == Target.ANDROID:
232             self.c_file_pfx = self.c_file_pfx + """
233 #include <android/log.h>
234 #define DEBUG_PRINT(...) __android_log_print(ANDROID_LOG_ERROR, "LDK", __VA_ARGS__)
235
236 #include <unistd.h>
237 #include <pthread.h>
238 static void* redirect_stderr(void* ignored) {
239         int pipes[2];
240         pipe(pipes);
241         dup2(pipes[1], STDERR_FILENO);
242         char buf[8192];
243         memset(buf, 0, 8192);
244         ssize_t len;
245         while ((len = read(pipes[0], buf, 8191)) > 0) {
246                 DEBUG_PRINT("%s\\n", buf);
247                 memset(buf, 0, 8192);
248         }
249         DEBUG_PRINT("End of stderr???\\n");
250         return 0;
251 }
252 void __attribute__((constructor)) spawn_stderr_redirection() {
253         pthread_t thread;
254         pthread_create(&thread, NULL, &redirect_stderr, NULL);
255 }
256 """
257         else:
258             self.c_file_pfx = self.c_file_pfx + "#define DEBUG_PRINT(...) fprintf(stderr, __VA_ARGS__)\n"
259
260         if not DEBUG or self.target == Target.MACOS:
261             self.c_file_pfx = self.c_file_pfx + """#define MALLOC(a, _) malloc(a)
262 #define FREE(p) if ((uint64_t)(p) > 4096) { free(p); }
263 #define CHECK_ACCESS(p)
264 #define CHECK_INNER_FIELD_ACCESS_OR_NULL(v)
265 """
266         if not DEBUG:
267             self.c_file_pfx += """#define DO_ASSERT(a) (void)(a)
268 #define CHECK(a)
269 """
270         if DEBUG:
271             self.c_file_pfx = self.c_file_pfx + """#include <assert.h>
272 // Always run a, then assert it is true:
273 #define DO_ASSERT(a) do { bool _assert_val = (a); assert(_assert_val); } while(0)
274 // Assert a is true or do nothing
275 #define CHECK(a) DO_ASSERT(a)
276
277 void __attribute__((constructor)) debug_log_version() {
278         if (check_get_ldk_version() == NULL)
279                 DEBUG_PRINT("LDK version did not match the header we built against\\n");
280         if (check_get_ldk_bindings_version() == NULL)
281                 DEBUG_PRINT("LDK C Bindings version did not match the header we built against\\n");
282 }
283 """
284
285             if self.target != Target.MACOS:
286                 self.c_file_pfx += """
287 // Running a leak check across all the allocations and frees of the JDK is a mess,
288 // so instead we implement our own naive leak checker here, relying on the -wrap
289 // linker option to wrap malloc/calloc/realloc/free, tracking everyhing allocated
290 // and free'd in Rust or C across the generated bindings shared library.
291 #include <threads.h>
292 """
293
294                 if self.target == Target.ANDROID:
295                     self.c_file_pfx = self.c_file_pfx + """
296 #include <unwind.h>
297 #include <dlfcn.h>
298
299 // Implement the execinfo functions using _Unwind_backtrace. This seems to miss many Rust
300 // symbols, so we only use it on Android, where execinfo.h is unavailable.
301
302 struct BacktraceState {
303         void** current;
304         void** end;
305 };
306 static _Unwind_Reason_Code unwind_callback(struct _Unwind_Context* context, void* arg) {
307         struct BacktraceState* state = (struct BacktraceState*)arg;
308         uintptr_t pc = _Unwind_GetIP(context);
309         if (pc) {
310                 if (state->current == state->end) {
311                         return _URC_END_OF_STACK;
312                 } else {
313                         *state->current++ = (void*)(pc);
314                 }
315         }
316         return _URC_NO_REASON;
317 }
318
319 int backtrace(void** buffer, int max) {
320         struct BacktraceState state = { buffer, buffer + max };
321         _Unwind_Backtrace(unwind_callback, &state);
322         return state.current - buffer;
323 }
324
325 void backtrace_symbols_fd(void ** buffer, int count, int _fd) {
326         for (int idx = 0; idx < count; ++idx) {
327                 Dl_info info;
328                 if (dladdr(buffer[idx], &info) && info.dli_sname) {
329                         DEBUG_PRINT("%p: %s", buffer[idx], info.dli_sname);
330                 } else {
331                         DEBUG_PRINT("%p: ???", buffer[idx]);
332                 }
333         }
334 }
335 """
336                 else:
337                     self.c_file_pfx = self.c_file_pfx + "#include <execinfo.h>\n"
338                 self.c_file_pfx = self.c_file_pfx + """
339 #include <unistd.h>
340 #include <pthread.h>
341 static pthread_mutex_t allocation_mtx;
342
343 void __attribute__((constructor)) init_mtx() {
344         DO_ASSERT(!pthread_mutex_init(&allocation_mtx, NULL));
345 }
346
347 #define BT_MAX 128
348 typedef struct allocation {
349         struct allocation* next;
350         void* ptr;
351         const char* struct_name;
352         void* bt[BT_MAX];
353         int bt_len;
354         unsigned long alloc_len;
355 } allocation;
356 static allocation* allocation_ll = NULL;
357
358 void* __real_malloc(size_t len);
359 void* __real_calloc(size_t nmemb, size_t len);
360 static void new_allocation(void* res, const char* struct_name, size_t len) {
361         allocation* new_alloc = __real_malloc(sizeof(allocation));
362         new_alloc->ptr = res;
363         new_alloc->struct_name = struct_name;
364         new_alloc->bt_len = backtrace(new_alloc->bt, BT_MAX);
365         new_alloc->alloc_len = len;
366         DO_ASSERT(!pthread_mutex_lock(&allocation_mtx));
367         new_alloc->next = allocation_ll;
368         allocation_ll = new_alloc;
369         DO_ASSERT(!pthread_mutex_unlock(&allocation_mtx));
370 }
371 static void* MALLOC(size_t len, const char* struct_name) {
372         void* res = __real_malloc(len);
373         new_allocation(res, struct_name, len);
374         return res;
375 }
376 void __real_free(void* ptr);
377 static void alloc_freed(void* ptr) {
378         allocation* p = NULL;
379         DO_ASSERT(!pthread_mutex_lock(&allocation_mtx));
380         allocation* it = allocation_ll;
381         while (it->ptr != ptr) {
382                 p = it; it = it->next;
383                 if (it == NULL) {
384                         DEBUG_PRINT("ERROR: Tried to free unknown pointer %p at:\\n", ptr);
385                         void* bt[BT_MAX];
386                         int bt_len = backtrace(bt, BT_MAX);
387                         backtrace_symbols_fd(bt, bt_len, STDERR_FILENO);
388                         DEBUG_PRINT("\\n\\n");
389                         DO_ASSERT(!pthread_mutex_unlock(&allocation_mtx));
390                         return; // addrsan should catch malloc-unknown and print more info than we have
391                 }
392         }
393         if (p) { p->next = it->next; } else { allocation_ll = it->next; }
394         DO_ASSERT(!pthread_mutex_unlock(&allocation_mtx));
395         DO_ASSERT(it->ptr == ptr);
396         __real_free(it);
397 }
398 static void FREE(void* ptr) {
399         if ((uint64_t)ptr <= 4096) return; // Rust loves to create pointers to the NULL page for dummys
400         alloc_freed(ptr);
401         __real_free(ptr);
402 }
403
404 void* __wrap_malloc(size_t len) {
405         void* res = __real_malloc(len);
406         new_allocation(res, "malloc call", len);
407         return res;
408 }
409 void* __wrap_calloc(size_t nmemb, size_t len) {
410         void* res = __real_calloc(nmemb, len);
411         new_allocation(res, "calloc call", len);
412         return res;
413 }
414 void __wrap_free(void* ptr) {
415         if (ptr == NULL) return;
416         alloc_freed(ptr);
417         __real_free(ptr);
418 }
419
420 static void CHECK_ACCESS(const void* ptr) {
421         DO_ASSERT(!pthread_mutex_lock(&allocation_mtx));
422         allocation* it = allocation_ll;
423         while (it->ptr != ptr) {
424                 it = it->next;
425                 if (it == NULL) {
426                         DEBUG_PRINT("ERROR: Tried to access unknown pointer %p at:\\n", ptr);
427                         void* bt[BT_MAX];
428                         int bt_len = backtrace(bt, BT_MAX);
429                         backtrace_symbols_fd(bt, bt_len, STDERR_FILENO);
430                         DEBUG_PRINT("\\n\\n");
431                         DO_ASSERT(!pthread_mutex_unlock(&allocation_mtx));
432                         return; // addrsan should catch and print more info than we have
433                 }
434         }
435         DO_ASSERT(!pthread_mutex_unlock(&allocation_mtx));
436 }
437 #define CHECK_INNER_FIELD_ACCESS_OR_NULL(v) \\
438         if (v.is_owned && v.inner != NULL) { \\
439                 const void *p = __unmangle_inner_ptr(v.inner); \\
440                 if (p != NULL) { \\
441                         CHECK_ACCESS(p); \\
442                 } \\
443         }
444
445 void* __real_realloc(void* ptr, size_t newlen);
446 void* __wrap_realloc(void* ptr, size_t len) {
447         if (ptr != NULL) alloc_freed(ptr);
448         void* res = __real_realloc(ptr, len);
449         new_allocation(res, "realloc call", len);
450         return res;
451 }
452 void __wrap_reallocarray(void* ptr, size_t new_sz) {
453         // Rust doesn't seem to use reallocarray currently
454         DO_ASSERT(false);
455 }
456
457 void __attribute__((destructor)) check_leaks() {
458         unsigned long alloc_count = 0;
459         unsigned long alloc_size = 0;
460         DEBUG_PRINT("The following LDK-allocated blocks still remain.\\n");
461         DEBUG_PRINT("Note that this is only accurate if System.gc(); System.runFinalization()\\n");
462         DEBUG_PRINT("was called prior to exit after all LDK objects were out of scope.\\n");
463         for (allocation* a = allocation_ll; a != NULL; a = a->next) {
464                 DEBUG_PRINT("%s %p (%lu bytes) remains:\\n", a->struct_name, a->ptr, a->alloc_len);
465                 backtrace_symbols_fd(a->bt, a->bt_len, STDERR_FILENO);
466                 DEBUG_PRINT("\\n\\n");
467                 alloc_count++;
468                 alloc_size += a->alloc_len;
469         }
470         DEBUG_PRINT("%lu allocations remained for %lu bytes.\\n", alloc_count, alloc_size);
471         DEBUG_PRINT("Note that this is only accurate if System.gc(); System.runFinalization()\\n");
472         DEBUG_PRINT("was called prior to exit after all LDK objects were out of scope.\\n");
473 }
474 """
475         self.c_file_pfx = self.c_file_pfx + """
476 static jmethodID ordinal_meth = NULL;
477 JNIEXPORT void Java_org_ldk_impl_bindings_init(JNIEnv * env, jclass _b, jclass enum_class) {
478         ordinal_meth = (*env)->GetMethodID(env, enum_class, "ordinal", "()I");
479         CHECK(ordinal_meth != NULL);
480 }
481
482 // We assume that CVec_u8Z and u8slice are the same size and layout (and thus pointers to the two can be mixed)
483 _Static_assert(sizeof(LDKCVec_u8Z) == sizeof(LDKu8slice), "Vec<u8> and [u8] need to have been mapped identically");
484 _Static_assert(offsetof(LDKCVec_u8Z, data) == offsetof(LDKu8slice, data), "Vec<u8> and [u8] need to have been mapped identically");
485 _Static_assert(offsetof(LDKCVec_u8Z, datalen) == offsetof(LDKu8slice, datalen), "Vec<u8> and [u8] need to have been mapped identically");
486
487 _Static_assert(sizeof(jlong) == sizeof(int64_t), "We assume that j-types are the same as C types");
488 _Static_assert(sizeof(jbyte) == sizeof(char), "We assume that j-types are the same as C types");
489 _Static_assert(sizeof(void*) <= 8, "Pointers must fit into 64 bits");
490
491 typedef jlongArray int64_tArray;
492 typedef jbyteArray int8_tArray;
493 typedef jshortArray int16_tArray;
494
495 static inline jstring str_ref_to_java(JNIEnv *env, const unsigned char* chars, size_t len) {
496         // Java uses "Modified UTF-8" rather than UTF-8. This requires special
497         // handling for codepoints above 0xFFFF, which get converted from four
498         // bytes to six. We don't know upfront how many codepoints in the string
499         // are above 0xFFFF, so we just allocate an extra 33% up front and waste a
500         // bit of space.
501         unsigned char* java_chars = MALLOC(len * 3 / 2 + 1, "str conv buf");
502         unsigned char* next_java_char = java_chars;
503         const unsigned char* next_in_char = chars;
504         const unsigned char* end = chars + len;
505         #define COPY_CHAR_TO_JAVA do { *next_java_char = *next_in_char; next_java_char++; next_in_char++; } while (0)
506
507         while (next_in_char < end) {
508                 if (!*next_in_char) break;
509                 if (!(*next_in_char & 0b10000000)) {
510                         COPY_CHAR_TO_JAVA;
511                 } else if ((*next_in_char & 0b11100000) == 0b11000000) {
512                         if (next_in_char + 2 > end) { CHECK(false); break; } // bad string
513                         COPY_CHAR_TO_JAVA;
514                         COPY_CHAR_TO_JAVA;
515                 } else if ((*next_in_char & 0b11110000) == 0b11100000) {
516                         if (next_in_char + 3 > end) { CHECK(false); break; } // bad string
517                         COPY_CHAR_TO_JAVA;
518                         COPY_CHAR_TO_JAVA;
519                         COPY_CHAR_TO_JAVA;
520                 } else if ((*next_in_char & 0b11111000) == 0b11110000) {
521                         if (next_in_char + 4 > end) { CHECK(false); break; } // bad string
522                         uint32_t codepoint = 0;
523                         codepoint |= (((uint32_t)*(next_in_char    )) & 0b00000111) << 18;
524                         codepoint |= (((uint32_t)*(next_in_char + 1)) & 0b00111111) << 12;
525                         codepoint |= (((uint32_t)*(next_in_char + 2)) & 0b00111111) << 6;
526                         codepoint |= (((uint32_t)*(next_in_char + 3)) & 0b00111111) << 0;
527                         codepoint -= 0x10000;
528                         *next_java_char = 0b11101101;
529                         next_java_char++;
530                         *next_java_char = 0b10100000 | ((codepoint >> 16) & 0b00001111);
531                         next_java_char++;
532                         *next_java_char = 0b10000000 | ((codepoint >> 10) & 0b00111111);
533                         next_java_char++;
534                         *next_java_char = 0b11101101;
535                         next_java_char++;
536                         *next_java_char = 0b10110000 | ((codepoint >>  6) & 0b00001111);
537                         next_java_char++;
538                         *next_java_char = 0b10000000 | ((codepoint >>  0) & 0b00111111);
539                         next_java_char++;
540                         next_in_char += 4;
541                 } else {
542                         // Bad string
543                         CHECK(false);
544                         break;
545                 }
546         }
547         *next_java_char = 0;
548         jstring ret = (*env)->NewStringUTF(env, java_chars);
549         FREE(java_chars);
550         return ret;
551 }
552 static inline LDKStr java_to_owned_str(JNIEnv *env, jstring str) {
553         uint64_t str_len = (*env)->GetStringUTFLength(env, str);
554         // Java uses "Modified UTF-8" rather than UTF-8. This requires special
555         // handling for codepoints above 0xFFFF, which we implement below.
556         unsigned char* newchars = MALLOC(str_len, "String chars");
557         unsigned char* next_newchar = newchars;
558         uint64_t utf8_len = 0;
559
560         const unsigned char* jchars = (*env)->GetStringUTFChars(env, str, NULL);
561         const unsigned char* next_char = jchars;
562         const unsigned char* end = jchars + str_len;
563
564         #define COPY_CHAR_FROM_JAVA do { *next_newchar = *next_char; next_newchar++; next_char++; utf8_len++; } while (0)
565
566         while (next_char < end) {
567                 if (!(*next_char & 0b10000000)) {
568                         CHECK(*next_char != 0); // Bad Modified UTF-8 string, but we'll just cut here
569                         COPY_CHAR_FROM_JAVA;
570                 } else if ((*next_char & 0b11100000) == 0b11000000) {
571                         if (next_char + 2 > end) { CHECK(false); break; } // bad string
572                         uint16_t codepoint = 0;
573                         codepoint |= (((uint16_t)(*next_char & 0x1f)) << 6);
574                         codepoint |= *(next_char + 1) & 0x3f;
575                         if (codepoint == 0) {
576                                 // We should really never get null codepoints, but java allows them.
577                                 // Just skip it.
578                                 next_char += 2;
579                         } else {
580                                 COPY_CHAR_FROM_JAVA;
581                                 COPY_CHAR_FROM_JAVA;
582                         }
583                 } else if ((*next_char & 0b11110000) == 0b11100000) {
584                         if (next_char + 3 > end) { CHECK(false); break; } // bad string
585                         if (*next_char == 0b11101101 && (*(next_char + 1) & 0b11110000) == 0b10100000) {
586                                 // Surrogate code unit shoul indicate we have a codepoint above
587                                 // 0xFFFF, which is where Modified UTF-8 and UTF-8 diverge.
588                                 if (next_char + 6 > end) { CHECK(false); break; } // bad string
589                                 CHECK(*(next_char + 3) == 0b11101101);
590                                 CHECK((*(next_char + 4) & 0b11110000) == 0b10110000);
591                                 // Calculate the codepoint per https://docs.oracle.com/javase/1.5.0/docs/guide/jni/spec/types.html#wp16542
592                                 uint32_t codepoint = 0x10000;
593                                 codepoint += ((((uint32_t)*(next_char + 1)) & 0x0f) << 16);
594                                 codepoint += ((((uint32_t)*(next_char + 2)) & 0x3f) << 10);
595                                 codepoint += ((((uint32_t)*(next_char + 4)) & 0x0f) <<  6);
596                                 codepoint +=  (((uint32_t)*(next_char + 5)) & 0x3f);
597                                 *next_newchar = 0b11110000 | ((codepoint >> 18) &    0b111);
598                                 next_newchar++;
599                                 *next_newchar = 0b10000000 | ((codepoint >> 12) & 0b111111);
600                                 next_newchar++;
601                                 *next_newchar = 0b10000000 | ((codepoint >>  6) & 0b111111);
602                                 next_newchar++;
603                                 *next_newchar = 0b10000000 | ( codepoint        & 0b111111);
604                                 next_newchar++;
605                                 next_char += 6;
606                                 utf8_len += 4;
607                         } else {
608                                 COPY_CHAR_FROM_JAVA;
609                                 COPY_CHAR_FROM_JAVA;
610                                 COPY_CHAR_FROM_JAVA;
611                         }
612                 } else {
613                         // Bad string
614                         CHECK(false);
615                         break;
616                 }
617         }
618         (*env)->ReleaseStringUTFChars(env, str, jchars);
619         LDKStr res = {
620                 .chars = newchars,
621                 .len = utf8_len,
622                 .chars_is_owned = true
623         };
624         return res;
625 }
626
627 JNIEXPORT jstring JNICALL Java_org_ldk_impl_bindings_get_1ldk_1c_1bindings_1version(JNIEnv *env, jclass _c) {
628         return str_ref_to_java(env, check_get_ldk_bindings_version(), strlen(check_get_ldk_bindings_version()));
629 }
630 JNIEXPORT jstring JNICALL Java_org_ldk_impl_bindings_get_1ldk_1version(JNIEnv *env, jclass _c) {
631         return str_ref_to_java(env, check_get_ldk_version(), strlen(check_get_ldk_version()));
632 }
633 #include "version.c"
634 """
635         self.c_version_file = """JNIEXPORT jstring JNICALL Java_org_ldk_impl_bindings_get_1lib_1version_1string(JNIEnv *env, jclass _c) {
636         return str_ref_to_java(env, "<git_version_ldk_garbagecollected>", strlen("<git_version_ldk_garbagecollected>"));
637 }"""
638
639         self.hu_struct_file_prefix = """package org.ldk.structs;
640
641 import org.ldk.impl.bindings;
642 import org.ldk.enums.*;
643 import org.ldk.util.*;
644 import java.util.Arrays;
645 import java.lang.ref.Reference;
646 import javax.annotation.Nullable;
647
648 """
649         self.hu_struct_file_suffix = ""
650         self.c_fn_ty_pfx = "JNIEXPORT "
651         self.c_fn_args_pfx = "JNIEnv *env, jclass clz"
652         self.file_ext = ".java"
653         self.ptr_c_ty = "int64_t"
654         self.ptr_native_ty = "long"
655         self.u128_native_ty = "UInt128"
656         self.usize_c_ty = "int64_t"
657         self.usize_native_ty = "long"
658         self.native_zero_ptr = "0"
659         self.unitary_enum_c_ty = "jclass"
660         self.ptr_arr = "jobjectArray"
661         self.is_arr_some_check = ("", " != NULL")
662         self.get_native_arr_len_call = ("(*env)->GetArrayLength(env, ", ")")
663
664     def bindings_footer(self):
665         return "}\n"
666
667     def construct_jenv(self):
668         res =  "JNIEnv *env;\n"
669         res += "jint get_jenv_res = (*j_calls->vm)->GetEnv(j_calls->vm, (void**)&env, JNI_VERSION_1_6);\n"
670         res += "if (get_jenv_res == JNI_EDETACHED) {\n"
671         if self.target == Target.ANDROID:
672             res += "\tDO_ASSERT((*j_calls->vm)->AttachCurrentThread(j_calls->vm, &env, NULL) == JNI_OK);\n"
673         else:
674             res += "\tDO_ASSERT((*j_calls->vm)->AttachCurrentThread(j_calls->vm, (void**)&env, NULL) == JNI_OK);\n"
675         res += "} else {\n"
676         res += "\tDO_ASSERT(get_jenv_res == JNI_OK);\n"
677         res += "}\n"
678         return res
679     def deconstruct_jenv(self):
680         res = "if (get_jenv_res == JNI_EDETACHED) {\n"
681         res += "\tDO_ASSERT((*j_calls->vm)->DetachCurrentThread(j_calls->vm) == JNI_OK);\n"
682         res += "}\n"
683         return res
684
685     def release_native_arr_ptr_call(self, ty_info, arr_var, arr_ptr_var):
686         if ty_info.subty is None or not ty_info.subty.c_ty.endswith("Array"):
687             return "(*env)->ReleasePrimitiveArrayCritical(env, " + arr_var + ", " + arr_ptr_var + ", 0)"
688         return None
689     def create_native_arr_call(self, arr_len, ty_info):
690         if ty_info.c_ty == "int8_tArray":
691             return "(*env)->NewByteArray(env, " + arr_len + ")"
692         elif ty_info.subty.c_ty.endswith("Array"):
693             clz_var = ty_info.java_fn_ty_arg[1:].replace("[", "arr_of_")
694             self.c_array_class_caches.add(clz_var)
695             return "(*env)->NewObjectArray(env, " + arr_len + ", " + clz_var + "_clz, NULL);\n"
696         elif ty_info.subty.c_ty == "jstring":
697             return "(*env)->NewObjectArray(env, " + arr_len + ", String_clz, NULL);\n"
698         else:
699             return "(*env)->New" + ty_info.java_ty.strip("[]").title() + "Array(env, " + arr_len + ")"
700     def set_native_arr_contents(self, arr_name, arr_len, ty_info):
701         if ty_info.c_ty == "int8_tArray":
702             return ("(*env)->SetByteArrayRegion(env, " + arr_name + ", 0, " + arr_len + ", ", ")")
703         elif ty_info.c_ty == "int16_tArray":
704             return ("(*env)->SetShortArrayRegion(env, " + arr_name + ", 0, " + arr_len + ", ", ")")
705         else:
706             assert False
707     def get_native_arr_contents(self, arr_name, dest_name, arr_len, ty_info, copy):
708         if "String" in ty_info.java_ty:
709             return None
710         if ty_info.c_ty == "int8_tArray" or ty_info.c_ty == "int16_tArray":
711             fn_ty = "Byte" if ty_info.c_ty == "int8_tArray" else "Short"
712             if copy:
713                 return "(*env)->Get" + fn_ty + "ArrayRegion(env, " + arr_name + ", 0, " + arr_len + ", " + dest_name + ")"
714             else:
715                 return "(*env)->Get" + fn_ty + "ArrayElements (env, " + arr_name + ", NULL)"
716         elif not ty_info.java_ty[:len(ty_info.java_ty) - 2].endswith("[]"):
717             return "(*env)->Get" + ty_info.subty.java_ty.title() + "ArrayElements (env, " + arr_name + ", NULL)"
718         else:
719             return None
720     def get_native_arr_elem(self, arr_name, idxc, ty_info):
721         if self.get_native_arr_contents(arr_name, "", "", ty_info, False) is None:
722             return "(*env)->GetObjectArrayElement(env, " + arr_name + ", " + idxc + ")"
723         else:
724             assert False # Only called if above is None
725     def get_native_arr_ptr_call(self, ty_info):
726         if ty_info.subty is not None and ty_info.subty.c_ty.endswith("Array"):
727             return None
728         return ("(*env)->GetPrimitiveArrayCritical(env, ", ", NULL)")
729     def get_native_arr_entry_call(self, ty_info, arr_name, idxc, entry_access):
730         if ty_info.subty is None or not ty_info.subty.c_ty.endswith("Array"):
731             return None
732         return "(*env)->SetObjectArrayElement(env, " + arr_name + ", " + idxc + ", " + entry_access + ")"
733     def cleanup_native_arr_ref_contents(self, arr_name, dest_name, arr_len, ty_info):
734         if ty_info.c_ty == "int8_tArray":
735             return "(*env)->ReleaseByteArrayElements(env, " + arr_name + ", (int8_t*)" + dest_name + ", 0);"
736         else:
737             return "(*env)->Release" + ty_info.java_ty.strip("[]").title() + "ArrayElements(env, " + arr_name + ", " + dest_name + ", 0)"
738
739     def map_hu_array_elems(self, arr_name, conv_name, arr_ty, elem_ty, is_nullable):
740         if elem_ty.java_ty == "long" and elem_ty.java_hu_ty != "long":
741             return arr_name + " != null ? Arrays.stream(" + arr_name + ").mapToLong(" + conv_name + " -> " + elem_ty.from_hu_conv[0] + ").toArray() : null"
742         elif elem_ty.java_ty == "long":
743             return arr_name + " != null ? Arrays.stream(" + arr_name + ").map(" + conv_name + " -> " + elem_ty.from_hu_conv[0] + ").toArray() : null"
744         elif elem_ty.java_hu_ty == "UInt5":
745             return arr_name + " != null ? InternalUtils.convUInt5Array(" + arr_name + ") : null"
746         elif elem_ty.java_hu_ty == "WitnessVersion":
747             return arr_name + " != null ? InternalUtils.convWitnessVersionArray(" + arr_name + ") : null"
748         else:
749             return arr_name + " != null ? Arrays.stream(" + arr_name + ").map(" + conv_name + " -> " + elem_ty.from_hu_conv[0] + ").toArray(" + arr_ty.java_ty + "::new) : null"
750
751     def str_ref_to_native_call(self, var_name, str_len):
752         return "str_ref_to_java(env, " + var_name + ", " + str_len + ")"
753     def str_ref_to_c_call(self, var_name):
754         return "java_to_owned_str(env, " + var_name + ")"
755     def str_to_hu_conv(self, var_name):
756         return None
757     def str_from_hu_conv(self, var_name):
758         return None
759
760     def c_fn_name_define_pfx(self, fn_name, has_args):
761         if has_args:
762             return "JNICALL Java_org_ldk_impl_bindings_" + fn_name.replace("_", "_1") + "(JNIEnv *env, jclass clz, "
763         return "JNICALL Java_org_ldk_impl_bindings_" + fn_name.replace("_", "_1") + "(JNIEnv *env, jclass clz"
764
765     def init_str(self):
766         res = ""
767         for ty in sorted(self.c_array_class_caches):
768             res = res + "static jclass " + ty + "_clz = NULL;\n"
769         res = res + "static jclass String_clz = NULL;\n"
770         res = res + "JNIEXPORT void Java_org_ldk_impl_bindings_init_1class_1cache(JNIEnv * env, jclass clz) {\n"
771         for ty in sorted(self.c_array_class_caches):
772             res = res + "\t" + ty + "_clz = (*env)->FindClass(env, \"" + ty.replace("arr_of_", "[") + "\");\n"
773             res = res + "\tCHECK(" + ty + "_clz != NULL);\n"
774             res = res + "\t" + ty + "_clz = (*env)->NewGlobalRef(env, " + ty + "_clz);\n"
775         res = res + "\tString_clz = (*env)->FindClass(env, \"java/lang/String\");\n"
776         res = res + "\tCHECK(String_clz != NULL);\n"
777         res = res + "\tString_clz = (*env)->NewGlobalRef(env, String_clz);\n"
778
779         res = res + "}\n"
780         return res
781
782     def var_decl_statement(self, ty_string, var_name, statement):
783         return ty_string + " " + var_name + " = " + statement
784
785     def get_java_arr_len(self, arr_name):
786         return arr_name + ".length"
787     def get_java_arr_elem(self, elem_ty, arr_name, idx):
788         return arr_name + "[" + idx + "]"
789     def constr_hu_array(self, ty_info, arr_len):
790         base_ty = ty_info.subty.java_hu_ty.split("[")[0].split("<")[0]
791         conv = "new " + base_ty + "[" + arr_len + "]"
792         if "[" in ty_info.subty.java_hu_ty.split("<")[0]:
793             # Do a bit of a dance to move any excess [] to the end
794             conv += "[" + ty_info.subty.java_hu_ty.split("<")[0].split("[")[1]
795         return conv
796     def cleanup_converted_native_array(self, ty_info, arr_name):
797         return None
798
799     def primitive_arr_from_hu(self, arr_ty, fixed_len, arr_name):
800         mapped_ty = arr_ty.subty
801         if arr_ty.rust_obj == "LDKU128":
802             return ("" + arr_name + ".getLEBytes()", "")
803         if fixed_len is not None:
804             if mapped_ty.c_ty == "int8_t" or mapped_ty.c_ty == "uint8_t":
805                 return ("InternalUtils.check_arr_len(" + arr_name + ", " + fixed_len + ")", "")
806             elif mapped_ty.c_ty == "int16_t" or mapped_ty.c_ty == "uint16_t":
807                 return ("InternalUtils.check_arr_16_len(" + arr_name + ", " + fixed_len + ")", "")
808             else:
809                 print(arr_ty.c_ty)
810                 assert False
811         return None
812     def primitive_arr_to_hu(self, arr_ty, fixed_len, arr_name, conv_name):
813         if arr_ty.rust_obj == "LDKU128":
814             return "org.ldk.util.UInt128 " + conv_name + " = new org.ldk.util.UInt128(" + arr_name + ");"
815         return None
816
817     def java_arr_ty_str(self, elem_ty_str):
818         return elem_ty_str + "[]"
819
820     def for_n_in_range(self, n, minimum, maximum):
821         return "for (int " + n + " = " + minimum + "; " + n + " < " + maximum + "; " + n + "++) {"
822     def for_n_in_arr(self, n, arr_name, arr_elem_ty):
823         return ("for (" + arr_elem_ty.java_hu_ty + " " + n + ": " + arr_name + ") { ", " }")
824
825     def get_ptr(self, var):
826         return var + ".ptr"
827     def set_null_skip_free(self, var):
828         return var + ".ptr" + " = 0;"
829
830     def add_ref(self, holder, referent):
831         return "if (" + holder + " != null) { " + holder + ".ptrs_to.add(" + referent + "); }"
832
833     def fully_qualified_hu_ty_path(self, ty):
834         if ty.java_fn_ty_arg.startswith("L") and ty.java_fn_ty_arg.endswith(";"):
835             return ty.java_fn_ty_arg.strip("L;").replace("/", ".")
836         if ty.java_hu_ty == "UnqualifiedError" or ty.java_hu_ty == "UInt128" or ty.java_hu_ty == "UInt5" or ty.java_hu_ty == "WitnessVersion":
837             return "org.ldk.util." + ty.java_hu_ty
838         if not ty.is_native_primitive and ty.rust_obj is not None and not "[]" in ty.java_hu_ty:
839             return "org.ldk.structs." + ty.java_hu_ty
840         return ty.java_hu_ty
841
842     def native_c_unitary_enum_map(self, struct_name, variants, enum_doc_comment):
843         out_java_enum = "package org.ldk.enums;\n\n"
844         out_java = ""
845         out_c = ""
846         out_c += "static inline LDK" + struct_name + " LDK" + struct_name + "_from_java(" + self.c_fn_args_pfx + ") {\n"
847         out_c += "\tjint ord = (*env)->CallIntMethod(env, clz, ordinal_meth);\n"
848         out_c += "\tif (UNLIKELY((*env)->ExceptionCheck(env))) {\n"
849         out_c += "\t\t(*env)->ExceptionDescribe(env);\n"
850         out_c += "\t\t(*env)->FatalError(env, \"A call to " + struct_name + ".ordinal() from rust threw an exception.\");\n"
851         out_c += "\t}\n"
852         out_c += "\tswitch (ord) {\n"
853
854         if enum_doc_comment is not None:
855             out_java_enum += "/**\n * " + enum_doc_comment.replace("\n", "\n * ") + "\n */\n"
856         out_java_enum += "public enum " + struct_name + " {\n"
857         ord_v = 0
858         for var, var_docs in variants:
859             if var_docs is not None:
860                 out_java_enum += "\t/**\n\t * " + var_docs.replace("\n", "\n\t * ") + "\n\t */\n"
861             out_java_enum += "\t" + var + ",\n"
862             out_c = out_c + "\t\tcase %d: return %s;\n" % (ord_v, var)
863             ord_v = ord_v + 1
864         out_java_enum = out_java_enum + "\t; static native void init();\n"
865         out_java_enum = out_java_enum + "\tstatic { org.ldk.impl.bindings.run_statics(); init(); }\n"
866         out_java_enum = out_java_enum + "}"
867         out_java = out_java + "\tstatic { " + struct_name + ".values(); /* Force enum statics to run */ }\n"
868         out_c += "\t}\n"
869         out_c += "\t(*env)->FatalError(env, \"A call to " + struct_name + ".ordinal() from rust returned an invalid value.\");\n"
870         out_c += "\tabort(); // Unreachable, but will let the compiler know we don't return here\n"
871         out_c += "}\n"
872
873         out_c = out_c + "static jclass " + struct_name + "_class = NULL;\n"
874         for var, _ in variants:
875             out_c = out_c + "static jfieldID " + struct_name + "_" + var + " = NULL;\n"
876         out_c = out_c + self.c_fn_ty_pfx + "void JNICALL Java_org_ldk_enums_" + struct_name.replace("_", "_1") + "_init (" + self.c_fn_args_pfx + ") {\n"
877         out_c = out_c + "\t" + struct_name + "_class = (*env)->NewGlobalRef(env, clz);\n"
878         out_c = out_c + "\tCHECK(" + struct_name + "_class != NULL);\n"
879         for var, _ in variants:
880             out_c = out_c + "\t" + struct_name + "_" + var + " = (*env)->GetStaticFieldID(env, " + struct_name + "_class, \"" + var + "\", \"Lorg/ldk/enums/" + struct_name + ";\");\n"
881             out_c = out_c + "\tCHECK(" + struct_name + "_" + var + " != NULL);\n"
882         out_c = out_c + "}\n"
883         out_c = out_c + "static inline jclass LDK" + struct_name + "_to_java(JNIEnv *env, LDK" + struct_name + " val) {\n"
884         out_c = out_c + "\tswitch (val) {\n"
885         ord_v = 0
886         for var, _ in variants:
887             out_c = out_c + "\t\tcase " + var + ":\n"
888             out_c = out_c + "\t\t\treturn (*env)->GetStaticObjectField(env, " + struct_name + "_class, " + struct_name + "_" + var + ");\n"
889             ord_v = ord_v + 1
890         out_c = out_c + "\t\tdefault: abort();\n"
891         out_c = out_c + "\t}\n"
892         out_c = out_c + "}\n\n"
893
894         return (out_c, out_java_enum, out_java)
895
896     def c_unitary_enum_to_native_call(self, ty_info):
897         return (ty_info.rust_obj + "_to_java(env, ", ")")
898     def native_unitary_enum_to_c_call(self, ty_info):
899         return (ty_info.rust_obj + "_from_java(env, ", ")")
900
901     def c_complex_enum_pfx(self, struct_name, variants, init_meth_jty_strs):
902         out_c = ""
903         for var in variants:
904             out_c = out_c + "static jclass " + struct_name + "_" + var + "_class = NULL;\n"
905             out_c = out_c + "static jmethodID " + struct_name + "_" + var + "_meth = NULL;\n"
906         out_c = out_c + self.c_fn_ty_pfx + "void JNICALL Java_org_ldk_impl_bindings_00024" + struct_name.replace("_", "_1") + "_init (" + self.c_fn_args_pfx + ") {\n"
907         for var_name in variants:
908             out_c += "\t" + struct_name + "_" + var_name + "_class =\n"
909             out_c += "\t\t(*env)->NewGlobalRef(env, (*env)->FindClass(env, \"org/ldk/impl/bindings$" + struct_name + "$" + var_name + "\"));\n"
910             out_c += "\tCHECK(" + struct_name + "_" + var_name + "_class != NULL);\n"
911             out_c += "\t" + struct_name + "_" + var_name + "_meth = (*env)->GetMethodID(env, " + struct_name + "_" + var_name + "_class, \"<init>\", \"(" + init_meth_jty_strs[var_name] + ")V\");\n"
912             out_c += "\tCHECK(" + struct_name + "_" + var_name + "_meth != NULL);\n"
913         out_c = out_c + "}\n"
914         return out_c
915
916     def c_complex_enum_pass_ty(self, struct_name):
917         return "jobject"
918
919     def c_constr_native_complex_enum(self, struct_name, variant, c_params):
920         ret = "(*env)->NewObject(env, " + struct_name + "_" + variant + "_class, " + struct_name + "_" + variant + "_meth"
921         for param in c_params:
922             ret = ret + ", " + param
923         return ret + ")"
924
925     def native_c_map_trait(self, struct_name, field_vars, flattened_field_vars, field_fns, trait_doc_comment):
926         out_java_trait = ""
927         out_java = ""
928
929         # First generate most of the Java code, note that we need information about java method argument strings for C
930         out_java_trait = out_java_trait + self.hu_struct_file_prefix
931         if trait_doc_comment is not None:
932             out_java_trait += "/**\n * " + trait_doc_comment.replace("\n", "\n * ") + "\n */\n"
933         out_java_trait += "@SuppressWarnings(\"unchecked\") // We correctly assign various generic arrays\n"
934         out_java_trait = out_java_trait + "public class " + struct_name.replace("LDK","") + " extends CommonBase {\n"
935         out_java_trait = out_java_trait + "\tfinal bindings." + struct_name + " bindings_instance;\n"
936         out_java_trait = out_java_trait + "\t" + struct_name.replace("LDK", "") + "(Object _dummy, long ptr) { super(ptr); bindings_instance = null; }\n"
937         out_java_trait = out_java_trait + "\tprivate " + struct_name.replace("LDK", "") + "(bindings." + struct_name + " arg"
938         for var in flattened_field_vars:
939             if isinstance(var, ConvInfo):
940                 out_java_trait = out_java_trait + ", " + var.java_hu_ty + " " + var.arg_name
941             else:
942                 out_java_trait = out_java_trait + ", bindings." + var[0] + " " + var[1]
943         out_java_trait = out_java_trait + ") {\n"
944         out_java_trait = out_java_trait + "\t\tsuper(bindings." + struct_name + "_new(arg"
945         for var in flattened_field_vars:
946             if isinstance(var, ConvInfo):
947                 if var.from_hu_conv is not None:
948                     out_java_trait = out_java_trait + ", " + var.from_hu_conv[0]
949                 else:
950                     out_java_trait = out_java_trait + ", " + var.arg_name
951             else:
952                 out_java_trait = out_java_trait + ", " + var[1]
953         out_java_trait = out_java_trait + "));\n"
954         out_java_trait = out_java_trait + "\t\tthis.ptrs_to.add(arg);\n"
955         for var in flattened_field_vars:
956             if isinstance(var, ConvInfo):
957                 if var.from_hu_conv is not None and var.from_hu_conv[1] != "":
958                     out_java_trait = out_java_trait + "\t\t" + var.from_hu_conv[1].replace("\n", "\n\t\t") + ";\n"
959             else:
960                 out_java_trait = out_java_trait + "\t\tthis.ptrs_to.add(" + var[1] + ");\n"
961         out_java_trait += f"""          this.bindings_instance = arg;
962         }}
963         @Override @SuppressWarnings("deprecation")
964         protected void finalize() throws Throwable {{
965                 if (ptr != 0) {{ bindings.{struct_name.replace("LDK","")}_free(ptr); }} super.finalize();
966         }}
967         /**
968          * Destroys the object, freeing associated resources. After this call, any access
969          * to this object may result in a SEGFAULT or worse.
970          *
971          * You should generally NEVER call this method. You should let the garbage collector
972          * do this for you when it finalizes objects. However, it may be useful for types
973          * which represent locks and should be closed immediately to avoid holding locks
974          * until the GC runs.
975          */
976         public void destroy() {{
977                 if (ptr != 0) {{ bindings.{struct_name.replace("LDK","")}_free(ptr); }}
978                 ptr = 0;
979         }}
980 """
981
982         java_trait_constr = "\tprivate static class " + struct_name + "Holder { " + struct_name.replace("LDK", "") + " held; }\n"
983         java_trait_constr = java_trait_constr + "\tpublic static " + struct_name.replace("LDK", "") + " new_impl(" + struct_name.replace("LDK", "") + "Interface arg"
984         for var in flattened_field_vars:
985             if isinstance(var, ConvInfo):
986                 java_trait_constr = java_trait_constr + ", " + var.java_hu_ty + " " + var.arg_name
987             else:
988                 # Ideally we'd be able to take any instance of the interface, but our C code can only represent
989                 # Java-implemented version, so we require users pass a Java implementation here :/
990                 java_trait_constr = java_trait_constr + ", " + var[0].replace("LDK", "") + "." + var[0].replace("LDK", "") + "Interface " + var[1] + "_impl"
991         java_trait_constr = java_trait_constr + ") {\n\t\tfinal " + struct_name + "Holder impl_holder = new " + struct_name + "Holder();\n"
992         java_trait_constr = java_trait_constr + "\t\timpl_holder.held = new " + struct_name.replace("LDK", "") + "(new bindings." + struct_name + "() {\n"
993         out_java_trait = out_java_trait + "\tpublic static interface " + struct_name.replace("LDK", "") + "Interface {\n"
994         out_java = out_java + "\tpublic interface " + struct_name + " {\n"
995         java_meths = []
996         for fn_line in field_fns:
997             java_meth_descr = "("
998             if fn_line.fn_name != "free" and fn_line.fn_name != "cloned":
999                 out_java = out_java + "\t\t " + fn_line.ret_ty_info.java_ty + " " + fn_line.fn_name + "("
1000                 java_trait_constr = java_trait_constr + "\t\t\t@Override public " + fn_line.ret_ty_info.java_ty + " " + fn_line.fn_name + "("
1001                 out_java_trait += "\t\t/**\n\t\t * " + fn_line.docs.replace("\n", "\n\t\t * ") + "\n\t\t */\n"
1002                 out_java_trait = out_java_trait + "\t\t" + fn_line.ret_ty_info.java_hu_ty + " " + fn_line.fn_name + "("
1003
1004                 for idx, arg_conv_info in enumerate(fn_line.args_ty):
1005                     if idx >= 1:
1006                         out_java = out_java + ", "
1007                         java_trait_constr = java_trait_constr + ", "
1008                         out_java_trait = out_java_trait + ", "
1009                     out_java = out_java + arg_conv_info.java_ty + " " + arg_conv_info.arg_name
1010                     out_java_trait = out_java_trait + arg_conv_info.java_hu_ty + " " + arg_conv_info.arg_name
1011                     java_trait_constr = java_trait_constr + arg_conv_info.java_ty + " " + arg_conv_info.arg_name
1012                     java_meth_descr = java_meth_descr + arg_conv_info.java_fn_ty_arg
1013                 java_meth_descr = java_meth_descr + ")" + fn_line.ret_ty_info.java_fn_ty_arg
1014                 java_meths.append((fn_line.fn_name, java_meth_descr))
1015
1016                 out_java = out_java + ");\n"
1017                 out_java_trait = out_java_trait + ");\n"
1018                 java_trait_constr = java_trait_constr + ") {\n"
1019
1020                 for arg_info in fn_line.args_ty:
1021                     if arg_info.to_hu_conv is not None:
1022                         java_trait_constr = java_trait_constr + "\t\t\t\t" + arg_info.to_hu_conv.replace("\n", "\n\t\t\t\t") + "\n"
1023
1024                 if fn_line.ret_ty_info.java_ty != "void":
1025                     java_trait_constr = java_trait_constr + "\t\t\t\t" + fn_line.ret_ty_info.java_hu_ty + " ret = arg." + fn_line.fn_name + "("
1026                 else:
1027                     java_trait_constr = java_trait_constr + "\t\t\t\targ." + fn_line.fn_name + "("
1028
1029                 for idx, arg_info in enumerate(fn_line.args_ty):
1030                     if idx != 0:
1031                         java_trait_constr = java_trait_constr + ", "
1032                     if arg_info.to_hu_conv_name is not None:
1033                         java_trait_constr = java_trait_constr + arg_info.to_hu_conv_name
1034                     else:
1035                         java_trait_constr = java_trait_constr + arg_info.arg_name
1036
1037                 java_trait_constr += ");\n"
1038                 java_trait_constr += "\t\t\t\tReference.reachabilityFence(arg);\n"
1039                 if fn_line.ret_ty_info.java_ty != "void":
1040                     if fn_line.ret_ty_info.from_hu_conv is not None:
1041                         java_trait_constr = java_trait_constr + "\t\t\t\t" + fn_line.ret_ty_info.java_ty + " result = " + fn_line.ret_ty_info.from_hu_conv[0] + ";\n"
1042                         if fn_line.ret_ty_info.from_hu_conv[1] != "":
1043                             java_trait_constr = java_trait_constr + "\t\t\t\t" + fn_line.ret_ty_info.from_hu_conv[1].replace("this", "impl_holder.held") + ";\n"
1044                         #if fn_line.ret_ty_info.rust_obj in result_types:
1045                         java_trait_constr = java_trait_constr + "\t\t\t\treturn result;\n"
1046                     else:
1047                         java_trait_constr = java_trait_constr + "\t\t\t\treturn ret;\n"
1048                 java_trait_constr = java_trait_constr + "\t\t\t}\n"
1049         java_trait_constr = java_trait_constr + "\t\t}"
1050         for var in field_vars:
1051             if isinstance(var, ConvInfo):
1052                 java_trait_constr = java_trait_constr + ", " + var.arg_name
1053             else:
1054                 java_trait_constr += ", " + var[1] + ".new_impl(" + var[1] + "_impl"
1055                 suptrait_constr = ""
1056                 for suparg in var[2]:
1057                     if isinstance(suparg, ConvInfo):
1058                         suptrait_constr += ", " + suparg.arg_name
1059                     else:
1060                         suptrait_constr += ", " + suparg[1] + "_impl"
1061                 java_trait_constr += suptrait_constr + ").bindings_instance"
1062                 for suparg in var[2]:
1063                     if isinstance(suparg, ConvInfo):
1064                         java_trait_constr += ", " + suparg.arg_name
1065                     else:
1066                         java_trait_constr += ", " + suparg[1] + ".new_impl("
1067                         # Blindly assume that we can just strip the first arg to build the args for the supertrait
1068                         java_trait_constr += suptrait_constr.split(", ", 1)[1]
1069                         java_trait_constr += ").bindings_instance"
1070         out_java_trait = out_java_trait + "\t}\n"
1071         out_java_trait = out_java_trait + java_trait_constr + ");\n\t\treturn impl_holder.held;\n\t}\n"
1072
1073         out_java = out_java + "\t}\n"
1074
1075         out_java = out_java + "\tpublic static native long " + struct_name + "_new(" + struct_name + " impl"
1076         for var in flattened_field_vars:
1077             if isinstance(var, ConvInfo):
1078                 out_java = out_java + ", " + var.java_ty + " " + var.arg_name
1079             else:
1080                 out_java = out_java + ", " + var[0] + " " + var[1]
1081         out_java = out_java + ");\n"
1082
1083         # Now that we've written out our java code (and created java_meths), generate C
1084         out_c = "typedef struct " + struct_name + "_JCalls {\n"
1085         out_c = out_c + "\tatomic_size_t refcnt;\n"
1086         out_c = out_c + "\tJavaVM *vm;\n"
1087         out_c = out_c + "\tjweak o;\n"
1088         for var in flattened_field_vars:
1089             if isinstance(var, ConvInfo):
1090                 # We're a regular ol' field
1091                 pass
1092             else:
1093                 # We're a supertrait
1094                 out_c = out_c + "\t" + var[0] + "_JCalls* " + var[1] + ";\n"
1095         for fn in field_fns:
1096             if fn.fn_name != "free" and fn.fn_name != "cloned":
1097                 out_c = out_c + "\tjmethodID " + fn.fn_name + "_meth;\n"
1098         out_c = out_c + "} " + struct_name + "_JCalls;\n"
1099
1100         for fn_line in field_fns:
1101             if fn_line.fn_name == "free":
1102                 out_c = out_c + "static void " + struct_name + "_JCalls_free(void* this_arg) {\n"
1103                 out_c = out_c + "\t" + struct_name + "_JCalls *j_calls = (" + struct_name + "_JCalls*) this_arg;\n"
1104                 out_c = out_c + "\tif (atomic_fetch_sub_explicit(&j_calls->refcnt, 1, memory_order_acquire) == 1) {\n"
1105                 out_c += "\t\t" + self.construct_jenv().replace("\n", "\n\t\t").strip() + "\n"
1106                 out_c = out_c + "\t\t(*env)->DeleteWeakGlobalRef(env, j_calls->o);\n"
1107                 out_c += "\t\t" + self.deconstruct_jenv().replace("\n", "\n\t\t").strip() + "\n"
1108                 out_c = out_c + "\t\tFREE(j_calls);\n"
1109                 out_c = out_c + "\t}\n}\n"
1110
1111         for idx, fn_line in enumerate(field_fns):
1112             if fn_line.fn_name != "free" and fn_line.fn_name != "cloned":
1113                 assert fn_line.ret_ty_info.ty_info.get_full_rust_ty()[1] == ""
1114                 out_c = out_c + fn_line.ret_ty_info.ty_info.get_full_rust_ty()[0] + " " + fn_line.fn_name + "_" + struct_name + "_jcall("
1115                 if fn_line.self_is_const:
1116                     out_c = out_c + "const void* this_arg"
1117                 else:
1118                     out_c = out_c + "void* this_arg"
1119
1120                 for idx, arg in enumerate(fn_line.args_ty):
1121                     out_c = out_c + ", " + arg.ty_info.get_full_rust_ty()[0] + " " + arg.arg_name + arg.ty_info.get_full_rust_ty()[1]
1122
1123                 out_c = out_c + ") {\n"
1124                 out_c = out_c + "\t" + struct_name + "_JCalls *j_calls = (" + struct_name + "_JCalls*) this_arg;\n"
1125                 out_c += "\t" + self.construct_jenv().replace("\n", "\n\t").strip() + "\n"
1126
1127                 for arg_info in fn_line.args_ty:
1128                     if arg_info.ret_conv is not None:
1129                         out_c = out_c + "\t" + arg_info.ret_conv[0].replace('\n', '\n\t')
1130                         out_c = out_c + arg_info.arg_name
1131                         out_c = out_c + arg_info.ret_conv[1].replace('\n', '\n\t') + "\n"
1132
1133                 out_c = out_c + "\tjobject obj = (*env)->NewLocalRef(env, j_calls->o);\n\tCHECK(obj != NULL);\n"
1134                 if fn_line.ret_ty_info.c_ty.endswith("Array"):
1135                     out_c = out_c + "\t" + fn_line.ret_ty_info.c_ty + " ret = (*env)->CallObjectMethod(env, obj, j_calls->" + fn_line.fn_name + "_meth"
1136                 elif fn_line.ret_ty_info.c_ty == "void":
1137                     out_c += "\t(*env)->CallVoidMethod(env, obj, j_calls->" + fn_line.fn_name + "_meth"
1138                 elif fn_line.ret_ty_info.java_hu_ty == "String" or "org/ldk/enums" in fn_line.ret_ty_info.java_fn_ty_arg:
1139                     # Manually write out String methods as they're just an Object
1140                     out_c += "\t" + fn_line.ret_ty_info.c_ty + " ret = (*env)->CallObjectMethod(env, obj, j_calls->" + fn_line.fn_name + "_meth"
1141                 elif not fn_line.ret_ty_info.passed_as_ptr:
1142                     out_c += "\t" + fn_line.ret_ty_info.c_ty + " ret = (*env)->Call" + fn_line.ret_ty_info.java_ty.title() + "Method(env, obj, j_calls->" + fn_line.fn_name + "_meth"
1143                 else:
1144                     out_c = out_c + "\tuint64_t ret = (*env)->CallLongMethod(env, obj, j_calls->" + fn_line.fn_name + "_meth"
1145
1146                 for idx, arg_info in enumerate(fn_line.args_ty):
1147                     if arg_info.ret_conv is not None:
1148                         out_c = out_c + ", " + arg_info.ret_conv_name
1149                     else:
1150                         out_c = out_c + ", " + arg_info.arg_name
1151                 out_c = out_c + ");\n"
1152
1153                 out_c += "\tif (UNLIKELY((*env)->ExceptionCheck(env))) {\n"
1154                 out_c += "\t\t(*env)->ExceptionDescribe(env);\n"
1155                 out_c += "\t\t(*env)->FatalError(env, \"A call to " + fn_line.fn_name + " in " + struct_name + " from rust threw an exception.\");\n"
1156                 out_c += "\t}\n"
1157
1158                 if fn_line.ret_ty_info.arg_conv is not None:
1159                     out_c += "\t" + fn_line.ret_ty_info.arg_conv.replace("\n", "\n\t") + "\n"
1160                     out_c += "\t" + self.deconstruct_jenv().replace("\n", "\n\t").strip() + "\n"
1161                     out_c += "\treturn " + fn_line.ret_ty_info.arg_conv_name + ";\n"
1162                 else:
1163                     out_c += "\t" + self.deconstruct_jenv().replace("\n", "\n\t").strip() + "\n"
1164                     if not fn_line.ret_ty_info.passed_as_ptr and fn_line.ret_ty_info.c_ty != "void":
1165                         out_c += "\treturn ret;\n"
1166
1167                 out_c = out_c + "}\n"
1168
1169         # If we can, write out a clone function whether we need one or not, as we use them in moving to rust
1170         can_clone_with_ptr = True
1171         for var in field_vars:
1172             if isinstance(var, ConvInfo):
1173                 can_clone_with_ptr = False
1174         if can_clone_with_ptr:
1175             out_c = out_c + "static void " + struct_name + "_JCalls_cloned(" + struct_name + "* new_obj) {\n"
1176             out_c = out_c + "\t" + struct_name + "_JCalls *j_calls = (" + struct_name + "_JCalls*) new_obj->this_arg;\n"
1177             out_c = out_c + "\tatomic_fetch_add_explicit(&j_calls->refcnt, 1, memory_order_release);\n"
1178             for var in flattened_field_vars:
1179                 if not isinstance(var, ConvInfo):
1180                     out_c = out_c + "\tatomic_fetch_add_explicit(&j_calls->" + var[2].replace(".", "->") + "->refcnt, 1, memory_order_release);\n"
1181             out_c = out_c + "}\n"
1182
1183         out_c = out_c + "static inline " + struct_name + " " + struct_name + "_init (" + self.c_fn_args_pfx + ", jobject o"
1184         for var in flattened_field_vars:
1185             if isinstance(var, ConvInfo):
1186                 out_c = out_c + ", " + var.c_ty + " " + var.arg_name
1187             else:
1188                 out_c = out_c + ", jobject " + var[1]
1189         out_c = out_c + ") {\n"
1190
1191         out_c = out_c + "\tjclass c = (*env)->GetObjectClass(env, o);\n"
1192         out_c = out_c + "\tCHECK(c != NULL);\n"
1193         out_c = out_c + "\t" + struct_name + "_JCalls *calls = MALLOC(sizeof(" + struct_name + "_JCalls), \"" + struct_name + "_JCalls\");\n"
1194         out_c = out_c + "\tatomic_init(&calls->refcnt, 1);\n"
1195         out_c = out_c + "\tDO_ASSERT((*env)->GetJavaVM(env, &calls->vm) == 0);\n"
1196         out_c = out_c + "\tcalls->o = (*env)->NewWeakGlobalRef(env, o);\n"
1197
1198         for (fn_name, java_meth_descr) in java_meths:
1199             if fn_name != "free" and fn_name != "cloned":
1200                 out_c = out_c + "\tcalls->" + fn_name + "_meth = (*env)->GetMethodID(env, c, \"" + fn_name + "\", \"" + java_meth_descr + "\");\n"
1201                 out_c = out_c + "\tCHECK(calls->" + fn_name + "_meth != NULL);\n"
1202
1203         for var in flattened_field_vars:
1204             if isinstance(var, ConvInfo) and var.arg_conv is not None:
1205                 out_c = out_c + "\n\t" + var.arg_conv.replace("\n", "\n\t") +"\n"
1206         out_c = out_c + "\n\t" + struct_name + " ret = {\n"
1207         out_c = out_c + "\t\t.this_arg = (void*) calls,\n"
1208         for fn_line in field_fns:
1209             if fn_line.fn_name != "free" and fn_line.fn_name != "cloned":
1210                 out_c = out_c + "\t\t." + fn_line.fn_name + " = " + fn_line.fn_name + "_" + struct_name + "_jcall,\n"
1211             elif fn_line.fn_name == "free":
1212                 out_c = out_c + "\t\t.free = " + struct_name + "_JCalls_free,\n"
1213             else:
1214                 out_c = out_c + "\t\t.cloned = " + struct_name + "_JCalls_cloned,\n"
1215         for var in field_vars:
1216             if isinstance(var, ConvInfo):
1217                 if var.arg_conv_name is not None:
1218                     out_c = out_c + "\t\t." + var.arg_name + " = " + var.arg_conv_name + ",\n"
1219                     out_c = out_c + "\t\t.set_" + var.arg_name + " = NULL,\n"
1220                 else:
1221                     out_c = out_c + "\t\t." + var.var_name + " = " + var.var_name + ",\n"
1222                     out_c = out_c + "\t\t.set_" + var.var_name + " = NULL,\n"
1223             else:
1224                 out_c += "\t\t." + var[1] + " = " + var[0] + "_init(env, clz, " + var[1]
1225                 for suparg in var[2]:
1226                     if isinstance(suparg, ConvInfo):
1227                         out_c = out_c + ", " + suparg.arg_name
1228                     else:
1229                         out_c = out_c + ", " + suparg[1]
1230                 out_c += "),\n"
1231         out_c = out_c + "\t};\n"
1232         for var in flattened_field_vars:
1233             if not isinstance(var, ConvInfo):
1234                 out_c = out_c + "\tcalls->" + var[1] + " = ret." + var[2] + ".this_arg;\n"
1235         out_c = out_c + "\treturn ret;\n"
1236         out_c = out_c + "}\n"
1237
1238         out_c = out_c + self.c_fn_ty_pfx + "int64_t " + self.c_fn_name_define_pfx(struct_name + "_new", True) + "jobject o"
1239         for var in flattened_field_vars:
1240             if isinstance(var, ConvInfo):
1241                 out_c = out_c + ", " + var.c_ty + " " + var.arg_name
1242             else:
1243                 out_c = out_c + ", jobject " + var[1]
1244         out_c = out_c + ") {\n"
1245         out_c = out_c + "\t" + struct_name + " *res_ptr = MALLOC(sizeof(" + struct_name + "), \"" + struct_name + "\");\n"
1246         out_c = out_c + "\t*res_ptr = " + struct_name + "_init(env, clz, o"
1247         for var in flattened_field_vars:
1248             if isinstance(var, ConvInfo):
1249                 out_c = out_c + ", " + var.arg_name
1250             else:
1251                 out_c = out_c + ", " + var[1]
1252         out_c = out_c + ");\n"
1253         out_c = out_c + "\treturn tag_ptr(res_ptr, true);\n"
1254         out_c = out_c + "}\n"
1255
1256         for var in flattened_field_vars:
1257             if not isinstance(var, ConvInfo):
1258                 out_java_trait += "\n\t/**\n"
1259                 out_java_trait += "\t * Gets the underlying " + var[1] + ".\n"
1260                 out_java_trait += "\t */\n"
1261                 underscore_name = ''.join('_' + c.lower() if c.isupper() else c for c in var[1]).strip('_')
1262                 out_java_trait += "\tpublic " + var[1] + " get_" + underscore_name + "() {\n"
1263                 out_java_trait += "\t\t" + var[1] + " res = new " + var[1] + "(null, bindings." + struct_name + "_get_" + var[1] + "(this.ptr));\n"
1264                 out_java_trait += "\t\tres.ptrs_to.add(this);\n"
1265                 out_java_trait += "\t\treturn res;\n"
1266                 out_java_trait += "\t}\n"
1267                 out_java_trait += "\n"
1268
1269                 out_java += "\tpublic static native long " + struct_name + "_get_" + var[1] + "(long arg);\n"
1270
1271                 out_c += "JNIEXPORT int64_t JNICALL Java_org_ldk_impl_bindings_" + struct_name + "_1get_1" + var[1] + "(JNIEnv *env, jclass clz, int64_t arg) {\n"
1272                 out_c += "\t" + struct_name + " *inp = (" + struct_name + " *)untag_ptr(arg);\n"
1273                 out_c += "\treturn tag_ptr(&inp->" + var[2] + ", false);\n"
1274                 out_c += "}\n"
1275
1276         return (out_java, out_java_trait, out_c)
1277
1278     def trait_struct_inc_refcnt(self, ty_info):
1279         base_conv = "\nif (" + ty_info.var_name + "_conv.free == " + ty_info.rust_obj + "_JCalls_free) {\n"
1280         base_conv = base_conv + "\t// If this_arg is a JCalls struct, then we need to increment the refcnt in it.\n"
1281         base_conv = base_conv + "\t" + ty_info.rust_obj + "_JCalls_cloned(&" + ty_info.var_name + "_conv);\n}"
1282         return base_conv
1283
1284     def map_complex_enum(self, struct_name, variant_list, camel_to_snake, enum_doc_comment):
1285         java_hu_type = struct_name.replace("LDK", "").replace("COption", "Option")
1286         out_java_enum = ""
1287         out_java = ""
1288         out_c = ""
1289
1290         out_java_enum += (self.hu_struct_file_prefix)
1291         out_java_enum += "\n/**\n * " + enum_doc_comment.replace("\n", "\n * ") + "\n */\n"
1292         out_java_enum += "@SuppressWarnings(\"unchecked\") // We correctly assign various generic arrays\n"
1293         out_java_enum += ("public class " + java_hu_type + " extends CommonBase {\n")
1294         out_java_enum += ("\tprivate " + java_hu_type + "(Object _dummy, long ptr) { super(ptr); }\n")
1295         out_java_enum += ("\t@Override @SuppressWarnings(\"deprecation\")\n")
1296         out_java_enum += ("\tprotected void finalize() throws Throwable {\n")
1297         out_java_enum += ("\t\tsuper.finalize();\n")
1298         out_java_enum += ("\t\tif (ptr != 0) { bindings." + struct_name.replace("LDK", "") + "_free(ptr); }\n")
1299         out_java_enum += ("\t}\n")
1300         out_java_enum += ("\tstatic " + java_hu_type + " constr_from_ptr(long ptr) {\n")
1301         out_java_enum += ("\t\tbindings." + struct_name + " raw_val = bindings." + struct_name + "_ref_from_ptr(ptr);\n")
1302         java_hu_subclasses = ""
1303
1304         init_meth_jty_strs = {}
1305
1306         out_java +=  ("\tpublic static class " + struct_name + " {\n")
1307         out_java +=  ("\t\tprivate " + struct_name + "() {}\n")
1308         for var in variant_list:
1309             out_java +=  ("\t\tpublic final static class " + var.var_name + " extends " + struct_name + " {\n")
1310             if var.var_docs is not None:
1311                 java_hu_subclasses += "\t/**\n\t * " + var.var_docs.replace("\n", "\n\t * ") + "\n\t */\n"
1312             java_hu_subclasses += "\tpublic final static class " + var.var_name + " extends " + java_hu_type + " {\n"
1313             out_java_enum += ("\t\tif (raw_val.getClass() == bindings." + struct_name + "." + var.var_name + ".class) {\n")
1314             out_java_enum += ("\t\t\treturn new " + var.var_name + "(ptr, (bindings." + struct_name + "." + var.var_name + ")raw_val);\n")
1315             init_meth_jty_str = ""
1316             init_meth_params = ""
1317             init_meth_body = ""
1318             hu_conv_body = ""
1319             for idx, (field_ty, field_docs) in enumerate(var.fields):
1320                 if idx > 0:
1321                     init_meth_params = init_meth_params + ", "
1322
1323                 java_ty = field_ty.java_ty
1324                 if field_ty.java_fn_ty_arg.startswith("L") and field_ty.java_fn_ty_arg.endswith(";"):
1325                     # If this is a simple enum, we have to reference it in the low-level bindings differently:
1326                     java_ty = field_ty.java_fn_ty_arg.strip("L;").replace("/", ".")
1327                 out_java += "\t\t\tpublic " + java_ty + " " + field_ty.arg_name + ";\n"
1328                 if field_docs is not None:
1329                     java_hu_subclasses += "\t\t/**\n\t\t * " + field_docs.replace("\n", "\n\t\t * ") + "\n\t\t*/\n"
1330                 java_hu_subclasses += "\t\t"
1331                 if field_ty.nullable:
1332                     java_hu_subclasses += "@Nullable "
1333                 java_hu_subclasses += "public final " + self.fully_qualified_hu_ty_path(field_ty) + " " + field_ty.arg_name + ";\n"
1334                 init_meth_params = init_meth_params + java_ty + " " + field_ty.arg_name
1335
1336                 init_meth_body = init_meth_body + "this." + field_ty.arg_name + " = " + field_ty.arg_name + "; "
1337                 if field_ty.to_hu_conv is not None:
1338                     hu_conv_body = hu_conv_body + "\t\t\t" + field_ty.java_ty + " " + field_ty.arg_name + " = obj." + field_ty.arg_name + ";\n"
1339                     hu_conv_body = hu_conv_body + "\t\t\t" + field_ty.to_hu_conv.replace("\n", "\n\t\t\t") + "\n"
1340                     hu_conv_body = hu_conv_body + "\t\t\tthis." + field_ty.arg_name + " = " + field_ty.to_hu_conv_name + ";\n"
1341                 else:
1342                     hu_conv_body = hu_conv_body + "\t\t\tthis." + field_ty.arg_name + " = obj." + field_ty.arg_name + ";\n"
1343                 init_meth_jty_str = init_meth_jty_str + field_ty.java_fn_ty_arg
1344             out_java +=  ("\t\t\t" + var.var_name + "(" + init_meth_params + ") { ")
1345             out_java +=  (init_meth_body)
1346             out_java +=  ("}\n")
1347             out_java += ("\t\t}\n")
1348             out_java_enum += ("\t\t}\n")
1349             java_hu_subclasses = java_hu_subclasses + "\t\tprivate " + var.var_name + "(long ptr, bindings." + struct_name + "." + var.var_name + " obj) {\n\t\t\tsuper(null, ptr);\n"
1350             java_hu_subclasses = java_hu_subclasses + hu_conv_body
1351             java_hu_subclasses = java_hu_subclasses + "\t\t}\n\t}\n"
1352             init_meth_jty_strs[var.var_name] = init_meth_jty_str
1353         out_java += ("\t\tstatic native void init();\n")
1354         out_java += ("\t}\n")
1355         out_java_enum += ("\t\tassert false; return null; // Unreachable without extending the (internal) bindings interface\n\t}\n\n")
1356         out_java_enum += (java_hu_subclasses)
1357         out_java += ("\tstatic { " + struct_name + ".init(); }\n")
1358         out_java += ("\tpublic static native " + struct_name + " " + struct_name + "_ref_from_ptr(long ptr);\n");
1359
1360         out_c += (self.c_complex_enum_pfx(struct_name, [x.var_name for x in variant_list], init_meth_jty_strs))
1361
1362         out_c += (self.c_fn_ty_pfx + self.c_complex_enum_pass_ty(struct_name) + " " + self.c_fn_name_define_pfx(struct_name + "_ref_from_ptr", True) + self.ptr_c_ty + " ptr) {\n")
1363         out_c += ("\t" + struct_name + " *obj = (" + struct_name + "*)untag_ptr(ptr);\n")
1364         out_c += ("\tswitch(obj->tag) {\n")
1365         for var in variant_list:
1366             out_c += ("\t\tcase " + struct_name + "_" + var.var_name + ": {\n")
1367             c_params = []
1368             for idx, (field_map, field_docs) in enumerate(var.fields):
1369                 if field_map.ret_conv is not None:
1370                     out_c += ("\t\t\t" + field_map.ret_conv[0].replace("\n", "\n\t\t\t"))
1371                     if var.tuple_variant:
1372                         out_c += "obj->" + camel_to_snake(var.var_name)
1373                     else:
1374                         out_c += "obj->" + camel_to_snake(var.var_name) + "." + field_map.arg_name
1375                     out_c += (field_map.ret_conv[1].replace("\n", "\n\t\t\t") + "\n")
1376                     c_params.append(field_map.ret_conv_name)
1377                 else:
1378                     if var.tuple_variant:
1379                         c_params.append("obj->" + camel_to_snake(var.var_name))
1380                     else:
1381                         c_params.append("obj->" + camel_to_snake(var.var_name) + "." + field_map.arg_name)
1382             out_c += ("\t\t\treturn " + self.c_constr_native_complex_enum(struct_name, var.var_name, c_params) + ";\n")
1383             out_c += ("\t\t}\n")
1384         out_c += ("\t\tdefault: abort();\n")
1385         out_c += ("\t}\n}\n")
1386         return (out_java, out_java_enum, out_c)
1387
1388     def map_opaque_struct(self, struct_name, struct_doc_comment):
1389         out_opaque_struct_human = ""
1390         out_opaque_struct_human += self.hu_struct_file_prefix
1391         out_opaque_struct_human += "\n/**\n * " + struct_doc_comment.replace("\n", "\n * ") + "\n */\n"
1392         out_opaque_struct_human += "@SuppressWarnings(\"unchecked\") // We correctly assign various generic arrays\n"
1393         hu_name = struct_name.replace("LDKC2Tuple", "TwoTuple").replace("LDKC3Tuple", "ThreeTuple").replace("LDK", "")
1394         out_opaque_struct_human += ("public class " + hu_name + " extends CommonBase")
1395         if struct_name.startswith("LDKLocked") or struct_name.startswith("LDKReadOnly"):
1396             out_opaque_struct_human += (" implements AutoCloseable")
1397         out_opaque_struct_human += (" {\n")
1398         out_opaque_struct_human += ("\t" + hu_name + "(Object _dummy, long ptr) { super(ptr); }\n")
1399         if struct_name.startswith("LDKLocked") or struct_name.startswith("LDKReadOnly"):
1400             out_opaque_struct_human += ("\t@Override public void close() {\n")
1401         else:
1402             out_opaque_struct_human += ("\t@Override @SuppressWarnings(\"deprecation\")\n")
1403             out_opaque_struct_human += ("\tprotected void finalize() throws Throwable {\n")
1404             out_opaque_struct_human += ("\t\tsuper.finalize();\n")
1405         out_opaque_struct_human += ("\t\tif (ptr != 0) { bindings." + struct_name.replace("LDK","") + "_free(ptr); }\n")
1406         out_opaque_struct_human += ("\t}\n\n")
1407         return out_opaque_struct_human
1408
1409     def map_tuple(self, struct_name):
1410         return self.map_opaque_struct(struct_name, "A Tuple")
1411
1412     def map_result(self, struct_name, res_map, err_map):
1413         human_ty = struct_name.replace("LDKCResult", "Result")
1414         java_hu_struct = ""
1415         java_hu_struct += self.hu_struct_file_prefix
1416         java_hu_struct += "public class " + human_ty + " extends CommonBase {\n"
1417         java_hu_struct += "\tprivate " + human_ty + "(Object _dummy, long ptr) { super(ptr); }\n"
1418         java_hu_struct += "\tprotected void finalize() throws Throwable {\n"
1419         java_hu_struct += "\t\tif (ptr != 0) { bindings." + struct_name.replace("LDK","") + "_free(ptr); } super.finalize();\n"
1420         java_hu_struct += "\t}\n\n"
1421         java_hu_struct += "\tstatic " + human_ty + " constr_from_ptr(long ptr) {\n"
1422         java_hu_struct += "\t\tif (bindings." + struct_name.replace("LDK", "") + "_is_ok(ptr)) {\n"
1423         java_hu_struct += "\t\t\treturn new " + human_ty + "_OK(null, ptr);\n"
1424         java_hu_struct += "\t\t} else {\n"
1425         java_hu_struct += "\t\t\treturn new " + human_ty + "_Err(null, ptr);\n"
1426         java_hu_struct += "\t\t}\n"
1427         java_hu_struct += "\t}\n"
1428
1429         java_hu_struct += "\tpublic static final class " + human_ty + "_OK extends " + human_ty + " {\n"
1430
1431         if res_map.java_hu_ty != "void":
1432             java_hu_struct += "\t\tpublic final " + res_map.java_hu_ty + " res;\n"
1433         java_hu_struct += "\t\tprivate " + human_ty + "_OK(Object _dummy, long ptr) {\n"
1434         java_hu_struct += "\t\t\tsuper(_dummy, ptr);\n"
1435         if res_map.java_hu_ty == "void":
1436             pass
1437         elif res_map.to_hu_conv is not None:
1438             java_hu_struct += "\t\t\t" + res_map.java_ty + " res = bindings." + struct_name.replace("LDK", "") + "_get_ok(ptr);\n"
1439             java_hu_struct += "\t\t\t" + res_map.to_hu_conv.replace("\n", "\n\t\t\t")
1440             java_hu_struct += "\n\t\t\tthis.res = " + res_map.to_hu_conv_name + ";\n"
1441         else:
1442             java_hu_struct += "\t\t\tthis.res = bindings." + struct_name.replace("LDK", "") + "_get_ok(ptr);\n"
1443         java_hu_struct += "\t\t}\n"
1444         java_hu_struct += "\t}\n\n"
1445
1446         java_hu_struct += "\tpublic static final class " + human_ty + "_Err extends " + human_ty + " {\n"
1447         if err_map.java_hu_ty != "void":
1448             java_hu_struct += "\t\tpublic final " + err_map.java_hu_ty + " err;\n"
1449         java_hu_struct += "\t\tprivate " + human_ty + "_Err(Object _dummy, long ptr) {\n"
1450         java_hu_struct += "\t\t\tsuper(_dummy, ptr);\n"
1451         if err_map.java_hu_ty == "void":
1452             pass
1453         elif err_map.to_hu_conv is not None:
1454             java_hu_struct += "\t\t\t" + err_map.java_ty + " err = bindings." + struct_name.replace("LDK", "") + "_get_err(ptr);\n"
1455             java_hu_struct += "\t\t\t" + err_map.to_hu_conv.replace("\n", "\n\t\t\t")
1456             java_hu_struct += "\n\t\t\tthis.err = " + err_map.to_hu_conv_name + ";\n"
1457         else:
1458             java_hu_struct += "\t\t\tthis.err = bindings." + struct_name.replace("LDK", "") + "_get_err(ptr);\n"
1459         java_hu_struct += "\t\t}\n"
1460
1461         java_hu_struct += "\t}\n\n"
1462         return java_hu_struct
1463
1464     def map_function(self, argument_types, c_call_string, method_name, meth_n, return_type_info, struct_meth, default_constructor_args, takes_self, takes_self_as_ref, args_known, type_mapping_generator, doc_comment):
1465         out_java = ""
1466         out_c = ""
1467         out_java_struct = None
1468
1469         out_java += ("\tpublic static native ")
1470         out_c += (self.c_fn_ty_pfx)
1471         out_c += (return_type_info.c_ty)
1472         out_java += (return_type_info.java_ty)
1473         if return_type_info.ret_conv is not None:
1474             ret_conv_pfx, ret_conv_sfx = return_type_info.ret_conv
1475         out_java += (" " + method_name + "(")
1476         have_args = len(argument_types) > 1 or (len(argument_types) > 0 and argument_types[0].c_ty != "void")
1477         out_c += (" " + self.c_fn_name_define_pfx(method_name, have_args))
1478
1479         for idx, arg_conv_info in enumerate(argument_types):
1480             if idx != 0:
1481                 out_java += (", ")
1482                 out_c += (", ")
1483             if arg_conv_info.c_ty != "void":
1484                 out_c += (arg_conv_info.c_ty + " " + arg_conv_info.arg_name)
1485                 out_java += (arg_conv_info.java_ty + " " + arg_conv_info.arg_name)
1486
1487         out_java_struct = ""
1488         extra_java_struct_out = ""
1489         if not args_known:
1490             out_java_struct += ("\t// Skipped " + method_name + "\n")
1491         else:
1492             if doc_comment is not None:
1493                 out_java_struct += "\t/**\n\t * " + doc_comment.replace("\n", "\n\t * ") + "\n\t */\n"
1494             if return_type_info.nullable:
1495                 out_java_struct += "\t@Nullable\n"
1496             if not takes_self:
1497                 if meth_n == "new":
1498                     out_java_struct += "\tpublic static " + return_type_info.java_hu_ty + " of("
1499                 elif meth_n == "default":
1500                     out_java_struct += "\tpublic static " + return_type_info.java_hu_ty + " with_default("
1501                 else:
1502                     out_java_struct += "\tpublic static " + return_type_info.java_hu_ty + " " + meth_n + "("
1503             elif meth_n == "clone_ptr" or (struct_meth.startswith("LDKCResult") and (meth_n == "get_ok" or meth_n == "get_err")):
1504                 out_java_struct += ("\t" + return_type_info.java_hu_ty + " " + meth_n + "(")
1505             else:
1506                 if meth_n == "hash" and return_type_info.java_hu_ty == "long":
1507                     extra_java_struct_out = "\t@Override public int hashCode() {\n"
1508                     extra_java_struct_out += "\t\treturn (int)this.hash();\n"
1509                     extra_java_struct_out += "\t}\n"
1510                 elif meth_n == "eq" and return_type_info.java_hu_ty == "boolean":
1511                     extra_java_struct_out = "\t@Override public boolean equals(Object o) {\n"
1512                     extra_java_struct_out += "\t\tif (!(o instanceof " + struct_meth + ")) return false;\n"
1513                     extra_java_struct_out += "\t\treturn this.eq((" + struct_meth + ")o);\n"
1514                     extra_java_struct_out += "\t}\n"
1515                 if meth_n == "wait":
1516                     meth_n = "wait_indefinite"
1517                 out_java_struct += ("\tpublic " + return_type_info.java_hu_ty + " " + meth_n + "(")
1518             for idx, arg in enumerate(argument_types):
1519                 if idx != 0:
1520                     if not takes_self or idx > 1:
1521                         out_java_struct += ", "
1522                 elif takes_self:
1523                     continue
1524                 if arg.java_ty != "void":
1525                     if arg.arg_name in default_constructor_args:
1526                         assert not arg.nullable
1527                         for explode_idx, explode_arg in enumerate(default_constructor_args[arg.arg_name]):
1528                             if explode_idx != 0:
1529                                 out_java_struct += (", ")
1530                             out_java_struct += (
1531                                 explode_arg.java_hu_ty + " " + arg.arg_name + "_" + explode_arg.arg_name)
1532                     else:
1533                         if arg.nullable:
1534                             out_java_struct += "@Nullable "
1535                         ty_string = self.fully_qualified_hu_ty_path(arg)
1536                         out_java_struct += ty_string + " " + arg.arg_name
1537         out_java += (");\n")
1538         out_c += (") {\n")
1539         if out_java_struct is not None:
1540             out_java_struct += (") {\n")
1541         for info in argument_types:
1542             if info.arg_conv is not None:
1543                 out_c += ("\t" + info.arg_conv.replace('\n', "\n\t") + "\n")
1544         if return_type_info.ret_conv is not None:
1545             out_c += ("\t" + ret_conv_pfx.replace('\n', '\n\t'))
1546         elif return_type_info.c_ty != "void":
1547             out_c += ("\t" + return_type_info.c_ty + " ret_val = ")
1548         else:
1549             out_c += ("\t")
1550         if c_call_string is None:
1551             out_c += (method_name + "(")
1552         else:
1553             out_c += (c_call_string)
1554         for idx, info in enumerate(argument_types):
1555             if info.arg_conv_name is not None:
1556                 if idx != 0:
1557                     out_c += (", ")
1558                 elif c_call_string is not None:
1559                     continue
1560                 out_c += (info.arg_conv_name)
1561         out_c += (")")
1562         if return_type_info.ret_conv is not None:
1563             out_c += (ret_conv_sfx.replace('\n', '\n\t'))
1564         else:
1565             out_c += (";")
1566         for info in argument_types:
1567             if info.arg_conv_cleanup is not None:
1568                 out_c += ("\n\t" + info.arg_conv_cleanup.replace("\n", "\n\t"))
1569         if return_type_info.ret_conv is not None:
1570             out_c += ("\n\treturn " + return_type_info.ret_conv_name + ";")
1571         elif return_type_info.c_ty != "void":
1572             out_c += ("\n\treturn ret_val;")
1573         out_c += ("\n}\n\n")
1574
1575         if args_known:
1576             out_java_struct += ("\t\t")
1577             if return_type_info.java_ty != "void":
1578                 out_java_struct += (return_type_info.java_ty + " ret = ")
1579             out_java_struct += ("bindings." + method_name + "(")
1580             for idx, info in enumerate(argument_types):
1581                 if idx != 0:
1582                     out_java_struct += (", ")
1583                 if idx == 0 and takes_self:
1584                     out_java_struct += ("this.ptr")
1585                 elif info.arg_name in default_constructor_args:
1586                     out_java_struct += ("bindings." + info.java_hu_ty + "_new(")
1587                     for explode_idx, explode_arg in enumerate(default_constructor_args[info.arg_name]):
1588                         if explode_idx != 0:
1589                             out_java_struct += (", ")
1590                         expl_arg_name = info.arg_name + "_" + explode_arg.arg_name
1591                         if explode_arg.from_hu_conv is not None:
1592                             out_java_struct += (
1593                                 explode_arg.from_hu_conv[0].replace(explode_arg.arg_name, expl_arg_name))
1594                         else:
1595                             out_java_struct += (expl_arg_name)
1596                     out_java_struct += (")")
1597                 elif info.from_hu_conv is not None:
1598                     out_java_struct += (info.from_hu_conv[0])
1599                 else:
1600                     out_java_struct += (info.arg_name)
1601             out_java_struct += (");\n")
1602
1603             # This is completely nuts. The OpenJDK JRE JIT will optimize out a object which is on
1604             # the stack, calling its finalizer immediately even if member methods are *actively
1605             # executing* on the same object, as long as said object is on the stack. There is no
1606             # concrete specification for when the optimizer is allowed to do this, and when it is
1607             # not, so there is absolutely no way to be certain that this fix suffices.
1608             #
1609             # Instead, the "Java Language Specification" says only that an object is reachable
1610             # (i.e. will not yet be finalized) if it "can be accessed in any potential continuing
1611             # computation from any live thread". To any sensible reader this would mean actively
1612             # executing a member function on an object would make it not eligible for finalization.
1613             # But, no, dear reader, this statement does not say that. Well, okay, it says that,
1614             # very explicitly in fact, but those are just, like, words, man.
1615             #
1616             # In the seemingly non-normative text further down, a few examples of things the
1617             # optimizer can do are given, including "if the values in an object's fields are
1618             # stored in registers[, t]he may then access the registers instead of the object, and
1619             # never access the object again[, implying] that the object is garbage". This appears
1620             # to fully contradict both the above statement, the API documentation in java.lang.ref
1621             # regarding when a reference is "strongly reachable", and basic common sense. There is
1622             # no concrete set of limitations stated, however, seemingly implying the JIT could
1623             # decide your code would run faster by simply garbage collecting everything
1624             # immediately, ensuring your code finishes soon, just by SEGFAULT. Thus, we're really
1625             # entirely flying blind here. We add some fences and hope that its sufficient, but
1626             # with no specification to rely on, we cannot be certain of anything.
1627             #
1628             # TL;DR: The Java Language "Specification" provides no real guarantees on when an
1629             # object will be considered available for garbage collection once the JIT kicks in, so
1630             # we put in some fences and hope to god the JIT doesn't get smarter/more broken.
1631             for idx, info in enumerate(argument_types):
1632                 if idx == 0 and takes_self:
1633                     out_java_struct += ("\t\tReference.reachabilityFence(this);\n")
1634                 elif info.arg_name in default_constructor_args:
1635                     for explode_idx, explode_arg in enumerate(default_constructor_args[info.arg_name]):
1636                         expl_arg_name = info.arg_name + "_" + explode_arg.arg_name
1637                         out_java_struct += ("\t\tReference.reachabilityFence(" + expl_arg_name + ");\n")
1638                 elif info.c_ty != "void":
1639                     out_java_struct += ("\t\tReference.reachabilityFence(" + info.arg_name + ");\n")
1640
1641             if return_type_info.java_ty == "long" and return_type_info.java_hu_ty != "long":
1642                 out_java_struct += "\t\tif (ret >= 0 && ret <= 4096) { return null; }\n"
1643
1644             if return_type_info.to_hu_conv is not None:
1645                 if not takes_self:
1646                     out_java_struct += ("\t\t" + return_type_info.to_hu_conv.replace("\n", "\n\t\t").replace("this",
1647                                                                                                                return_type_info.to_hu_conv_name) + "\n")
1648                 else:
1649                     out_java_struct += ("\t\t" + return_type_info.to_hu_conv.replace("\n", "\n\t\t") + "\n")
1650
1651             for idx, info in enumerate(argument_types):
1652                 if idx == 0 and takes_self:
1653                     pass
1654                 elif info.arg_name in default_constructor_args:
1655                     for explode_arg in default_constructor_args[info.arg_name]:
1656                         expl_arg_name = info.arg_name + "_" + explode_arg.arg_name
1657                         if explode_arg.from_hu_conv is not None and return_type_info.to_hu_conv_name:
1658                             out_java_struct += ("\t\t" + explode_arg.from_hu_conv[1].replace(explode_arg.arg_name,
1659                                                                                                expl_arg_name).replace(
1660                                 "this", return_type_info.to_hu_conv_name) + ";\n")
1661                 elif info.from_hu_conv is not None and info.from_hu_conv[1] != "":
1662                     if not takes_self and return_type_info.to_hu_conv_name is not None:
1663                         out_java_struct += (
1664                             "\t\t" + info.from_hu_conv[1].replace("this", return_type_info.to_hu_conv_name).replace("\n", "\n\t\t") + ";\n")
1665                     else:
1666                         out_java_struct += ("\t\t" + info.from_hu_conv[1].replace("\n", "\n\t\t") + ";\n")
1667
1668             if takes_self and not takes_self_as_ref:
1669                 out_java_struct += "\t\t" + argument_types[0].from_hu_conv[1].replace("\n", "\n\t\t").replace("this_arg", "this") + ";\n"
1670             if return_type_info.to_hu_conv_name is not None:
1671                 out_java_struct += ("\t\treturn " + return_type_info.to_hu_conv_name + ";\n")
1672             elif return_type_info.java_ty != "void" and return_type_info.rust_obj != "LDK" + struct_meth:
1673                 out_java_struct += ("\t\treturn ret;\n")
1674             out_java_struct += ("\t}\n\n")
1675
1676         return (out_java, out_c, out_java_struct + extra_java_struct_out)
1677
1678     def cleanup(self):
1679         pass