]> git.bitcoin.ninja Git - ldk-java/commitdiff
[TS] Be more aggressive with type checks
authorMatt Corallo <git@bluematt.me>
Fri, 28 Oct 2022 18:30:30 +0000 (18:30 +0000)
committerMatt Corallo <git@bluematt.me>
Fri, 28 Oct 2022 19:43:41 +0000 (19:43 +0000)
ts/test/tests.mts
ts/tsconfig.json
typescript_strings.py

index 61b10d3ecc5a67a3df96565c9aad3de5ce13f036..db0fe326618841a51b77104421565428272a66a1 100644 (file)
@@ -69,12 +69,12 @@ class Node {
 }
 function get_chanman(): Node {
        const fee_est = ldk.FeeEstimator.new_impl({
-               get_est_sat_per_1000_weight(confirmation_target: ldk.ConfirmationTarget): number {
+               get_est_sat_per_1000_weight(_confirmation_target: ldk.ConfirmationTarget): number {
                        return 253;
                }
        } as ldk.FeeEstimatorInterface);
-       var tx_broadcaster;
-       const tx_broadcasted: Promise<Uint8Array> = new Promise((resolve, reject) => {
+       var tx_broadcaster: ldk.BroadcasterInterface;
+       const tx_broadcasted: Promise<Uint8Array> = new Promise((resolve, _reject) => {
                tx_broadcaster = ldk.BroadcasterInterface.new_impl({
                        broadcast_transaction(tx: Uint8Array): void { console.log("Tx Broadcast: " + tx); resolve(tx); }
                } as ldk.BroadcasterInterfaceInterface);
@@ -86,15 +86,15 @@ function get_chanman(): Node {
        } as ldk.LoggerInterface);
 
        const persister = ldk.Persist.new_impl({
-               persist_new_channel(channel_id: ldk.OutPoint, data: ldk.ChannelMonitor, update_id: ldk.MonitorUpdateId): ldk.ChannelMonitorUpdateStatus {
+               persist_new_channel(_channel_id: ldk.OutPoint, _data: ldk.ChannelMonitor, _update_id: ldk.MonitorUpdateId): ldk.ChannelMonitorUpdateStatus {
                        return ldk.ChannelMonitorUpdateStatus.LDKChannelMonitorUpdateStatus_Completed;
                },
-               update_persisted_channel(channel_id: ldk.OutPoint, update: ldk.ChannelMonitorUpdate, data: ldk.ChannelMonitor, update_id: ldk.MonitorUpdateId): ldk.ChannelMonitorUpdateStatus {
+               update_persisted_channel(_channel_id: ldk.OutPoint, _update: ldk.ChannelMonitorUpdate, _data: ldk.ChannelMonitor, _update_id: ldk.MonitorUpdateId): ldk.ChannelMonitorUpdateStatus {
                        return ldk.ChannelMonitorUpdateStatus.LDKChannelMonitorUpdateStatus_Completed;
                }
        } as ldk.PersistInterface);
 
-       const chain_monitor = ldk.ChainMonitor.constructor_new(ldk.Option_FilterZ.constructor_none(), tx_broadcaster, logger, fee_est, persister);
+       const chain_monitor = ldk.ChainMonitor.constructor_new(ldk.Option_FilterZ.constructor_none(), tx_broadcaster!, logger, fee_est, persister);
        const chain_watch: ldk.Watch = chain_monitor.as_Watch();
 
        const seed = new Uint8Array(32);
@@ -105,7 +105,7 @@ function get_chanman(): Node {
        const config = ldk.UserConfig.constructor_default();
        const params = ldk.ChainParameters.constructor_new(ldk.Network.LDKNetwork_Testnet, ldk.BestBlock.constructor_from_genesis(ldk.Network.LDKNetwork_Testnet));
 
-       const chan_man = ldk.ChannelManager.constructor_new(fee_est, chain_watch, tx_broadcaster, logger, keys_interface, config, params);
+       const chan_man = ldk.ChannelManager.constructor_new(fee_est, chain_watch, tx_broadcaster!, logger, keys_interface, config, params);
        return new Node(chan_man, tx_broadcasted, logger, keys_interface);
 }
 
@@ -164,7 +164,7 @@ function get_event(chan_man: ldk.ChannelManager): ldk.Event {
 
        chan_man.as_EventsProvider().process_pending_events(event_handler);
        assert(events.length == 1);
-       return events[0];
+       return events[0]!;
 }
 
 tests.push(async () => {
@@ -228,6 +228,7 @@ tests.push(async () => {
        const sock_a = ldk.SocketDescriptor.new_impl({
                send_data(data: Uint8Array, resume_read: boolean): number {
                        assert(pm_b.read_event(sock_b, data) instanceof ldk.Result_boolPeerHandleErrorZ_OK);
+                       assert(resume_read);
                        return data.length;
                },
                disconnect_socket(): void {
@@ -243,6 +244,7 @@ tests.push(async () => {
        sock_b = ldk.SocketDescriptor.new_impl({
                send_data(data: Uint8Array, resume_read: boolean): number {
                        assert(pm_a.read_event(sock_a, data) instanceof ldk.Result_boolPeerHandleErrorZ_OK);
+                       assert(resume_read);
                        return data.length;
                },
                disconnect_socket(): void {
@@ -307,7 +309,7 @@ tests.push(async () => {
                        for (var i = 0; i < 44; i++) assert(buffer[i] == 67);
                        return ldk.Result_COption_CustomOnionMessageContentsZDecodeErrorZ.constructor_ok(ldk.Option_CustomOnionMessageContentsZ.constructor_some(ldk.CustomOnionMessageContents.new_impl({
                                tlv_type(): bigint { return 9998n; },
-                               write(): Uint8Array { assert(false); return null; }
+                               write(): Uint8Array { throw new Error(); }
                        } as ldk.CustomOnionMessageContentsInterface)));
                },
                handle_custom_message(msg: ldk.CustomOnionMessageContents) {
@@ -348,7 +350,7 @@ tests.push(async () => {
                        for (var i = 0; i < 43; i++) assert(buffer[i] == 66);
                        return ldk.Result_COption_CustomOnionMessageContentsZDecodeErrorZ.constructor_ok(ldk.Option_CustomOnionMessageContentsZ.constructor_some(ldk.CustomOnionMessageContents.new_impl({
                                tlv_type(): bigint { return 9999n; },
-                               write(): Uint8Array { assert(false); return null; }
+                               write(): Uint8Array { throw new Error(); }
                        } as ldk.CustomOnionMessageContentsInterface)));
                },
                handle_custom_message(msg: ldk.CustomOnionMessageContents) {
@@ -365,6 +367,7 @@ tests.push(async () => {
        const sock_a = ldk.SocketDescriptor.new_impl({
                send_data(data: Uint8Array, resume_read: boolean): number {
                        assert(pm_b.read_event(sock_b, data) instanceof ldk.Result_boolPeerHandleErrorZ_OK);
+                       assert(resume_read);
                        return data.length;
                },
                disconnect_socket(): void {
@@ -380,6 +383,7 @@ tests.push(async () => {
        sock_b = ldk.SocketDescriptor.new_impl({
                send_data(data: Uint8Array, resume_read: boolean): number {
                        assert(pm_a.read_event(sock_a, data) instanceof ldk.Result_boolPeerHandleErrorZ_OK);
+                       assert(resume_read);
                        return data.length;
                },
                disconnect_socket(): void {
@@ -463,7 +467,7 @@ async function run_tests(check_leaks: boolean) {
        console.log("all tests passed: " + result);
        if (result !== true || !check_leaks) { return result; }
 
-       const allocs_finished = new Promise((resolve, reject) => {
+       const allocs_finished = new Promise((resolve, _reject) => {
                var loop_count = 0;
                const interval_id = setInterval(() => {
                        const alloc_count = rawldk.getRemainingAllocationCount();
index a2867b849f45006c7eee061f719c8a75e7ec79f4..57c75ee762c8a1886cca487716eeabe2d45dcb06 100644 (file)
     "declaration": true,
     "strict": true,
     "noImplicitAny": true,
-    "strictNullChecks": false,
+    "strictNullChecks": true,
     "strictFunctionTypes": true,
     "strictBindCallApply": true,
-    "strictPropertyInitialization": false,
+    "strictPropertyInitialization": true,
     "noImplicitThis": true,
     "useUnknownInCatchVariables": true,
     "alwaysStrict": true,
     "noUnusedLocals": false,
     "noUnusedParameters": false,
-    "exactOptionalPropertyTypes": false,
+    "exactOptionalPropertyTypes": true,
     "noImplicitReturns": true,
     "noFallthroughCasesInSwitch": true,
     "noUncheckedIndexedAccess": true,
@@ -29,6 +29,6 @@
     "allowUnusedLabels": false,
     "allowUnreachableCode": false,
 
-    "skipLibCheck": true
+    "skipLibCheck": false
   }
 }
index aeb2a4ae8e68b5ac7214eec3a0c5273e844cfb14..64eae1fa4de7542a57e8fbe70586c14186ade47a 100644 (file)
@@ -53,7 +53,7 @@ imports.wasi_snapshot_preview1 = {
                for (var i = 0; i < iovec_array_len; i++) {
                        const bytes_view = new Uint8Array(wasm.memory.buffer, ptr_len_view[i*2], ptr_len_view[i*2+1]);
                        console.log("[fd " + fd + "]: " + String.fromCharCode(...bytes_view));
-                       bytes_written += ptr_len_view[i*2+1];
+                       bytes_written += ptr_len_view[i*2+1]!;
                }
                const written_view = new Uint32Array(wasm.memory.buffer, bytes_written_ptr, 1);
                written_view[0] = bytes_written;
@@ -82,7 +82,7 @@ imports.wasi_snapshot_preview1 = {
                out_len_view[0] = 0;
                return 0;
        },
-       "environ_get": (environ_ptr: number, environ_buf_ptr: number) => {
+       "environ_get": (_environ_ptr: number, _environ_buf_ptr: number) => {
                // This is called before fd_write to format + print panic messages,
                // but only if we have variables in environ_sizes_get, so shouldn't ever actually happen!
                console.log("wasi_snapshot_preview1:environ_get");
@@ -150,7 +150,7 @@ export async function initializeWasmFetch(uri: string) {
 export function uint5ArrToBytes(inputArray: Array<UInt5>): Uint8Array {
        const arr = new Uint8Array(inputArray.length);
        for (var i = 0; i < inputArray.length; i++) {
-               arr[i] = inputArray[i].getVal();
+               arr[i] = inputArray[i]!.getVal();
        }
        return arr;
 }
@@ -159,7 +159,7 @@ export function uint5ArrToBytes(inputArray: Array<UInt5>): Uint8Array {
 export function WitnessVersionArrToBytes(inputArray: Array<WitnessVersion>): Uint8Array {
        const arr = new Uint8Array(inputArray.length);
        for (var i = 0; i < inputArray.length; i++) {
-               arr[i] = inputArray[i].getVal();
+               arr[i] = inputArray[i]!.getVal();
        }
        return arr;
 }
@@ -197,7 +197,7 @@ export function encodeUint64Array (inputArray: BigUint64Array|Array<bigint>|null
 }
 
 /* @internal */
-export function check_arr_len(arr: Uint8Array|null, len: number): Uint8Array {
+export function check_arr_len(arr: Uint8Array|null, len: number): Uint8Array|null {
        if (arr !== null && arr.length != len) { throw new Error("Expected array of length " + len + " got " + arr.length); }
        return arr;
 }
@@ -205,7 +205,7 @@ export function check_arr_len(arr: Uint8Array|null, len: number): Uint8Array {
 /* @internal */
 export function getArrayLength(arrayPointer: number): number {
        const arraySizeViewer = new BigUint64Array(wasm.memory.buffer, arrayPointer, 1);
-       const len = arraySizeViewer[0];
+       const len = arraySizeViewer[0]!;
        if (len >= (2n ** 32n)) throw new Error("Bogus Array Size");
        return Number(len % (2n ** 32n));
 }
@@ -260,19 +260,19 @@ export function freeWasmMemory(pointer: number) { wasm.TS_free(pointer); }
 /* @internal */
 export function getU64ArrayElem(arrayPointer: number, idx: number): bigint {
        const actualArrayViewer = new BigUint64Array(wasm.memory.buffer, arrayPointer + 8, idx + 1);
-       return actualArrayViewer[idx];
+       return actualArrayViewer[idx]!;
 }
 
 /* @internal */
 export function getU32ArrayElem(arrayPointer: number, idx: number): number {
        const actualArrayViewer = new Uint32Array(wasm.memory.buffer, arrayPointer + 8, idx + 1);
-       return actualArrayViewer[idx];
+       return actualArrayViewer[idx]!;
 }
 
 /* @internal */
 export function getU8ArrayElem(arrayPointer: number, idx: number): number {
        const actualArrayViewer = new Uint8Array(wasm.memory.buffer, arrayPointer + 8, idx + 1);
-       return actualArrayViewer[idx];
+       return actualArrayViewer[idx]!;
 }
 
 
@@ -384,7 +384,7 @@ export class WitnessVersion {
 }
 
 export class UnqualifiedError {
-       public constructor(val: number) {}
+       public constructor(_val: number) {}
 }
 """
 
@@ -395,7 +395,7 @@ export class UnqualifiedError {
        public value: bigint;
 
        /* @internal */
-       public constructor(_dummy: object, ptr: bigint) {
+       public constructor(_dummy: null, ptr: bigint) {
                super(ptr, bindings.TxOut_free);
                this.script_pubkey = bindings.decodeUint8Array(bindings.TxOut_get_script_pubkey(ptr));
                this.value = bindings.TxOut_get_value(ptr);
@@ -411,7 +411,7 @@ export class UnqualifiedError {
        public scalar_bytes: Uint8Array;
 
        /* @internal */
-       public constructor(_dummy: object, ptr: bigint) {
+       public constructor(_dummy: null, ptr: bigint) {
                super(ptr, bindings.BigEndianScalar_free);
                this.scalar_bytes = bindings.decodeUint8Array(bindings.BigEndianScalar_get_bytes(ptr));
        }
@@ -874,7 +874,7 @@ export enum {struct_name} {{
                 else:
                     bindings_instantiator += ", " + first_to_lower(var.arg_name)
             else:
-                bindings_instantiator += ", " + first_to_lower(var[1]) + ".instance_idx"
+                bindings_instantiator += ", " + first_to_lower(var[1]) + ".instance_idx!"
                 super_instantiator += first_to_lower(var[1]) + "_impl, "
                 pointer_to_adder += "\t\timpl_holder.held.ptrs_to.push(" + first_to_lower(var[1]) + ");\n"
                 impl_constructor_arguments += f", {first_to_lower(var[1])}_impl: {var[0].replace('LDK', '')}Interface"
@@ -886,7 +886,7 @@ export enum {struct_name} {{
                 trait_constructor_arguments += ", " + var.arg_name
             else:
                 super_constructor_statements += "\t\tconst " + first_to_lower(var[1]) + " = " + var[1] + ".new_impl(" + super_instantiator + ");\n"
-                trait_constructor_arguments += ", " + first_to_lower(var[1]) + ".instance_idx"
+                trait_constructor_arguments += ", " + first_to_lower(var[1]) + ".instance_idx!"
                 for suparg in var[2]:
                     if isinstance(suparg, ConvInfo):
                         trait_constructor_arguments += ", " + suparg.arg_name
@@ -958,7 +958,7 @@ export interface {struct_name.replace("LDK", "")}Interface {{
 {out_java_interface}}}
 
 class {struct_name}Holder {{
-       held: {struct_name.replace("LDK", "")};
+       held: {struct_name.replace("LDK", "")}|null = null;
 }}
 
 /**
@@ -966,13 +966,13 @@ class {struct_name}Holder {{
  */
 export class {struct_name.replace("LDK","")} extends CommonBase {{
        /* @internal */
-       public bindings_instance?: bindings.{struct_name};
+       public bindings_instance: bindings.{struct_name}|null;
 
        /* @internal */
        public instance_idx?: number;
 
        /* @internal */
-       constructor(_dummy: object, ptr: bigint) {{
+       constructor(_dummy: null, ptr: bigint) {{
                super(ptr, bindings.{struct_name.replace("LDK","")}_free);
                this.bindings_instance = null;
        }}
@@ -987,7 +987,7 @@ export class {struct_name.replace("LDK","")} extends CommonBase {{
                impl_holder.held = new {struct_name.replace("LDK", "")}(null, ptr_idx[0]);
                impl_holder.held.instance_idx = ptr_idx[1];
                impl_holder.held.bindings_instance = structImplementation;
-{pointer_to_adder}             return impl_holder.held;
+{pointer_to_adder}             return impl_holder.held!;
        }}
 
 """
@@ -1214,7 +1214,7 @@ export class {struct_name.replace("LDK","")} extends CommonBase {{
 
         java_hu_class = "/**\n * " + enum_doc_comment.replace("\n", "\n * ") + "\n */\n"
         java_hu_class += "export class " + java_hu_type + " extends CommonBase {\n"
-        java_hu_class += "\tprotected constructor(_dummy: object, ptr: bigint) { super(ptr, bindings." + bindings_type + "_free); }\n"
+        java_hu_class += "\tprotected constructor(_dummy: null, ptr: bigint) { super(ptr, bindings." + bindings_type + "_free); }\n"
         java_hu_class += "\t/* @internal */\n"
         java_hu_class += f"\tpublic static constr_from_ptr(ptr: bigint): {java_hu_type} {{\n"
         java_hu_class += f"\t\tconst raw_ty: number = bindings." + struct_name + "_ty_from_ptr(ptr);\n"
@@ -1306,7 +1306,7 @@ export class {struct_name.replace("LDK","")} extends CommonBase {{
  */
 export class {hu_name} extends CommonBase {implementations}{{
        /* @internal */
-       public constructor(_dummy: object, ptr: bigint) {{
+       public constructor(_dummy: null, ptr: bigint) {{
                {constructor_body}
        }}{extra_body}
 
@@ -1325,7 +1325,7 @@ export class {hu_name} extends CommonBase {implementations}{{
             suffixes += "\tpublic res: " + res_map.java_hu_ty + ";\n"
         suffixes += f"""
        /* @internal */
-       public constructor(_dummy: object, ptr: bigint) {{
+       public constructor(_dummy: null, ptr: bigint) {{
                super(_dummy, ptr);
 """
         if res_map.java_hu_ty == "void":
@@ -1343,7 +1343,7 @@ export class {hu_name} extends CommonBase {implementations}{{
             suffixes += "\tpublic err: " + err_map.java_hu_ty + ";\n"
         suffixes += f"""
        /* @internal */
-       public constructor(_dummy: object, ptr: bigint) {{
+       public constructor(_dummy: null, ptr: bigint) {{
                super(_dummy, ptr);
 """
         if err_map.java_hu_ty == "void":
@@ -1362,7 +1362,7 @@ export class {hu_name} extends CommonBase {implementations}{{
         return f"""{self.hu_struct_file_prefix}
 
 export class {human_ty} extends CommonBase {{
-       protected constructor(_dummy: object, ptr: bigint) {{
+       protected constructor(_dummy: null, ptr: bigint) {{
                super(ptr, bindings.{struct_name.replace("LDK","")}_free);
        }}
        /* @internal */
@@ -1443,6 +1443,8 @@ export function {method_name}({method_argument_string}): {return_java_ty} {{
                             out_java_struct += arg.arg_name + "_" + explode_arg.arg_name + ": " + explode_arg.java_hu_ty
                     else:
                         out_java_struct += arg.arg_name + ": " + arg.java_hu_ty
+                        if arg.nullable:
+                            out_java_struct += "|null"
 
         out_c += (") {\n")
         if out_java_struct is not None:
@@ -1549,12 +1551,12 @@ export function {method_name}({method_argument_string}): {return_java_ty} {{
             bindings.write("""
 
 js_invoke = function(obj_ptr: number, fn_id: number, arg1: bigint|number, arg2: bigint|number, arg3: bigint|number, arg4: bigint|number, arg5: bigint|number, arg6: bigint|number, arg7: bigint|number, arg8: bigint|number, arg9: bigint|number, arg10: bigint|number) {
-       const weak: WeakRef<object> = js_objs[obj_ptr];
+       const weak: WeakRef<object>|undefined = js_objs[obj_ptr];
        if (weak == null || weak == undefined) {
                console.error("Got function call on unknown/free'd JS object!");
                throw new Error("Got function call on unknown/free'd JS object!");
        }
-       const obj: object = weak.deref();
+       const obj = weak.deref();
        if (obj == null || obj == undefined) {
                console.error("Got function call on GC'd JS object!");
                throw new Error("Got function call on GC'd JS object!");