Update CI references to 0.0.122
[ldk-java] / genbindings.py
index 8b067f72a8d27c36840e53089be0eaaaeee9c375..3c79bb8fa94789fd245dd4e6f6891442ac0d62d7 100755 (executable)
@@ -1,8 +1,8 @@
 #!/usr/bin/env python3
 import os, sys, re, subprocess
 
-if len(sys.argv) < 7:
-    print("USAGE: /path/to/lightning.h /path/to/bindings/output /path/to/bindings/ /path/to/bindings/output.c debug lang")
+if len(sys.argv) < 8:
+    print("USAGE: /path/to/lightning.h /path/to/bindings/output /path/to/bindings/ /path/to/bindings/output.c debug lang target-tuple")
     sys.exit(1)
 
 if sys.argv[5] == "false":
@@ -20,17 +20,33 @@ if sys.argv[6] == "java" or sys.argv[6] == "android":
     target = java_strings.Target.JAVA
     if sys.argv[6] == "android":
         target = java_strings.Target.ANDROID
+    if "apple" in sys.argv[8]:
+        target = java_strings.Target.MACOS
 elif sys.argv[6] == "typescript":
     import typescript_strings
     from typescript_strings import Consts
     target = typescript_strings.Target.NODEJS
     if len(sys.argv) == 8 and sys.argv[7] == 'browser':
         target = typescript_strings.Target.BROWSER
+elif sys.argv[6].startswith("c_sharp"):
+    import csharp_strings
+    from csharp_strings import Consts
+    if sys.argv[6] == "c_sharp-win":
+        target = csharp_strings.Target.WINDOWS
+    elif sys.argv[6] == "c_sharp-darwin":
+        target = csharp_strings.Target.PTHREAD
+    elif sys.argv[6] == "c_sharp-linux":
+        target = csharp_strings.Target.LINUX
+    else:
+        assert False
+elif sys.argv[6] == "python":
+    import python_strings
+    from python_strings import Consts
+    target = python_strings.Target.PYTHON
 else:
-    print("Only java or typescript can be set for lang")
+    print("Only java, typescript, python, or c_sharp can be set for lang")
     sys.exit(1)
 
-
 consts = Consts(DEBUG, target=target, outdir=sys.argv[4])
 
 local_git_version = os.getenv("LDK_GARBAGECOLLECTED_GIT_OVERRIDE")
@@ -129,11 +145,21 @@ def java_c_types(fn_arg, ret_arr_len):
         assert var_is_arr_regex.match(fn_arg[8:])
         rust_obj = "LDKThirtyTwoBytes"
         arr_access = "data"
-    elif fn_arg.startswith("LDKTxid"):
-        fn_arg = "uint8_t (*" + fn_arg[8:] + ")[32]"
-        assert var_is_arr_regex.match(fn_arg[8:])
-        rust_obj = "LDKThirtyTwoBytes"
+    elif fn_arg.startswith("LDKThirtyTwoU16s"):
+        fn_arg = "uint16_t (*" + fn_arg[17:] + ")[32]"
+        assert var_is_arr_regex.match(fn_arg[9:])
+        rust_obj = "LDKThirtyTwoU16s"
         arr_access = "data"
+    elif fn_arg.startswith("LDKU128"):
+        if fn_arg == "LDKU128":
+            fn_arg = "LDKU128 arg"
+        if fn_arg.startswith("LDKU128*") or fn_arg.startswith("LDKU128 *"):
+            fn_arg = "uint8_t (" + fn_arg[8:] + ")[16]"
+        else:
+            fn_arg = "uint8_t (*" + fn_arg[8:] + ")[16]"
+        assert var_is_arr_regex.match(fn_arg[8:])
+        rust_obj = "LDKU128"
+        arr_access = "le_bytes"
     elif fn_arg.startswith("LDKPublicKey"):
         fn_arg = "uint8_t (*" + fn_arg[13:] + ")[33]"
         assert var_is_arr_regex.match(fn_arg[8:])
@@ -144,10 +170,15 @@ def java_c_types(fn_arg, ret_arr_len):
         assert var_is_arr_regex.match(fn_arg[8:])
         rust_obj = "LDKSecretKey"
         arr_access = "bytes"
-    elif fn_arg.startswith("LDKSignature"):
-        fn_arg = "uint8_t (*" + fn_arg[13:] + ")[64]"
+    elif fn_arg.startswith("LDKECDSASignature"):
+        fn_arg = "uint8_t (*" + fn_arg[18:] + ")[64]"
+        assert var_is_arr_regex.match(fn_arg[8:])
+        rust_obj = "LDKECDSASignature"
+        arr_access = "compact_form"
+    elif fn_arg.startswith("LDKSchnorrSignature"):
+        fn_arg = "uint8_t (*" + fn_arg[20:] + ")[64]"
         assert var_is_arr_regex.match(fn_arg[8:])
