[Java] Update tests + batteries to latest upstream API
[ldk-java] / src / main / java / org / ldk / batteries / ChannelManagerConstructor.java
1 package org.ldk.batteries;
2
3 import javax.annotation.Nullable;
4 import org.ldk.enums.Network;
5 import org.ldk.enums.Recipient;
6 import org.ldk.structs.*;
7
8 import java.io.IOException;
9 import java.util.HashSet;
10
11
12 /**
13  * A simple utility class which assists in constructing a fresh or deserializing from disk a ChannelManager and one or
14  * more ChannelMonitors.
15  *
16  * Also constructs a PeerManager and spawns a background thread to monitor for and notify you of relevant Events.
17  */
18 public class ChannelManagerConstructor {
19     /**
20      * An Exception that indicates the serialized data is invalid and has been corrupted on disk. You should attempt to
21      * restore from a backup if there is one which is known to be current. Otherwise, funds may have been lost.
22      */
23     public static class InvalidSerializedDataException extends Exception {
24         InvalidSerializedDataException(String reason) {
25             super(reason);
26         }
27     }
28
29     /**
30      * The ChannelManager either deserialized or newly-constructed.
31      */
32     public final ChannelManager channel_manager;
33     /**
34      * The latest block has the channel manager saw. If this is non-null it is a 32-byte block hash.
35      * You should sync the blockchain starting with the block that builds on this block.
36      */
37     public final byte[] channel_manager_latest_block_hash;
38     /**
39      * A list of ChannelMonitors and the last block they each saw. You should sync the blockchain on each individually
40      * starting with the block that builds on the hash given.
41      * After doing so (and syncing the blockchain on the channel manager as well), you should call chain_sync_completed()
42      * and then continue to normal application operation.
43      */
44     public final TwoTuple_BlockHashChannelMonitorZ[] channel_monitors;
45     /**
46      * A PeerManager which is constructed to pass messages and handle connections to peers.
47      */
48     public final PeerManager peer_manager;
49     /**
50      * A NioPeerHandler which manages a background thread to handle socket events and pass them to the peer_manager.
51      */
52     public final NioPeerHandler nio_peer_handler;
53     /**
54      * If a `NetworkGraph` is provided to the constructor *and* a `LockableScore` is provided to
55          * `chain_sync_completed`, this will be non-null after `chain_sync_completed` returns.
56          *
57      * It should be used to send payments instead of doing so directly via the `channel_manager`.
58          *
59      * When payments are made through this, they are automatically retried and the provided Scorer
60      * will be updated with payment failure data.
61      */
62     @Nullable public InvoicePayer payer;
63
64     private final ChainMonitor chain_monitor;
65     @Nullable private final NetworkGraph net_graph;
66     @Nullable private final NetGraphMsgHandler graph_msg_handler;
67     private final Logger logger;
68
69     /**
70      * Deserializes a channel manager and a set of channel monitors from the given serialized copies and interface implementations
71      *
72      * @param filter If provided, the outputs which were previously registered to be monitored for will be loaded into the filter.
73      *               Note that if the provided Watch is a ChainWatch and has an associated filter, the previously registered
74      *               outputs will be loaded when chain_sync_completed is called.
75      */
76     public ChannelManagerConstructor(byte[] channel_manager_serialized, byte[][] channel_monitors_serialized, UserConfig config,
77                                      KeysInterface keys_interface, FeeEstimator fee_estimator, ChainMonitor chain_monitor,
78                                      @Nullable Filter filter, @Nullable NetworkGraph net_graph,
79                                      BroadcasterInterface tx_broadcaster, Logger logger) throws InvalidSerializedDataException {
80         final IgnoringMessageHandler no_custom_messages = IgnoringMessageHandler.of();
81         final ChannelMonitor[] monitors = new ChannelMonitor[channel_monitors_serialized.length];
82         this.channel_monitors = new TwoTuple_BlockHashChannelMonitorZ[monitors.length];
83         HashSet<OutPoint> monitor_funding_set = new HashSet();
84         for (int i = 0; i < monitors.length; i++) {
85             Result_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ res = UtilMethods.C2Tuple_BlockHashChannelMonitorZ_read(channel_monitors_serialized[i], keys_interface);
86             if (res instanceof Result_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ.Result_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ_Err) {
87                 throw new InvalidSerializedDataException("Serialized ChannelMonitor was corrupt");
88             }
89             byte[] block_hash = ((Result_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ.Result_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ_OK)res).res.get_a();
90             monitors[i] = ((Result_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ.Result_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ_OK) res).res.get_b();
91             this.channel_monitors[i] = TwoTuple_BlockHashChannelMonitorZ.of(block_hash, monitors[i]);
92             if (!monitor_funding_set.add(monitors[i].get_funding_txo().get_a()))
93                 throw new InvalidSerializedDataException("Set of ChannelMonitors contained duplicates (ie the same funding_txo was set on multiple monitors)");
94         }
95         Result_C2Tuple_BlockHashChannelManagerZDecodeErrorZ res =
96                 UtilMethods.C2Tuple_BlockHashChannelManagerZ_read(channel_manager_serialized, keys_interface, fee_estimator, chain_monitor.as_Watch(), tx_broadcaster,
97                         logger, config, monitors);
98         if (res instanceof Result_C2Tuple_BlockHashChannelManagerZDecodeErrorZ.Result_C2Tuple_BlockHashChannelManagerZDecodeErrorZ_Err) {
99             throw new InvalidSerializedDataException("Serialized ChannelManager was corrupt");
100         }
101         this.channel_manager = ((Result_C2Tuple_BlockHashChannelManagerZDecodeErrorZ.Result_C2Tuple_BlockHashChannelManagerZDecodeErrorZ_OK)res).res.get_b();
102         this.channel_manager_latest_block_hash = ((Result_C2Tuple_BlockHashChannelManagerZDecodeErrorZ.Result_C2Tuple_BlockHashChannelManagerZDecodeErrorZ_OK)res).res.get_a();
103         this.chain_monitor = chain_monitor;
104         this.logger = logger;
105         byte[] random_data = keys_interface.get_secure_random_bytes();
106         this.net_graph = net_graph;
107         Result_SecretKeyNoneZ node_secret = keys_interface.get_node_secret(Recipient.LDKRecipient_Node);
108         assert node_secret.is_ok();
109         if (net_graph != null) {
110             //TODO: We really need to expose the Access here to let users prevent DoS issues
111             this.graph_msg_handler = NetGraphMsgHandler.of(net_graph, Option_AccessZ.none(), logger);
112             this.peer_manager = PeerManager.of(channel_manager.as_ChannelMessageHandler(),
113                     graph_msg_handler.as_RoutingMessageHandler(),
114                     ((Result_SecretKeyNoneZ.Result_SecretKeyNoneZ_OK)node_secret).res,
115                     random_data, logger, no_custom_messages.as_CustomMessageHandler());
116         } else {
117             this.graph_msg_handler = null;
118             this.peer_manager = PeerManager.of(channel_manager.as_ChannelMessageHandler(), no_custom_messages.as_RoutingMessageHandler(),
119                     ((Result_SecretKeyNoneZ.Result_SecretKeyNoneZ_OK)node_secret).res,
120                     random_data, logger, no_custom_messages.as_CustomMessageHandler());
121         }
122         NioPeerHandler nio_peer_handler = null;
123         try {
124             nio_peer_handler = new NioPeerHandler(this.peer_manager);
125         } catch (IOException e) {
126             throw new IllegalStateException("We should never fail to construct nio objects unless we're on a platform that cannot run LDK.");
127         }
128         this.nio_peer_handler = nio_peer_handler;
129         if (filter != null) {
130             for (ChannelMonitor monitor : monitors) {
131                 monitor.load_outputs_to_watch(filter);
132             }
133         }
134     }
135
136     /**
137      * Constructs a channel manager from the given interface implementations
138      */
139     public ChannelManagerConstructor(Network network, UserConfig config, byte[] current_blockchain_tip_hash, int current_blockchain_tip_height,
140                                      KeysInterface keys_interface, FeeEstimator fee_estimator, ChainMonitor chain_monitor,
141                                      @Nullable NetworkGraph net_graph,
142                                      BroadcasterInterface tx_broadcaster, Logger logger) {
143         final IgnoringMessageHandler no_custom_messages = IgnoringMessageHandler.of();
144         channel_monitors = new TwoTuple_BlockHashChannelMonitorZ[0];
145         channel_manager_latest_block_hash = null;
146         this.chain_monitor = chain_monitor;
147         BestBlock block = BestBlock.of(current_blockchain_tip_hash, current_blockchain_tip_height);
148         ChainParameters params = ChainParameters.of(network, block);
149         channel_manager = ChannelManager.of(fee_estimator, chain_monitor.as_Watch(), tx_broadcaster, logger, keys_interface, config, params);
150         this.logger = logger;
151         byte[] random_data = keys_interface.get_secure_random_bytes();
152         this.net_graph = net_graph;
153         Result_SecretKeyNoneZ node_secret = keys_interface.get_node_secret(Recipient.LDKRecipient_Node);
154         assert node_secret.is_ok();
155         if (net_graph != null) {
156             //TODO: We really need to expose the Access here to let users prevent DoS issues
157             this.graph_msg_handler = NetGraphMsgHandler.of(net_graph, Option_AccessZ.none(), logger);
158             this.peer_manager = PeerManager.of(channel_manager.as_ChannelMessageHandler(),
159                     graph_msg_handler.as_RoutingMessageHandler(),
160                     ((Result_SecretKeyNoneZ.Result_SecretKeyNoneZ_OK)node_secret).res,
161                     random_data, logger, no_custom_messages.as_CustomMessageHandler());
162         } else {
163             this.graph_msg_handler = null;
164             this.peer_manager = PeerManager.of(channel_manager.as_ChannelMessageHandler(), no_custom_messages.as_RoutingMessageHandler(),
165                     ((Result_SecretKeyNoneZ.Result_SecretKeyNoneZ_OK)node_secret).res,
166                     random_data, logger, no_custom_messages.as_CustomMessageHandler());
167         }
168         NioPeerHandler nio_peer_handler = null;
169         try {
170             nio_peer_handler = new NioPeerHandler(this.peer_manager);
171         } catch (IOException e) {
172             throw new IllegalStateException("We should never fail to construct nio objects unless we're on a platform that cannot run LDK.");
173         }
174         this.nio_peer_handler = nio_peer_handler;
175     }
176
177     /**
178      * Abstract interface which should handle Events and persist the ChannelManager. When you call chain_sync_completed
179      * a background thread is started which will automatically call these methods for you when events occur.
180      */
181     public interface EventHandler {
182         void handle_event(Event events);
183         void persist_manager(byte[] channel_manager_bytes);
184     }
185
186     BackgroundProcessor background_processor = null;
187
188     /**
189      * Utility which adds all of the deserialized ChannelMonitors to the chain watch so that further updates from the
190      * ChannelManager are processed as normal.
191      *
192      * This also spawns a background thread which will call the appropriate methods on the provided
193      * EventHandler as required.
194      */
195     public void chain_sync_completed(EventHandler event_handler, @Nullable MultiThreadedLockableScore scorer) {
196         if (background_processor != null) { return; }
197         for (TwoTuple_BlockHashChannelMonitorZ monitor: channel_monitors) {
198             this.chain_monitor.as_Watch().watch_channel(monitor.get_b().get_funding_txo().get_a(), monitor.get_b());
199         }
200         org.ldk.structs.EventHandler ldk_handler = org.ldk.structs.EventHandler.new_impl(event_handler::handle_event);
201         if (this.net_graph != null && scorer != null) {
202             Router router = DefaultRouter.of(net_graph, logger).as_Router();
203             this.payer = InvoicePayer.of(this.channel_manager.as_Payer(), router, scorer, this.logger, ldk_handler, RetryAttempts.of(3));
204 assert this.payer != null;
205             ldk_handler = this.payer.as_EventHandler();
206         }
207
208         background_processor = BackgroundProcessor.start(org.ldk.structs.ChannelManagerPersister.new_impl(channel_manager -> {
209             event_handler.persist_manager(channel_manager.write());
210             return Result_NoneErrorZ.ok();
211         }), ldk_handler, this.chain_monitor, this.channel_manager, this.graph_msg_handler, this.peer_manager, this.logger);
212     }
213
214     /**
215      * Interrupt the background thread, stopping the background handling of events.
216      */
217     public void interrupt() {
218         this.nio_peer_handler.interrupt();
219         this.background_processor.stop();
220     }
221 }