Update tests for latest upstream API, sadly disabling the Sign wrapper test
[ldk-java] / src / main / java / org / ldk / batteries / ChannelManagerConstructor.java
1 package org.ldk.batteries;
2
3 import org.jetbrains.annotations.Nullable;
4 import org.ldk.enums.LDKNetwork;
5 import org.ldk.structs.*;
6 import org.ldk.util.TwoTuple;
7
8
9 /**
10  * A simple utility class which assists in constructing a fresh or deserializing from disk a ChannelManager and one or
11  * more ChannelMonitors.
12  */
13 public class ChannelManagerConstructor {
14     /**
15      * An Exception that indicates the serialized data is invalid and has been corrupted on disk. You should attempt to
16      * restore from a backup if there is one which is known to be current. Otherwise, funds may have been lost.
17      */
18     public static class InvalidSerializedDataException extends Exception {}
19
20     /**
21      * The ChannelManager either deserialized or newly-constructed.
22      */
23     public final ChannelManager channel_manager;
24     /**
25      * The latest block has the channel manager saw. If this is non-null it is a 32-byte block hash.
26      * You should sync the blockchain starting with the block that builds on this block.
27      */
28     public final byte[] channel_manager_latest_block_hash;
29     /**
30      * A list of ChannelMonitors and the last block they each saw. You should sync the blockchain on each individually
31      * starting with the block that builds on the hash given.
32      * After doing so (and syncing the blockchain on the channel manager as well), you should call chain_sync_completed()
33      * and then continue to normal application operation.
34      */
35     public final TwoTuple<ChannelMonitor, byte[]>[] channel_monitors;
36
37     private final ChainMonitor chain_monitor;
38
39     /**
40      * Deserializes a channel manager and a set of channel monitors from the given serialized copies and interface implementations
41      *
42      * @param filter If provided, the outputs which were previously registered to be monitored for will be loaded into the filter.
43      *               Note that if the provided Watch is a ChainWatch and has an associated filter, the previously registered
44      *               outputs will be loaded when chain_sync_completed is called.
45      */
46     public ChannelManagerConstructor(byte[] channel_manager_serialized, byte[][] channel_monitors_serialized,
47                                      KeysInterface keys_interface, FeeEstimator fee_estimator, ChainMonitor chain_monitor, @Nullable Filter filter,
48                                      BroadcasterInterface tx_broadcaster, Logger logger) throws InvalidSerializedDataException {
49         final ChannelMonitor[] monitors = new ChannelMonitor[channel_monitors_serialized.length];
50         this.channel_monitors = new TwoTuple[monitors.length];
51         for (int i = 0; i < monitors.length; i++) {
52             Result_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ res = UtilMethods.constructor_BlockHashChannelMonitorZ_read(channel_monitors_serialized[i], keys_interface);
53             if (res instanceof Result_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ.Result_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ_Err) {
54                 throw new InvalidSerializedDataException();
55             }
56             monitors[i] = ((Result_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ.Result_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ_OK) res).res.b;
57             this.channel_monitors[i] = new TwoTuple<>(monitors[i], ((Result_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ.Result_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ_OK)res).res.a);
58         }
59         Result_C2Tuple_BlockHashChannelManagerZDecodeErrorZ res =
60                 UtilMethods.constructor_BlockHashChannelManagerZ_read(channel_manager_serialized, keys_interface, fee_estimator, chain_monitor.as_Watch(), tx_broadcaster,
61                         logger, UserConfig.constructor_default(), monitors);
62         if (res instanceof Result_C2Tuple_BlockHashChannelManagerZDecodeErrorZ.Result_C2Tuple_BlockHashChannelManagerZDecodeErrorZ_Err) {
63             throw new InvalidSerializedDataException();
64         }
65         this.channel_manager = ((Result_C2Tuple_BlockHashChannelManagerZDecodeErrorZ.Result_C2Tuple_BlockHashChannelManagerZDecodeErrorZ_OK)res).res.b;
66         this.channel_manager_latest_block_hash = ((Result_C2Tuple_BlockHashChannelManagerZDecodeErrorZ.Result_C2Tuple_BlockHashChannelManagerZDecodeErrorZ_OK)res).res.a;
67         this.chain_monitor = chain_monitor;
68         if (filter != null) {
69             for (ChannelMonitor monitor : monitors) {
70                 monitor.load_outputs_to_watch(filter);
71             }
72         }
73     }
74
75     /**
76      * Constructs a channel manager from the given interface implementations
77      */
78     public ChannelManagerConstructor(LDKNetwork network, UserConfig config, byte[] current_blockchain_tip_hash, int current_blockchain_tip_height,
79                                      KeysInterface keys_interface, FeeEstimator fee_estimator, ChainMonitor chain_monitor,
80                                      BroadcasterInterface tx_broadcaster, Logger logger) throws InvalidSerializedDataException {
81         channel_monitors = new TwoTuple[0];
82         channel_manager_latest_block_hash = null;
83         this.chain_monitor = chain_monitor;
84         BestBlock block = BestBlock.constructor_new(current_blockchain_tip_hash, current_blockchain_tip_height);
85         channel_manager = ChannelManager.constructor_new(fee_estimator, chain_monitor.as_Watch(), tx_broadcaster, logger, keys_interface, config, network, block);
86     }
87
88     /**
89      * Abstract interface which should handle Events and persist the ChannelManager. When you call chain_sync_completed
90      * a background thread is started which will automatically call these methods for you when events occur.
91      */
92     public interface ChannelManagerPersister {
93         void handle_events(Event[] events);
94         void persist_manager(byte[] channel_manager_bytes);
95     }
96
97     Thread persister_thread = null;
98     volatile boolean shutdown = false;
99
100     /**
101      * Utility which adds all of the deserialized ChannelMonitors to the chain watch so that further updates from the
102      * ChannelManager are processed as normal.
103      *
104      * This also spawns a background thread which will call the appropriate methods on the provided
105      * ChannelManagerPersister as required.
106      */
107     public void chain_sync_completed(ChannelManagerPersister persister) {
108         if (persister_thread != null) { return; }
109         for (TwoTuple<ChannelMonitor, byte[]> monitor: channel_monitors) {
110             this.chain_monitor.as_Watch().watch_channel(monitor.a.get_funding_txo().a, monitor.a);
111         }
112         persister_thread = new Thread(() -> {
113             long lastTimerTick = System.currentTimeMillis();
114             while (true) {
115                 boolean need_persist = this.channel_manager.await_persistable_update_timeout(1);
116                 Event[] events = this.channel_manager.as_EventsProvider().get_and_clear_pending_events();
117                 if (events.length != 0) {
118                     persister.handle_events(events);
119                     need_persist = true;
120                 }
121                 events = this.chain_monitor.as_EventsProvider().get_and_clear_pending_events();
122
123                 if (events.length != 0) {
124                     persister.handle_events(events);
125                     need_persist = true;
126                 }
127                 if (need_persist) {
128                     persister.persist_manager(this.channel_manager.write());
129                 }
130                 if (shutdown) {
131                     return;
132                 }
133                 if (lastTimerTick < System.currentTimeMillis() - 60 * 1000) {
134                     this.channel_manager.timer_tick_occurred();
135                     lastTimerTick = System.currentTimeMillis();
136                 }
137             }
138         }, "NioPeerHandler NIO Thread");
139         persister_thread.start();
140     }
141
142     /**
143      * Interrupt the background thread, stopping the background handling of
144      */
145     public void interrupt() {
146         shutdown = true;
147         try {
148             persister_thread.join();
149         } catch (InterruptedException ignored) { }
150     }
151 }