-        rust_obj = "LDKSignature"
+        rust_obj = "LDKSchnorrSignature"
         arr_access = "compact_form"
     elif fn_arg.startswith("LDKRecoverableSignature"):
         fn_arg = "uint8_t (*" + fn_arg[24:] + ")[68]"
@@ -194,6 +225,17 @@ def java_c_types(fn_arg, ret_arr_len):
         rust_obj = "LDKTransaction"
         assert var_is_arr_regex.match(fn_arg[8:])
         arr_access = "data"
+    elif fn_arg.startswith("LDKTransactionOutputs "):
+        fn_arg = "C2Tuple_ThirtyTwoBytesCVec_C2Tuple_u32TxOutZZZ"
+        rust_obj = "C2Tuple_ThirtyTwoBytesCVec_C2Tuple_u32TxOutZZZ"
+    elif fn_arg.startswith("LDKWitness ") or fn_arg == "LDKWitness":
+        if len(fn_arg) > 12 and fn_arg[11] == "*":
+            fn_arg = "uint8_t (" + fn_arg[11:] + ")[datalen]"
+        else:
+            fn_arg = "uint8_t (*" + fn_arg[11:] + ")[datalen]"
+        rust_obj = "LDKWitness"
+        assert var_is_arr_regex.match(fn_arg[8:])
+        arr_access = "data"
     elif fn_arg.startswith("LDKCVec_"):
         is_ptr = False
         if "*" in fn_arg:
@@ -239,7 +281,7 @@ def java_c_types(fn_arg, ret_arr_len):
         fn_arg = fn_arg[4:].strip()
         is_primitive = True
     elif fn_arg.startswith("bool"):
-        java_ty = "boolean"
+        java_ty = consts.c_type_map['bool'][0]
         c_ty = "jboolean"
         fn_ty_arg = "Z"
         arr_ty = "bool"
@@ -253,14 +295,19 @@ def java_c_types(fn_arg, ret_arr_len):
         arr_ty = "uint8_t"
         fn_arg = fn_arg[7:].strip()
         is_primitive = True
-    elif fn_arg.startswith("LDKu5"):
+    elif fn_arg.startswith("LDKU5") or fn_arg.startswith("LDKWitnessVersion"):
         java_ty = consts.c_type_map['uint8_t'][0]
-        java_hu_ty = "UInt5"
-        rust_obj = "LDKu5"
+        if fn_arg.startswith("LDKU5"):
+            java_hu_ty = "UInt5"
+            rust_obj = "LDKU5"
+            fn_arg = fn_arg[6:].strip()
+        else:
+            java_hu_ty = "WitnessVersion"
+            rust_obj = "LDKWitnessVersion"
+            fn_arg = fn_arg[18:].strip()
         c_ty = "int8_t"
         arr_ty = "uint8_t"
         fn_ty_arg = "B"
-        fn_arg = fn_arg[6:].strip()
     elif fn_arg.startswith("uint16_t"):
         mapped_type = consts.c_type_map['uint16_t']
         java_ty = mapped_type[0]
@@ -277,6 +324,22 @@ def java_c_types(fn_arg, ret_arr_len):
         fn_ty_arg = "I"
         fn_arg = fn_arg[8:].strip()
         is_primitive = True
+    elif fn_arg.startswith("int64_t"):
+        mapped_type = consts.c_type_map['int64_t']
+        java_ty = mapped_type[0]
+        c_ty = "int64_t"
+        arr_ty = "int64_t"
+        fn_ty_arg = "J"
+        fn_arg = fn_arg[7:].strip()
+        is_primitive = True
+    elif fn_arg.startswith("double"):
+        mapped_type = consts.c_type_map['double']
+        java_ty = mapped_type[0]
+        c_ty = "double"
+        arr_ty = "double"
+        fn_ty_arg = "D"
+        fn_arg = fn_arg[6:].strip()
+        is_primitive = True
     elif fn_arg.startswith("uint64_t") or fn_arg.startswith("uintptr_t"):
         # TODO: uintptr_t is arch-dependent :(
         mapped_type = consts.c_type_map['uint64_t']
@@ -287,8 +350,8 @@ def java_c_types(fn_arg, ret_arr_len):
             arr_ty = "uint64_t"
             fn_arg = fn_arg[8:].strip()
         else:
