Expand and update ChannelManagerConstructor+tests for BP and Event API
[ldk-java] / src / test / java / org / ldk / HumanObjectPeerTest.java
index 79f1fd1e93552893dec65c553b77eeea853ce620..2de305844ee33eb8f4d9d6e6416cf4fdb6f79af9 100644 (file)
@@ -135,7 +135,7 @@ class HumanObjectPeerTestInstance {
                     synchronized (monitors) {
                         assert monitors.put(Arrays.toString(funding_txo.get_txid()), monitor) == null;
                     }
-                    return Result_NoneChannelMonitorUpdateErrZ.constructor_ok();
+                    return Result_NoneChannelMonitorUpdateErrZ.ok();
                 }
 
                 public Result_NoneChannelMonitorUpdateErrZ update_channel(OutPoint funding_txo, ChannelMonitorUpdate update) {
@@ -145,7 +145,7 @@ class HumanObjectPeerTestInstance {
                         Result_NoneMonitorUpdateErrorZ update_res = monitors.get(txid).update_monitor(update, tx_broadcaster, fee_estimator, logger);
                         assert update_res instanceof Result_NoneMonitorUpdateErrorZ.Result_NoneMonitorUpdateErrorZ_OK;
                     }
-                    return Result_NoneChannelMonitorUpdateErrZ.constructor_ok();
+                    return Result_NoneChannelMonitorUpdateErrZ.ok();
                 }
 
                 @Override
@@ -191,7 +191,7 @@ class HumanObjectPeerTestInstance {
             // Because get_funding_txo() returns an OutPoint in a tuple that is a reference to an OutPoint inside the
             // ChannelMonitor, its a good test to ensure that the OutPoint isn't freed (or is cloned) before the
             // ChannelMonitor is. This used to be broken.
-            Result_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ roundtrip_monitor = UtilMethods.constructor_BlockHashChannelMonitorZ_read(mon.write(), keys_interface);
+            Result_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ roundtrip_monitor = UtilMethods.BlockHashChannelMonitorZ_read(mon.write(), keys_interface);
             assert roundtrip_monitor instanceof Result_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ.Result_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ_OK;
             TwoTuple<OutPoint, byte[]> funding_txo = ((Result_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ.Result_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ_OK) roundtrip_monitor).res.b.get_funding_txo();
             System.gc(); System.runFinalization(); // Give the GC a chance to run.
@@ -216,7 +216,7 @@ class HumanObjectPeerTestInstance {
                         assert Arrays.equals(res.a.get_txid(), id.get_txid());
                         assert res.a.get_index() == id.get_index();
                     }
-                    return Result_NoneChannelMonitorUpdateErrZ.constructor_ok();
+                    return Result_NoneChannelMonitorUpdateErrZ.ok();
                 }
 
                 @Override
@@ -228,7 +228,7 @@ class HumanObjectPeerTestInstance {
                         assert Arrays.equals(res.a.get_txid(), id.get_txid());
                         assert res.a.get_index() == id.get_index();
                     }
-                    return Result_NoneChannelMonitorUpdateErrZ.constructor_ok();
+                    return Result_NoneChannelMonitorUpdateErrZ.ok();
                 }
             });
 
