[Java] Update ChannelManagerConstructor and tests to latest 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  * Note that you must ensure you hold a reference to any constructed ChannelManagerConstructor objects to ensure you
19  * continue to receive events generated by the background thread which will be stopped if this object is garbage
20  * collected.
21  */
22 public class ChannelManagerConstructor {
23     /**
24      * An Exception that indicates the serialized data is invalid and has been corrupted on disk. You should attempt to
25      * restore from a backup if there is one which is known to be current. Otherwise, funds may have been lost.
26      */
27     public static class InvalidSerializedDataException extends Exception {
28         InvalidSerializedDataException(String reason) {
29             super(reason);
30         }
31     }
32
33     /**
34      * The ChannelManager either deserialized or newly-constructed.
35      */
36     public final ChannelManager channel_manager;
37     /**
38      * The latest block has the channel manager saw. If this is non-null it is a 32-byte block hash.
39      * You should sync the blockchain starting with the block that builds on this block.
40      */
41     public final byte[] channel_manager_latest_block_hash;
42     /**
43      * A list of ChannelMonitors and the last block they each saw. You should sync the blockchain on each individually
44      * starting with the block that builds on the hash given.
45      * After doing so (and syncing the blockchain on the channel manager as well), you should call chain_sync_completed()
46      * and then continue to normal application operation.
47      */
48     public final TwoTuple_BlockHashChannelMonitorZ[] channel_monitors;
49     /**
50      * A PeerManager which is constructed to pass messages and handle connections to peers.
51      */
52     public final PeerManager peer_manager;
53     /**
54      * A NioPeerHandler which manages a background thread to handle socket events and pass them to the peer_manager.
55      */
56     public final NioPeerHandler nio_peer_handler;
57     /**
58      * If a `NetworkGraph` is provided to the constructor *and* a `LockableScore` is provided to
59          * `chain_sync_completed`, this will be non-null after `chain_sync_completed` returns.
60          *
61      * It should be used to send payments instead of doing so directly via the `channel_manager`.
62          *
63      * When payments are made through this, they are automatically retried and the provided Scorer
64      * will be updated with payment failure data.
65      */
66     @Nullable public InvoicePayer payer;
67
68     private final ChainMonitor chain_monitor;
69
70     /**
71      * The `NetworkGraph` deserialized from the byte given to the constructor when deserializing or the `NetworkGraph`
72      * given explicitly to the new-object constructor.
73      */
74     @Nullable public final NetworkGraph net_graph;
75     @Nullable private final P2PGossipSync graph_msg_handler;
76     private final Logger logger;
77
78     private final byte[] router_rand_bytes;
79
80     /**
81      * Deserializes a channel manager and a set of channel monitors from the given serialized copies and interface implementations
82      *
83      * @param filter If provided, the outputs which were previously registered to be monitored for will be loaded into the filter.
84      *               Note that if the provided Watch is a ChainWatch and has an associated filter, the previously registered
85      *               outputs will be loaded when chain_sync_completed is called.
86      */
87     public ChannelManagerConstructor(byte[] channel_manager_serialized, byte[][] channel_monitors_serialized, UserConfig config,
88                                      KeysInterface keys_interface, FeeEstimator fee_estimator, ChainMonitor chain_monitor,
89                                      @Nullable Filter filter, @Nullable byte[] net_graph_serialized,
90                                      BroadcasterInterface tx_broadcaster, Logger logger) throws InvalidSerializedDataException {
91         final IgnoringMessageHandler ignoring_handler = IgnoringMessageHandler.of();
92         final ChannelMonitor[] monitors = new ChannelMonitor[channel_monitors_serialized.length];
93         this.channel_monitors = new TwoTuple_BlockHashChannelMonitorZ[monitors.length];
94         HashSet<OutPoint> monitor_funding_set = new HashSet();
95         for (int i = 0; i < monitors.length; i++) {
96             Result_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ res = UtilMethods.C2Tuple_BlockHashChannelMonitorZ_read(channel_monitors_serialized[i], keys_interface);
97             if (res instanceof Result_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ.Result_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ_Err) {
98                 throw new InvalidSerializedDataException("Serialized ChannelMonitor was corrupt");
99             }
100             byte[] block_hash = ((Result_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ.Result_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ_OK)res).res.get_a();
101             monitors[i] = ((Result_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ.Result_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ_OK) res).res.get_b();
102             this.channel_monitors[i] = TwoTuple_BlockHashChannelMonitorZ.of(block_hash, monitors[i]);
103             if (!monitor_funding_set.add(monitors[i].get_funding_txo().get_a()))
104                 throw new InvalidSerializedDataException("Set of ChannelMonitors contained duplicates (ie the same funding_txo was set on multiple monitors)");
105         }
106         Result_C2Tuple_BlockHashChannelManagerZDecodeErrorZ res =
107                 UtilMethods.C2Tuple_BlockHashChannelManagerZ_read(channel_manager_serialized, keys_interface, fee_estimator, chain_monitor.as_Watch(), tx_broadcaster,
108                         logger, config, monitors);
109         if (!res.is_ok()) {
110             throw new InvalidSerializedDataException("Serialized ChannelManager was corrupt");
111         }
112         this.channel_manager = ((Result_C2Tuple_BlockHashChannelManagerZDecodeErrorZ.Result_C2Tuple_BlockHashChannelManagerZDecodeErrorZ_OK)res).res.get_b();
113         this.channel_manager_latest_block_hash = ((Result_C2Tuple_BlockHashChannelManagerZDecodeErrorZ.Result_C2Tuple_BlockHashChannelManagerZDecodeErrorZ_OK)res).res.get_a();
114         this.chain_monitor = chain_monitor;
115         this.logger = logger;
116         byte[] random_data = keys_interface.get_secure_random_bytes();
117         if (net_graph_serialized != null) {
118             Result_NetworkGraphDecodeErrorZ graph_res = NetworkGraph.read(net_graph_serialized, logger);
119             if (!graph_res.is_ok()) {
120                 throw new InvalidSerializedDataException("Serialized Network Graph was corrupt");
121             }
122             this.net_graph = ((Result_NetworkGraphDecodeErrorZ.Result_NetworkGraphDecodeErrorZ_OK)graph_res).res;
123         } else {
124             this.net_graph = null;
125         }
126         Result_SecretKeyNoneZ node_secret = keys_interface.get_node_secret(Recipient.LDKRecipient_Node);
127         assert node_secret.is_ok();
128         if (net_graph != null) {
129             //TODO: We really need to expose the Access here to let users prevent DoS issues
130             this.graph_msg_handler = P2PGossipSync.of(net_graph, Option_AccessZ.none(), logger);
131             this.peer_manager = PeerManager.of(channel_manager.as_ChannelMessageHandler(),
132                     graph_msg_handler.as_RoutingMessageHandler(),
133                     ignoring_handler.as_OnionMessageHandler(),
134                     ((Result_SecretKeyNoneZ.Result_SecretKeyNoneZ_OK)node_secret).res,
135                     System.currentTimeMillis() / 1000,
136                     random_data, logger, ignoring_handler.as_CustomMessageHandler());
137         } else {
138             this.graph_msg_handler = null;
139             this.peer_manager = PeerManager.of(channel_manager.as_ChannelMessageHandler(),
140                     ignoring_handler.as_RoutingMessageHandler(),
141                     ignoring_handler.as_OnionMessageHandler(),
142                     ((Result_SecretKeyNoneZ.Result_SecretKeyNoneZ_OK)node_secret).res,
143                     System.currentTimeMillis() / 1000,
144                     random_data, logger, ignoring_handler.as_CustomMessageHandler());
145         }
146         NioPeerHandler nio_peer_handler = null;
147         try {
148             nio_peer_handler = new NioPeerHandler(this.peer_manager);
149         } catch (IOException e) {
150             throw new IllegalStateException("We should never fail to construct nio objects unless we're on a platform that cannot run LDK.");
151         }
152         this.nio_peer_handler = nio_peer_handler;
153         if (filter != null) {
154             for (ChannelMonitor monitor : monitors) {
155                 monitor.load_outputs_to_watch(filter);
156             }
157         }
158         router_rand_bytes = keys_interface.get_secure_random_bytes();
159     }
160
161     /**
162      * Constructs a channel manager from the given interface implementations
163      */
164     public ChannelManagerConstructor(Network network, UserConfig config, byte[] current_blockchain_tip_hash, int current_blockchain_tip_height,
165                                      KeysInterface keys_interface, FeeEstimator fee_estimator, ChainMonitor chain_monitor,
166                                      @Nullable NetworkGraph net_graph,
167                                      BroadcasterInterface tx_broadcaster, Logger logger) {
168         final IgnoringMessageHandler ignoring_handler = IgnoringMessageHandler.of();
169         channel_monitors = new TwoTuple_BlockHashChannelMonitorZ[0];
170         channel_manager_latest_block_hash = null;
171         this.chain_monitor = chain_monitor;
172         BestBlock block = BestBlock.of(current_blockchain_tip_hash, current_blockchain_tip_height);
173         ChainParameters params = ChainParameters.of(network, block);
174         channel_manager = ChannelManager.of(fee_estimator, chain_monitor.as_Watch(), tx_broadcaster, logger, keys_interface, config, params);
175         this.logger = logger;
176         byte[] random_data = keys_interface.get_secure_random_bytes();
177         this.net_graph = net_graph;
178         Result_SecretKeyNoneZ node_secret = keys_interface.get_node_secret(Recipient.LDKRecipient_Node);
179         assert node_secret.is_ok();
180         if (net_graph != null) {
181             //TODO: We really need to expose the Access here to let users prevent DoS issues
182             this.graph_msg_handler = P2PGossipSync.of(net_graph, Option_AccessZ.none(), logger);
183             this.peer_manager = PeerManager.of(channel_manager.as_ChannelMessageHandler(),
184                     graph_msg_handler.as_RoutingMessageHandler(),
185                     ignoring_handler.as_OnionMessageHandler(),
186                     ((Result_SecretKeyNoneZ.Result_SecretKeyNoneZ_OK)node_secret).res,
187                     System.currentTimeMillis() / 1000,
188                     random_data, logger, ignoring_handler.as_CustomMessageHandler());
189         } else {
190             this.graph_msg_handler = null;
191             this.peer_manager = PeerManager.of(channel_manager.as_ChannelMessageHandler(),
192                     ignoring_handler.as_RoutingMessageHandler(),
193                     ignoring_handler.as_OnionMessageHandler(),
194                     ((Result_SecretKeyNoneZ.Result_SecretKeyNoneZ_OK)node_secret).res,
195                     System.currentTimeMillis() / 1000,
196                     random_data, logger, ignoring_handler.as_CustomMessageHandler());
197         }
198         NioPeerHandler nio_peer_handler = null;
199         try {
200             nio_peer_handler = new NioPeerHandler(this.peer_manager);
201         } catch (IOException e) {
202             throw new IllegalStateException("We should never fail to construct nio objects unless we're on a platform that cannot run LDK.");
203         }
204         this.nio_peer_handler = nio_peer_handler;
205         router_rand_bytes = keys_interface.get_secure_random_bytes();
206     }
207
208     /**
209      * Abstract interface which should handle Events and persist the ChannelManager. When you call chain_sync_completed
210      * a background thread is started which will automatically call these methods for you when events occur.
211      */
212     public interface EventHandler {
213         void handle_event(Event events);
214         void persist_manager(byte[] channel_manager_bytes);
215         void persist_network_graph(byte[] network_graph);
216         void persist_scorer(byte[] scorer_bytes);
217     }
218
219     BackgroundProcessor background_processor = null;
220
221     /**
222      * Utility which adds all of the deserialized ChannelMonitors to the chain watch so that further updates from the
223      * ChannelManager are processed as normal.
224      *
225      * This also spawns a background thread which will call the appropriate methods on the provided
226      * EventHandler as required.
227      */
228     public void chain_sync_completed(EventHandler event_handler, @Nullable MultiThreadedLockableScore scorer) {
229         if (background_processor != null) { return; }
230         for (TwoTuple_BlockHashChannelMonitorZ monitor: channel_monitors) {
231             this.chain_monitor.as_Watch().watch_channel(monitor.get_b().get_funding_txo().get_a(), monitor.get_b());
232         }
233         org.ldk.structs.EventHandler ldk_handler = org.ldk.structs.EventHandler.new_impl(event_handler::handle_event);
234         if (this.net_graph != null && scorer != null) {
235             Router router = DefaultRouter.of(net_graph, logger, router_rand_bytes, scorer.as_LockableScore()).as_Router();
236             this.payer = InvoicePayer.of(this.channel_manager.as_Payer(), router, this.logger, ldk_handler, Retry.attempts(3));
237             ldk_handler = this.payer.as_EventHandler();
238         }
239
240         GossipSync gossip_sync;
241         if (this.graph_msg_handler == null)
242             gossip_sync = GossipSync.none();
243         else
244             gossip_sync = GossipSync.p2_p(this.graph_msg_handler);
245
246         Option_WriteableScoreZ writeable_score;
247         if (scorer != null)
248             writeable_score = Option_WriteableScoreZ.some(scorer.as_WriteableScore());
249         else
250             writeable_score = Option_WriteableScoreZ.none();
251
252         background_processor = BackgroundProcessor.start(Persister.new_impl(new Persister.PersisterInterface() {
253             @Override
254             public Result_NoneErrorZ persist_manager(ChannelManager channel_manager) {
255                 event_handler.persist_manager(channel_manager.write());
256                 return Result_NoneErrorZ.ok();
257             }
258
259             @Override
260             public Result_NoneErrorZ persist_graph(NetworkGraph network_graph) {
261                 event_handler.persist_network_graph(network_graph.write());
262                 return Result_NoneErrorZ.ok();
263             }
264
265             @Override
266             public Result_NoneErrorZ persist_scorer(WriteableScore scorer) {
267                 event_handler.persist_scorer(scorer.write());
268                 return Result_NoneErrorZ.ok();
269             }
270         }), ldk_handler, this.chain_monitor, this.channel_manager, gossip_sync, this.peer_manager, this.logger, writeable_score);
271     }
272
273     /**
274      * Interrupt the background thread, stopping the background handling of events.
275      */
276     public void interrupt() {
277         this.nio_peer_handler.interrupt();
278         this.background_processor.stop();
279     }
280 }