-            java_ty = consts.ptr_native_ty
-            c_ty = "int64_t"
+            java_ty = consts.usize_native_ty
+            c_ty = consts.usize_c_ty
             arr_ty = "uintptr_t"
             rust_obj = "uintptr_t"
             fn_arg = fn_arg[9:].strip()
@@ -300,16 +363,27 @@ def java_c_types(fn_arg, ret_arr_len):
         arr_ty = "LDKStr"
         fn_ty_arg = "Ljava/lang/String;"
         fn_arg = fn_arg[6:].strip()
-    elif fn_arg.startswith("LDKStr"):
+    elif fn_arg.startswith("LDKStr") or fn_arg.startswith("LDKAddress"):
         rust_obj = "LDKStr"
         arr_ty = "LDKStr"
         java_ty = consts.java_type_map["String"]
         java_hu_ty = consts.java_hu_type_map["String"]
         c_ty = "jstring"
         fn_ty_arg = "Ljava/lang/String;"
-        fn_arg = fn_arg[6:].strip()
+        if fn_arg.startswith("LDKAddress"):
+            fn_arg = fn_arg[10:].strip()
+        else:
+            fn_arg = fn_arg[6:].strip()
         arr_access = "chars"
         arr_len = "len"
+    elif fn_arg.startswith("LDKError ") or fn_arg == "LDKError":
+        java_ty = consts.c_type_map['uint32_t'][0]
+        java_hu_ty = "UnqualifiedError"
+        rust_obj = "LDKError"
+        c_ty = "int32_t"
+        arr_ty = "uint32_t"
+        fn_ty_arg = "I"
+        fn_arg = fn_arg[8:].strip()
     else:
         ma = var_ty_regex.match(fn_arg)
         arr_ty = ma.group(1).strip()
@@ -317,7 +391,7 @@ def java_c_types(fn_arg, ret_arr_len):
             assert ma.group(1).strip().startswith("LDK")
             java_ty = ma.group(1).strip()[3:]
             java_hu_ty = java_ty
-            c_ty = consts.result_c_ty
+            c_ty = consts.unitary_enum_c_ty
             fn_ty_arg = "Lorg/ldk/enums/" + java_ty + ";"
             fn_arg = ma.group(2).strip()
             rust_obj = ma.group(1).strip()
@@ -358,6 +432,8 @@ def java_c_types(fn_arg, ret_arr_len):
         else:
             java_ty = java_ty + "[]"
             java_hu_ty = java_ty
+        if rust_obj == "LDKU128":
+            java_hu_ty = consts.u128_native_ty
         c_ty = c_ty + "Array"
 
         subty = java_c_types(arr_ty, None)
@@ -411,7 +487,66 @@ with open(sys.argv[1]) as in_h:
 
 # Define some manual clones...
 clone_fns.add("ThirtyTwoBytes_clone")