@@ -240,7 +240,7 @@ class HumanObjectPeerTestInstance {
                     }
                     @Override public Option_C2Tuple_usizeTransactionZZ register_output(WatchedOutput output) {
                         filter_additions.add(Arrays.toString(output.get_outpoint().get_txid()) + ":" + output.get_outpoint().get_index());
-                        return Option_C2Tuple_usizeTransactionZZ.constructor_none();
+                        return Option_C2Tuple_usizeTransactionZZ.none();
                     }
                 });
             } else {
@@ -251,7 +251,7 @@ class HumanObjectPeerTestInstance {
                 chain_watch = get_manual_watch();
                 chain_monitor = null;
             } else {
-                chain_monitor = ChainMonitor.constructor_new(filter, tx_broadcaster, logger, fee_estimator, persister);
+                chain_monitor = ChainMonitor.of(filter, tx_broadcaster, logger, fee_estimator, persister);
                 chain_watch = chain_monitor.as_Watch();
             }
 
@@ -259,7 +259,7 @@ class HumanObjectPeerTestInstance {
             for (byte i = 0; i < 32; i++) {
                 key_seed[i] = (byte) (i ^ seed);
             }
-            KeysManager keys = KeysManager.constructor_new(key_seed, System.currentTimeMillis() / 1000, (int) (System.currentTimeMillis() * 1000));
+            KeysManager keys = KeysManager.of(key_seed, System.currentTimeMillis() / 1000, (int) (System.currentTimeMillis() * 1000));
             if (use_km_wrapper) {
                 this.keys_interface = manual_keysif(keys.as_KeysInterface());
                 this.explicit_keys_manager = null;
@@ -267,11 +267,15 @@ class HumanObjectPeerTestInstance {
                 this.keys_interface = keys.as_KeysInterface();
                 this.explicit_keys_manager = keys;
             }
-            this.router = NetGraphMsgHandler.constructor_new(new byte[32], null, logger);
+            this.router = NetGraphMsgHandler.of(new byte[32], null, logger);
         }
         private void bind_nio() {
             if (!use_nio_peer_handler) return;
-            try { this.nio_peer_handler = new NioPeerHandler(peer_manager); } catch (IOException e) { assert false; }
+            if (use_chan_manager_constructor) {
+                this.nio_peer_handler = this.constructor.nio_peer_handler;
+            } else {
+                try { this.nio_peer_handler = new NioPeerHandler(peer_manager); } catch (IOException e) { assert false; }
+            }
             for (short i = 10_000; true; i++) {
                 try {
                     nio_peer_handler.bind_listener(new InetSocketAddress("127.0.0.1", i));
@@ -284,48 +288,35 @@ class HumanObjectPeerTestInstance {
             this(null, seed);
             if (use_chan_manager_constructor) {
                 try {
-                    this.constructor = new ChannelManagerConstructor(LDKNetwork.LDKNetwork_Bitcoin, UserConfig.constructor_default(), new byte[32], 0,
-                            this.keys_interface, this.fee_estimator, this.chain_monitor, this.tx_broadcaster, this.logger);
+                    this.constructor = new ChannelManagerConstructor(LDKNetwork.LDKNetwork_Bitcoin, UserConfig.with_default(), new byte[32], 0,
+                            this.keys_interface, this.fee_estimator, this.chain_monitor, this.router, this.tx_broadcaster, this.logger);
                     constructor.chain_sync_completed(new ChannelManagerConstructor.ChannelManagerPersister() {
-                        @Override public void handle_events(Event[] events) {
+                        @Override public void handle_event(Event event) {
                             synchronized (pending_manager_events) {
-                                pending_manager_events.addAll(Arrays.asList(events));
+                                pending_manager_events.add(event);
                                 pending_manager_events.notifyAll();
                             }
                         }
                         @Override public void persist_manager(byte[] channel_manager_bytes) { }
                     });
                     this.chan_manager = constructor.channel_manager;
+                    this.peer_manager = constructor.peer_manager;
                     must_free_objs.add(new WeakReference<>(this.chan_manager));
                 } catch (ChannelManagerConstructor.InvalidSerializedDataException e) {
                     assert false;
                 }
             } else {
-                this.chan_manager = ChannelManager.constructor_new(this.fee_estimator, chain_watch, tx_broadcaster, logger, this.keys_interface, UserConfig.constructor_default(), LDKNetwork.LDKNetwork_Bitcoin, BestBlock.constructor_new(new byte[32], 0));
+                ChainParameters params = ChainParameters.of(LDKNetwork.LDKNetwork_Bitcoin, BestBlock.of(new byte[32], 0));
+                this.chan_manager = ChannelManager.of(this.fee_estimator, chain_watch, tx_broadcaster, logger, this.keys_interface, UserConfig.with_default(), params);
+                byte[] random_data = keys_interface.get_secure_random_bytes();
+                this.peer_manager = PeerManager.of(chan_manager.as_ChannelMessageHandler(), router.as_RoutingMessageHandler(), keys_interface.get_node_secret(), random_data, logger);
             }
 
             this.node_id = chan_manager.get_our_node_id();
-
-            byte[] random_data = new byte[32];
-            for (byte i = 0; i < 32; i++) {
-                random_data[i] = (byte) ((i ^ seed) ^ 0xf0);
-            }
-            this.peer_manager = PeerManager.constructor_new(chan_manager.as_ChannelMessageHandler(), router.as_RoutingMessageHandler(), keys_interface.get_node_secret(), random_data, logger);
             bind_nio();
             System.gc();
         }
 
-        byte[] hexStringToByteArray(String s) {
-            int len = s.length();
-            byte[] data = new byte[len / 2];
-            for (int i = 0; i < len; i += 2) {
-                data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
-                        + Character.digit(s.charAt(i+1), 16));
-            }
-            return data;
-        }
-
-
         Object ptr_to;
         Peer(Peer orig) {
             this(null, orig.seed);
@@ -334,17 +325,18 @@ class HumanObjectPeerTestInstance {
                 byte[] serialized = orig.chan_manager.write();
                 try {
                     this.constructor = new ChannelManagerConstructor(serialized, monitors, this.keys_interface,
-                            this.fee_estimator, this.chain_monitor, this.filter, this.tx_broadcaster, this.logger);
+                            this.fee_estimator, this.chain_monitor, this.filter, this.router, this.tx_broadcaster, this.logger);
                     constructor.chain_sync_completed(new ChannelManagerConstructor.ChannelManagerPersister() {
-                        @Override public void handle_events(Event[] events) {
+                        @Override public void handle_event(Event event) {
                             synchronized (pending_manager_events) {
-                                pending_manager_events.addAll(Arrays.asList(events));
+                                pending_manager_events.add(event);
                                 pending_manager_events.notifyAll();
                             }
                         }
                         @Override public void persist_manager(byte[] channel_manager_bytes) { }
                     });
                     this.chan_manager = constructor.channel_manager;
+                    this.peer_manager = constructor.peer_manager;
                     must_free_objs.add(new WeakReference<>(this.chan_manager));
                     // If we are using a ChannelManagerConstructor, we may have pending events waiting on the old peer
                     // which have been removed from the ChannelManager but which we still need to handle.
@@ -364,16 +356,18 @@ class HumanObjectPeerTestInstance {
                 } else {
                     byte[] serialized = orig.monitors.values().stream().iterator().next().write();
                     Result_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ res =
-                            UtilMethods.constructor_BlockHashChannelMonitorZ_read(serialized, this.keys_interface);
+                            UtilMethods.BlockHashChannelMonitorZ_read(serialized, this.keys_interface);
                     assert res instanceof Result_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ.Result_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ_OK;
                     monitors[0] = ((Result_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ.Result_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ_OK) res).res.b;
                 }
                 byte[] serialized = orig.chan_manager.write();
                 Result_C2Tuple_BlockHashChannelManagerZDecodeErrorZ read_res =
-                        UtilMethods.constructor_BlockHashChannelManagerZ_read(serialized, this.keys_interface, this.fee_estimator, this.chain_watch, this.tx_broadcaster, this.logger, UserConfig.constructor_default(), monitors);
+                        UtilMethods.BlockHashChannelManagerZ_read(serialized, this.keys_interface, this.fee_estimator, this.chain_watch, this.tx_broadcaster, this.logger, UserConfig.with_default(), monitors);
                 assert read_res instanceof Result_C2Tuple_BlockHashChannelManagerZDecodeErrorZ.Result_C2Tuple_BlockHashChannelManagerZDecodeErrorZ_OK;
                 this.chan_manager = ((Result_C2Tuple_BlockHashChannelManagerZDecodeErrorZ.Result_C2Tuple_BlockHashChannelManagerZDecodeErrorZ_OK) read_res).res.b;
                 this.chain_watch.watch_channel(monitors[0].get_funding_txo().a, monitors[0]);
+                byte[] random_data = keys_interface.get_secure_random_bytes();
+                this.peer_manager = PeerManager.of(chan_manager.as_ChannelMessageHandler(), router.as_RoutingMessageHandler(), keys_interface.get_node_secret(), random_data, logger);
                 if (!break_cross_peer_refs && (use_manual_watch || use_km_wrapper)) {
                     // When we pass monitors[0] into chain_watch.watch_channel we create a reference from the new Peer to a
                     // field in the old peer, preventing freeing of the original Peer until the new Peer is freed. Thus, we
@@ -382,6 +376,7 @@ class HumanObjectPeerTestInstance {
                 }
             }
             this.node_id = chan_manager.get_our_node_id();
+            bind_nio();
 
             if (cross_reload_ref_pollution) {
                 // This really, really needs to be handled at the bindings layer, but its rather complicated -
@@ -393,13 +388,6 @@ class HumanObjectPeerTestInstance {
                 // the ChannelSigner.
                 this.ptr_to = orig.chan_manager;
             }
-
-            byte[] random_data = new byte[32];
-            for (byte i = 0; i < 32; i++) {
-                random_data[i] = (byte) ((i ^ seed) ^ 0xf0);
-            }
-            this.peer_manager = PeerManager.constructor_new(chan_manager.as_ChannelMessageHandler(), router.as_RoutingMessageHandler(), keys_interface.get_node_secret(), random_data, logger);
-            bind_nio();
         }
 
         TwoTuple<byte[], TwoTuple<Integer, TxOut>[]>[] connect_block(Block b, int height, long expected_monitor_update_len) {
@@ -448,7 +436,10 @@ class HumanObjectPeerTestInstance {
                     return res;
                 }
             } else if (chain_monitor != null) {
-                return chain_monitor.as_EventsProvider().get_and_clear_pending_events();
+                ArrayList<Event> l = new ArrayList<Event>();
+                chain_monitor.as_EventsProvider().process_pending_events(EventHandler.new_impl(l::add));
+                assert l.size() == expected_len;
+                return l.toArray(new Event[0]);
             } else {
                 synchronized (monitors) {
                     assert monitors.size() == 1;
@@ -476,7 +467,9 @@ class HumanObjectPeerTestInstance {
                     }
                 }
             } else {
-                res = this.chan_manager.as_EventsProvider().get_and_clear_pending_events();
+                ArrayList<Event> l = new ArrayList<Event>();
+                chan_manager.as_EventsProvider().process_pending_events(EventHandler.new_impl(l::add));
+                return l.toArray(new Event[0]);
             }
             assert res.length == expected_len;
             return res;
@@ -490,7 +483,7 @@ class HumanObjectPeerTestInstance {
                 assert bindings.LDKCResult_RouteLightningErrorZ_result_ok(res);
                 byte[] serialized_route = bindings.Route_write(bindings.LDKCResult_RouteLightningErrorZ_get_ok(res));
                 must_free_objs.add(new WeakReference<>(serialized_route));
-                Result_RouteDecodeErrorZ copy = Route.constructor_read(serialized_route);
+                Result_RouteDecodeErrorZ copy = Route.read(serialized_route);
                 assert copy instanceof Result_RouteDecodeErrorZ.Result_RouteDecodeErrorZ_OK;
                 bindings.CResult_RouteLightningErrorZ_free(res);
                 return ((Result_RouteDecodeErrorZ.Result_RouteDecodeErrorZ_OK) copy).res;
@@ -653,17 +646,17 @@ class HumanObjectPeerTestInstance {
         assert peer1_chans.length == 1;
         assert peer2_chans.length == 1;
         assert peer1_chans[0].get_channel_value_satoshis() == 10000;
-        assert peer1_chans[0].get_is_live();
+        assert peer1_chans[0].get_is_usable();
         Option_u64Z short_chan_id = peer1_chans[0].get_short_channel_id();
         assert short_chan_id instanceof Option_u64Z.Some;
         assert ((Option_u64Z.Some)short_chan_id).some == (1L << 40); // 0th output in the 0th transaction in the 1st block
         assert Arrays.equals(peer1_chans[0].get_channel_id(), funding.getTxId().getReversedBytes());
         assert Arrays.equals(peer2_chans[0].get_channel_id(), funding.getTxId().getReversedBytes());
 
-        Result_InvoiceSignOrCreationErrorZ invoice = UtilMethods.constructor_invoice_from_channelmanager(peer2.chan_manager, peer2.keys_interface, LDKCurrency.LDKCurrency_Bitcoin, Option_u64Z.constructor_none(), "Invoice Description");
+        Result_InvoiceSignOrCreationErrorZ invoice = UtilMethods.invoice_from_channelmanager(peer2.chan_manager, peer2.keys_interface, LDKCurrency.LDKCurrency_Bitcoin, Option_u64Z.none(), "Invoice Description");
         assert invoice instanceof Result_InvoiceSignOrCreationErrorZ.Result_InvoiceSignOrCreationErrorZ_OK;
         System.out.println("Got invoice: " + ((Result_InvoiceSignOrCreationErrorZ.Result_InvoiceSignOrCreationErrorZ_OK) invoice).res.to_str());
-        Result_InvoiceNoneZ parsed_invoice = Invoice.constructor_from_str(((Result_InvoiceSignOrCreationErrorZ.Result_InvoiceSignOrCreationErrorZ_OK) invoice).res.to_str());
+        Result_InvoiceNoneZ parsed_invoice = Invoice.from_str(((Result_InvoiceSignOrCreationErrorZ.Result_InvoiceSignOrCreationErrorZ_OK) invoice).res.to_str());
         assert parsed_invoice instanceof Result_InvoiceNoneZ.Result_InvoiceNoneZ_OK;
         assert Arrays.equals(((Result_InvoiceNoneZ.Result_InvoiceNoneZ_OK) parsed_invoice).res.payment_hash(), ((Result_InvoiceSignOrCreationErrorZ.Result_InvoiceSignOrCreationErrorZ_OK) invoice).res.payment_hash());
         SignedRawInvoice signed_raw = ((Result_InvoiceNoneZ.Result_InvoiceNoneZ_OK) parsed_invoice).res.into_signed_raw();
@@ -684,8 +677,8 @@ class HumanObjectPeerTestInstance {
         byte[] hop_pubkey = new byte[33];
         hop_pubkey[0] = 3;
         hop_pubkey[1] = 42;
-        hops[0][0] = RouteHop.constructor_new(hop_pubkey, NodeFeatures.constructor_known(), 42, ChannelFeatures.constructor_known(), 100, 0);
-        Route r2 = Route.constructor_new(hops);
+        hops[0][0] = RouteHop.of(hop_pubkey, NodeFeatures.known(), 42, ChannelFeatures.known(), 100, 0);
+        Route r2 = Route.of(hops);
         payment_res = peer1.chan_manager.send_payment(r2, payment_hash, payment_secret);
         assert payment_res instanceof Result_NonePaymentSendFailureZ.Result_NonePaymentSendFailureZ_Err;
 
@@ -822,6 +815,8 @@ class HumanObjectPeerTestInstance {
             state.peer1.constructor.interrupt();
             state.peer2.constructor.interrupt();
         }
+
+        t.interrupt();
     }
 
     java.util.LinkedList<WeakReference<Object>> must_free_objs = new java.util.LinkedList();
@@ -866,8 +861,8 @@ public class HumanObjectPeerTest {
                 // There are no cross refs to break without reloading peers.
                 continue;
             }
-            if (use_chan_manager_constructor && use_manual_watch) {
-                // ChannelManagerConstructor requires a ChainMonitor as the Watch
+            if (use_chan_manager_constructor && (use_manual_watch || !nio_peer_handler)) {
+                // ChannelManagerConstructor requires a ChainMonitor as the Watch and creates a NioPeerHandler for us.
                 continue;
             }
             System.err.println("Running test with flags " + i);