-write_c("static inline struct LDKThirtyTwoBytes ThirtyTwoBytes_clone(const struct LDKThirtyTwoBytes *orig) { struct LDKThirtyTwoBytes ret; memcpy(ret.data, orig->data, 32); return ret; }\n")
+write_c("static inline struct LDKThirtyTwoBytes ThirtyTwoBytes_clone(const struct LDKThirtyTwoBytes *orig) { struct LDKThirtyTwoBytes ret; memcpy(ret.data, orig->data, 32); return ret; }\n\n")
+
+
+write_c("static inline void* untag_ptr(uint64_t ptr) {\n")
+write_c("\tif (ptr < 4096) return (void*)ptr;\n")
+write_c("\tif (sizeof(void*) == 4) {\n")
+write_c("\t\t// For 32-bit systems, store pointers as 64-bit ints and use the 31st bit\n")
+write_c("\t\treturn (void*)(uintptr_t)ptr;\n")
+write_c("\t} else {\n")
+write_c("\t\t// For 64-bit systems, assume the top byte is used for tagging, then\n")
+write_c("\t\t// use bit 9 ^ bit 10.\n")
+write_c("\t\tuint64_t tenth_bit = (((uintptr_t)ptr) & (1ULL << 54)) >> 54;\n")
+write_c("\t\tuintptr_t p = (ptr & ~(1ULL << 55)) | (tenth_bit << 55);\n")
+write_c("#ifdef LDK_DEBUG_BUILD\n")
+write_c("\t\t// On debug builds we also use the 11th bit as a debug flag\n")
+write_c("\t\tuintptr_t eleventh_bit = (((uintptr_t)ptr) & (1ULL << 53)) >> 53;\n")
+write_c("\t\tCHECK(tenth_bit != eleventh_bit);\n")
+write_c("\t\tp ^= 1ULL << 53;\n")
+write_c("#endif\n")
+write_c("\t\treturn (void*)p;\n")
+write_c("\t}\n")
+write_c("}\n")
+
+write_c("static inline bool ptr_is_owned(uint64_t ptr) {\n")
+write_c("\tif(ptr < 4096) return true;\n")
+write_c("\tif (sizeof(void*) == 4) {\n")
+write_c("\t\treturn ptr & (1ULL << 32);\n")
+write_c("\t} else {\n")
+write_c("\t\tuintptr_t ninth_bit = (((uintptr_t)ptr) & (1ULL << 55)) >> 55;\n")
+write_c("\t\tuintptr_t tenth_bit = (((uintptr_t)ptr) & (1ULL << 54)) >> 54;\n")
+write_c("#ifdef LDK_DEBUG_BUILD\n")
+write_c("\t\t// On debug builds we also use the 11th bit as a debug flag\n")
+write_c("\t\tuintptr_t eleventh_bit = (((uintptr_t)ptr) & (1ULL << 53)) >> 53;\n")
+write_c("\t\tCHECK(tenth_bit != eleventh_bit);\n")
+write_c("#endif\n")
+write_c("\t\treturn (ninth_bit ^ tenth_bit) ? true : false;\n")
+write_c("\t}\n")
+write_c("}\n")
+
+write_c("static inline uint64_t tag_ptr(const void* ptr, bool is_owned) {\n")
+write_c("\tif ((uintptr_t)ptr < 4096) return (uint64_t)ptr;\n")
+write_c("\tif (sizeof(void*) == 4) {\n")
+write_c("\t\treturn (((uint64_t)ptr) | ((is_owned ? 1ULL : 0) << 32));\n")
+write_c("\t} else {\n")
+write_c("\t\tCHECK(sizeof(uintptr_t) == 8);\n")
+write_c("\t\tuintptr_t tenth_bit = (((uintptr_t)ptr) & (1ULL << 54)) >> 54;\n")
+write_c("\t\tuintptr_t t = (((uintptr_t)ptr) | (((is_owned ? 1ULL : 0ULL) ^ tenth_bit) << 55));\n")
+write_c("#ifdef LDK_DEBUG_BUILD\n")
+write_c("\t\tuintptr_t ninth_bit = (((uintptr_t)ptr) & (1ULL << 55)) >> 55;\n")
+write_c("\t\tuintptr_t eleventh_bit = (((uintptr_t)ptr) & (1ULL << 53)) >> 53;\n")
+write_c("\t\tCHECK(ninth_bit == tenth_bit);\n")
+write_c("\t\tCHECK(ninth_bit == eleventh_bit);\n")
+write_c("\t\tt ^= 1ULL << 53;\n")
+write_c("#endif\n")
+write_c("\t\tCHECK(ptr_is_owned(t) == is_owned);\n")
+write_c("\t\tCHECK(untag_ptr(t) == ptr);\n")
+#write_c("\t\tCHECK(untag_ptr((uintptr_t)untag_ptr(t)) == ptr);\n")
+write_c("\t\treturn t;\n")
+write_c("\t}\n")
+write_c("}\n\n")
 
 java_c_types_none_allowed = False # C structs created by cbindgen are declared in dependency order
 
@@ -457,19 +592,21 @@ with open(sys.argv[1]) as in_h, open(f"{sys.argv[2]}/bindings{consts.file_ext}",
             return_type_info = type_mapping_generator.map_type(method_return_type.strip() + " ret", True, ret_arr_len, False, force_holds_ref)
 
         if method_name.endswith("_clone") and expected_struct not in unitary_enums:
-            meth_line = "uintptr_t " + expected_struct.replace("LDK", "") + "_clone_ptr(" + expected_struct + " *NONNULL_PTR arg)"
+            # LDKWitness is mapped as an array, so no need to implement clone
+            if expected_struct == "LDKWitness":
+                return
+            meth_line = "uint64_t " + expected_struct.replace("LDK", "") + "_clone_ptr(" + expected_struct + " *NONNULL_PTR arg)"
             write_c("static inline " + meth_line + " {\n")
             write_c("\t" + return_type_info.ret_conv[0].replace("\n", "\n\t"))
             write_c(method_name + "(arg)")
-            write_c(return_type_info.ret_conv[1])
+            write_c(return_type_info.ret_conv[1].replace("\n", "\n\t"))
             write_c("\n\treturn " + return_type_info.ret_conv_name + ";\n}\n")
-            map_fn(meth_line + ";\n", re.compile("(uintptr_t) ([A-Za-z_0-9]*)\((.*)\)").match(meth_line), None, None, None)
+            map_fn(meth_line + ";\n", re.compile("(uint64_t) ([A-Za-z_0-9]*)\((.*)\)").match(meth_line), None, None, None)
 
         argument_types = []
         default_constructor_args = {}
         takes_self = False
         takes_self_ptr = False
-        args_known = True
 
         for argument_index, argument in enumerate(method_arguments):
             arg_ty = type_mapping_generator.java_c_types(argument, None)
@@ -481,7 +618,7 @@ with open(sys.argv[1]) as in_h, open(f"{sys.argv[2]}/bindings{consts.file_ext}",
                     takes_self_ptr = True
             elif arg_ty.var_name in params_nullable:
                 argument_conversion_info = type_mapping_generator.map_type_with_info(arg_ty, False, None, is_free, True, True)
-                if argument_conversion_info.arg_conv is not None and "Warning" in argument_conversion_info.arg_conv:
+                if argument_conversion_info.arg_conv is not None and "WARNING" in argument_conversion_info.arg_conv:
                     arg_ty_info = java_c_types(argument, None)
                     print("WARNING: Remapping argument " + arg_ty_info.var_name + " of function " + method_name + " to a reference")
                     print("    The argument appears to require a move, or not clonable, and is nullable.")
@@ -496,20 +633,19 @@ with open(sys.argv[1]) as in_h, open(f"{sys.argv[2]}/bindings{consts.file_ext}",
                     arg_ty_info.requires_clone = False
                     argument_conversion_info = type_mapping_generator.map_type_with_info(arg_ty_info, False, None, is_free, True, True)
                     assert argument_conversion_info.nullable
-                    assert argument_conversion_info.arg_conv is not None and "Warning" not in argument_conversion_info.arg_conv
+                    assert argument_conversion_info.arg_conv is not None and "WARNING" not in argument_conversion_info.arg_conv
             else:
                 argument_conversion_info = type_mapping_generator.map_type_with_info(arg_ty, False, None, is_free, True, False)
 
-            if argument_conversion_info.arg_conv is not None and "Warning" in argument_conversion_info.arg_conv:
+            if argument_conversion_info.arg_conv is not None and "WARNING" in argument_conversion_info.arg_conv:
                 if argument_conversion_info.rust_obj in constructor_fns:
                     assert not is_free
-                    for explode_arg in constructor_fns[argument_conversion_info.rust_obj].split(','):
+                    for explode_idx, explode_arg in enumerate(constructor_fns[argument_conversion_info.rust_obj].split(',')):
                         explode_arg_conv = type_mapping_generator.map_type(explode_arg, False, None, False, True)
+                        if explode_idx == 0 and explode_arg_conv.c_ty == "void":
+                            continue # (void) is C lingo for "no arguments)
                         if explode_arg_conv.c_ty == "void":
-                            # We actually want to handle this case, but for now its only used in NetGraphMsgHandler::new()
-                            # which ends up resulting in a redundant constructor - both without arguments for the NetworkGraph.
-                            args_known = False
-                            pass
+                            assert False
                         if not argument_conversion_info.arg_name in default_constructor_args:
                             default_constructor_args[argument_conversion_info.arg_name] = []
                         default_constructor_args[argument_conversion_info.arg_name].append(explode_arg_conv)
@@ -525,7 +661,8 @@ with open(sys.argv[1]) as in_h, open(f"{sys.argv[2]}/bindings{consts.file_ext}",
             expected_struct in complex_enums or expected_struct in complex_enums or
             expected_struct in result_types or expected_struct in tuple_types) and not is_free
         impl_on_utils = not impl_on_struct and (not is_free and not method_name.endswith("_clone") and
-            not method_name.startswith("TxOut") and
+            not method_name.startswith("TxOut") and not method_name.startswith("TxIn") and
+            not method_name.startswith("BigEndianScalar") and not method_name.startswith("WitnessProgram") and
             not method_name.startswith("_") and
             method_name != "check_platform" and method_name != "Result_read" and
             not expected_struct in unitary_enums and
@@ -543,6 +680,7 @@ with open(sys.argv[1]) as in_h, open(f"{sys.argv[2]}/bindings{consts.file_ext}",
                         arg.from_hu_conv = (arg.from_hu_conv[0], "")
 
         out_java.write("\t// " + line)
+        args_known = True # We no longer ever set this to false
         (out_java_delta, out_c_delta, out_java_struct_delta) = \
             consts.map_function(argument_types, c_call_string, method_name, struct_meth_name, return_type_info, struct_meth, default_constructor_args, takes_self, takes_self_ptr, args_known, type_mapping_generator, doc_comment)
         out_java.write(out_java_delta)
@@ -552,7 +690,7 @@ with open(sys.argv[1]) as in_h, open(f"{sys.argv[2]}/bindings{consts.file_ext}",
             assert return_type_info.c_ty == "void"
             write_c(consts.c_fn_ty_pfx + "void " + consts.c_fn_name_define_pfx(method_name, True) + argument_types[0].c_ty + " " + argument_types[0].ty_info.var_name + ") {\n")
             if argument_types[0].ty_info.passed_as_ptr and not argument_types[0].ty_info.rust_obj in opaque_structs:
-                write_c("\tif ((" + argument_types[0].ty_info.var_name + " & 1) != 0) return;\n")
+                write_c("\tif (!ptr_is_owned(" + argument_types[0].ty_info.var_name + ")) return;\n")
 
             for info in argument_types:
                 if info.arg_conv is not None:
@@ -630,7 +768,13 @@ with open(sys.argv[1]) as in_h, open(f"{sys.argv[2]}/bindings{consts.file_ext}",
                 elif camel_to_snake(variant_name) in inline_enum_variants:
                     # TODO: If we ever have a rust enum Variant(Option<Struct>) we need to pipe
                     # docs through to there, and then potentially mark the field nullable.
-                    mapped = type_mapping_generator.map_type(inline_enum_variants[camel_to_snake(variant_name)] + " " + camel_to_snake(variant_name), False, None, False, True)
+                    (variant_info, variant_field_docs) = inline_enum_variants[camel_to_snake(variant_name)]
+                    variant_ty_text = variant_info + " " + camel_to_snake(variant_name)
+                    variant_ty_info = type_mapping_generator.java_c_types(variant_ty_text, None)
+                    if variant_field_docs is not None and doc_to_field_nullable(variant_field_docs):
+                        mapped = type_mapping_generator.map_type_with_info(variant_ty_info, False, None, False, True, True)
+                    else:
+                        mapped = type_mapping_generator.map_type_with_info(variant_ty_info, False, None, False, True, False)
                     contains_trait |= mapped.ty_info.contains_trait
                     fields.append((mapped, None))
                     enum_variants.append(ComplexEnumVariantInfo(variant_name, variant_docs, fields, True))
@@ -652,13 +796,20 @@ with open(sys.argv[1]) as in_h, open(f"{sys.argv[2]}/bindings{consts.file_ext}",
             for var_line in field_var_lines:
                 if var_line.group(1) in trait_structs:
                     field_var_convs.append((var_line.group(1), var_line.group(2), trait_structs[var_line.group(1)]))
-                    flattened_field_var_convs.append((var_line.group(1), var_line.group(2), ))
-                    flattened_field_var_convs.extend(trait_structs[var_line.group(1)])
+                    flattened_field_var_convs.append((var_line.group(1), var_line.group(2), var_line.group(2)))
+                    for field_var in trait_structs[var_line.group(1)]:
+                        if isinstance(field_var, ConvInfo):
+                            flattened_field_var_convs.append(field_var)
+                        else:
+                            path = var_line.group(2)
+                            if len(field_var) > 2:
+                                path = var_line.group(2) + "." + field_var[2]
+                            flattened_field_var_convs.append((field_var[0], field_var[1], path))
                 else:
                     mapped = type_mapping_generator.map_type(var_line.group(1) + " " + var_line.group(2), False, None, False, False)
                     field_var_convs.append(mapped)
                     flattened_field_var_convs.append(mapped)
-            trait_structs[struct_name] = field_var_convs
+            trait_structs[struct_name] = flattened_field_var_convs
 
             field_fns = []
             for fn_docs, fn_line in trait_fn_lines:
@@ -668,9 +819,8 @@ with open(sys.argv[1]) as in_h, open(f"{sys.argv[2]}/bindings{consts.file_ext}",
                 else:
                     (nullable_params, ret_nullable) = doc_to_params_ret_nullable(fn_docs)
                     if ret_nullable:
-                        assert False # This isn't yet handled on the Java side
-                        ret_ty_info.nullable = True
                         ret_ty_info = type_mapping_generator.map_nullable_type(fn_line.group(2).strip() + " ret", True, None, False, False)
+                        ret_ty_info.nullable = True
                     else:
                         ret_ty_info = type_mapping_generator.map_type(fn_line.group(2).strip() + " ret", True, None, False, False)
                     is_const = fn_line.group(4) is not None
@@ -728,7 +878,13 @@ with open(sys.argv[1]) as in_h, open(f"{sys.argv[2]}/bindings{consts.file_ext}",
         owned_fn_defn = field_decl + " " + struct_name.replace("LDK", "") + "_get_" + field_name + "(" + struct_name + " *NONNULL_PTR owner)"
 
         holds_ref = False
-        if field_ty.rust_obj is not None and field_ty.rust_obj.replace("LDK", "") + "_clone" in clone_fns:
+        if field_ty.rust_obj is not None and field_ty.rust_obj in opaque_structs:
+            fn_defn = owned_fn_defn
+            write_c("static inline " + fn_defn + "{\n")
+            write_c("\t" + field_ty.rust_obj + " ret = " + accessor[0] + "owner" + accessor[1] + ";\n")
+            write_c("\tret.is_owned = false;\n")
+            write_c("\treturn ret;\n")
+        elif field_ty.rust_obj is not None and field_ty.rust_obj.replace("LDK", "") + "_clone" in clone_fns:
             fn_defn = owned_fn_defn
             write_c("static inline " + fn_defn + "{\n")
             if check_sfx is not None:
@@ -904,7 +1060,7 @@ with open(sys.argv[1]) as in_h, open(f"{sys.argv[2]}/bindings{consts.file_ext}",
                         write_c("\tmemcpy(ret.data, orig->data, sizeof(" + ty_info.c_ty + ") * ret.datalen);\n")
                         write_c("\treturn ret;\n}\n")
                     elif (ty_info.rust_obj.replace("LDK", "") + "_clone") in clone_fns:
-                        ty_name = "CVec_" + ty_info.rust_obj.replace("LDK", "") + "Z";
+                        ty_name = struct_name.replace("LDK", "")
                         clone_fns.add(ty_name + "_clone")
                         write_c("static inline " + struct_name + " " + ty_name + "_clone(const " + struct_name + " *orig) {\n")
                         write_c("\t" + struct_name + " ret = { .data = MALLOC(sizeof(" + ty_info.rust_obj + ") * orig->datalen, \"" + struct_name + " clone bytes\"), .datalen = orig->datalen };\n")
@@ -921,7 +1077,7 @@ with open(sys.argv[1]) as in_h, open(f"{sys.argv[2]}/bindings{consts.file_ext}",
                 elif struct_name in union_enum_items:
                     tuple_variants = {}
                     elem_items = -1
-                    for line, _ in field_lines:
+                    for line, field_block_comment in field_lines:
                         if line == "      struct {":
                             elem_items = 0
                         elif line == "      };":
@@ -934,7 +1090,7 @@ with open(sys.argv[1]) as in_h, open(f"{sys.argv[2]}/bindings{consts.file_ext}",
                                 line = line[5:]
                             split = line.split(" ")
                             assert len(split) == 2
-                            tuple_variants[split[1].strip(";")] = split[0]
+                            tuple_variants[split[1].strip(";")] = (split[0], field_block_comment)
                             elem_items += 1
                             if elem_items > 1:
                                 # We don't currently support tuple variant with more than one element
@@ -950,18 +1106,39 @@ with open(sys.argv[1]) as in_h, open(f"{sys.argv[2]}/bindings{consts.file_ext}",
                     with open(f"{sys.argv[3]}/structs/TxOut{consts.file_ext}", "w") as out_java_struct:
                         out_java_struct.write(consts.hu_struct_file_prefix)
                         out_java_struct.write(consts.txout_defn)
-                        fn_line = "struct LDKCVec_u8Z TxOut_get_script_pubkey (struct LDKTxOut* thing)"
-                        write_c(fn_line + " {")
-                        write_c("\treturn CVec_u8Z_clone(&thing->script_pubkey);")
-                        write_c("}")
-                        map_fn(fn_line + "\n", re.compile("(.*) (TxOut_get_script_pubkey) \((.*)\)").match(fn_line), None, None, None)
-                        fn_line = "uint64_t TxOut_get_value (struct LDKTxOut* thing)"
-                        write_c(fn_line + " {")
-                        write_c("\treturn thing->value;")
-                        write_c("}")
-                        map_fn(fn_line + "\n", re.compile("(.*) (TxOut_get_value) \((.*)\)").match(fn_line), None, None, None)
+                        out_java_struct.write(consts.hu_struct_file_suffix)
+                elif struct_name == "LDKTxIn":
+                    with open(f"{sys.argv[3]}/structs/TxIn{consts.file_ext}", "w") as out_java_struct:
+                        out_java_struct.write(consts.hu_struct_file_prefix)
+                        out_java_struct.write(consts.txin_defn)
+                        out_java_struct.write(consts.hu_struct_file_suffix)
+                elif struct_name == "LDKBigEndianScalar":
+                    with open(f"{sys.argv[3]}/structs/BigEndianScalar{consts.file_ext}", "w") as out_java_struct:
+                        out_java_struct.write(consts.hu_struct_file_prefix)
+                        out_java_struct.write(consts.scalar_defn)
+                        out_java_struct.write(consts.hu_struct_file_suffix)
+                        fn_line = "struct LDKThirtyTwoBytes BigEndianScalar_get_bytes (struct LDKBigEndianScalar* thing)"
+                        write_c(fn_line + " {\n")
+                        write_c("\tLDKThirtyTwoBytes ret = { .data = *thing->big_endian_bytes };\n")
+                        write_c("\treturn ret;\n")
+                        write_c("}\n")
+                        map_fn(fn_line + "\n", re.compile("(.*) (BigEndianScalar_get_bytes) \((.*)\)").match(fn_line), None, None, None)
+
+                        # We need to be able to FREE a heap-allocated BigEndianScalar, but because
+                        # there's nothing heap-allocated inside it the C bindings don't bother
+                        # exposing a `_free` method. Instead, we have to manually write one here,
+                        # though it doesn't need to do anything, the autogenerated wrapper will do
+                        # the required FREE.
+                        fn_line = "static void BigEndianScalar_free (struct LDKBigEndianScalar thing)"
+                        write_c(fn_line + " {}\n")
+                        map_fn(fn_line + "\n", re.compile("static (.*) (BigEndianScalar_free) \((.*)\)").match(fn_line), None, None, None)
+                elif struct_name == "LDKWitnessProgram":
+                    with open(f"{sys.argv[3]}/structs/WitnessProgram{consts.file_ext}", "w") as out_java_struct:
+                        out_java_struct.write(consts.hu_struct_file_prefix)
+                        out_java_struct.write(consts.witness_program_defn)
+                        out_java_struct.write(consts.hu_struct_file_suffix)
                 else:
-                    pass # Everything remaining is a byte[] or some form
+                    pass # Everything remaining is a byte[] of some form
                 cur_block_obj = None
         else:
             fn_ptr = fn_ptr_regex.match(line)
@@ -995,23 +1172,23 @@ with open(sys.argv[1]) as in_h, open(f"{sys.argv[2]}/bindings{consts.file_ext}",
             else:
                 assert(line == "\n")
 
-    out_java.write(consts.bindings_footer)
+    out_java.write(consts.bindings_footer())
     for struct_name in opaque_structs:
         with open(f"{sys.argv[3]}/structs/{struct_name.replace('LDK', '')}{consts.file_ext}", "a") as out_java_struct:
-            out_java_struct.write("}\n")
+            out_java_struct.write("}\n" + consts.hu_struct_file_suffix)
     for struct_name in trait_structs:
         with open(f"{sys.argv[3]}/structs/{struct_name.replace('LDK', '')}{consts.file_ext}", "a") as out_java_struct:
-            out_java_struct.write("}\n")
+            out_java_struct.write("}\n" + consts.hu_struct_file_suffix)
     for struct_name in complex_enums:
         with open(f"{sys.argv[3]}/structs/{struct_name.replace('LDK', '').replace('COption', 'Option')}{consts.file_ext}", "a") as out_java_struct:
-            out_java_struct.write("}\n")
+            out_java_struct.write("}\n" + consts.hu_struct_file_suffix)
     for struct_name in result_types:
         with open(f"{sys.argv[3]}/structs/{struct_name.replace('LDKCResult', 'Result')}{consts.file_ext}", "a") as out_java_struct:
-            out_java_struct.write("}\n")
+            out_java_struct.write("}\n" + consts.hu_struct_file_suffix)
     for struct_name in tuple_types:
         struct_hu_name = struct_name.replace("LDKC2Tuple", "TwoTuple").replace("LDKC3Tuple", "ThreeTuple")
         with open(f"{sys.argv[3]}/structs/{struct_hu_name}{consts.file_ext}", "a") as out_java_struct:
-            out_java_struct.write("}\n")
+            out_java_struct.write("}\n" + consts.hu_struct_file_suffix)
 
 with open(f"{sys.argv[4]}/bindings.c.body", "w") as out_c:
     out_c.write(consts.c_file_pfx)