[Java] Update LDK 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
66     /**
67      * The `NetworkGraph` deserialized from the byte given to the constructor when deserializing or the `NetworkGraph`
68      * given explicitly to the new-object constructor.
69      */
70     @Nullable public final NetworkGraph net_graph;
71     @Nullable private final NetGraphMsgHandler graph_msg_handler;
72     private final Logger logger;
73
74     private final byte[] router_rand_bytes;
75
76     /**
77      * Deserializes a channel manager and a set of channel monitors from the given serialized copies and interface implementations
78      *
79      * @param filter If provided, the outputs which were previously registered to be monitored for will be loaded into the filter.
80      *               Note that if the provided Watch is a ChainWatch and has an associated filter, the previously registered
81      *               outputs will be loaded when chain_sync_completed is called.
82      */
83     public ChannelManagerConstructor(byte[] channel_manager_serialized, byte[][] channel_monitors_serialized, UserConfig config,
84                                      KeysInterface keys_interface, FeeEstimator fee_estimator, ChainMonitor chain_monitor,
85                                      @Nullable Filter filter, @Nullable byte[] net_graph_serialized,
86                                      BroadcasterInterface tx_broadcaster, Logger logger) throws InvalidSerializedDataException {
87         final IgnoringMessageHandler no_custom_messages = IgnoringMessageHandler.of();
88         final ChannelMonitor[] monitors = new ChannelMonitor[channel_monitors_serialized.length];
89         this.channel_monitors = new TwoTuple_BlockHashChannelMonitorZ[monitors.length];
90         HashSet<OutPoint> monitor_funding_set = new HashSet();
91         for (int i = 0; i < monitors.length; i++) {
92             Result_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ res = UtilMethods.C2Tuple_BlockHashChannelMonitorZ_read(channel_monitors_serialized[i], keys_interface);
93             if (res instanceof Result_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ.Result_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ_Err) {
94                 throw new InvalidSerializedDataException("Serialized ChannelMonitor was corrupt");
95             }
96             byte[] block_hash = ((Result_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ.Result_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ_OK)res).res.get_a();
97             monitors[i] = ((Result_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ.Result_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ_OK) res).res.get_b();
98             this.channel_monitors[i] = TwoTuple_BlockHashChannelMonitorZ.of(block_hash, monitors[i]);
99             if (!monitor_funding_set.add(monitors[i].get_funding_txo().get_a()))
100                 throw new InvalidSerializedDataException("Set of ChannelMonitors contained duplicates (ie the same funding_txo was set on multiple monitors)");
101         }
102         Result_C2Tuple_BlockHashChannelManagerZDecodeErrorZ res =
103                 UtilMethods.C2Tuple_BlockHashChannelManagerZ_read(channel_manager_serialized, keys_interface, fee_estimator, chain_monitor.as_Watch(), tx_broadcaster,
104                         logger, config, monitors);
105         if (!res.is_ok()) {
106             throw new InvalidSerializedDataException("Serialized ChannelManager was corrupt");
107         }
108         this.channel_manager = ((Result_C2Tuple_BlockHashChannelManagerZDecodeErrorZ.Result_C2Tuple_BlockHashChannelManagerZDecodeErrorZ_OK)res).res.get_b();
109         this.channel_manager_latest_block_hash = ((Result_C2Tuple_BlockHashChannelManagerZDecodeErrorZ.Result_C2Tuple_BlockHashChannelManagerZDecodeErrorZ_OK)res).res.get_a();
110         this.chain_monitor = chain_monitor;
111         this.logger = logger;
112         byte[] random_data = keys_interface.get_secure_random_bytes();
113         if (net_graph_serialized != null) {
114             Result_NetworkGraphDecodeErrorZ graph_res = NetworkGraph.read(net_graph_serialized);
115             if (!graph_res.is_ok()) {
116                 throw new InvalidSerializedDataException("Serialized Network Graph was corrupt");
117             }
118             this.net_graph = ((Result_NetworkGraphDecodeErrorZ.Result_NetworkGraphDecodeErrorZ_OK)graph_res).res;
119         } else {
120             this.net_graph = null;
121         }
122         Result_SecretKeyNoneZ node_secret = keys_interface.get_node_secret(Recipient.LDKRecipient_Node);
123         assert node_secret.is_ok();
124         if (net_graph != null) {
125             //TODO: We really need to expose the Access here to let users prevent DoS issues
126             this.graph_msg_handler = NetGraphMsgHandler.of(net_graph, Option_AccessZ.none(), logger);
127             this.peer_manager = PeerManager.of(channel_manager.as_ChannelMessageHandler(),
128                     graph_msg_handler.as_RoutingMessageHandler(),
129                     ((Result_SecretKeyNoneZ.Result_SecretKeyNoneZ_OK)node_secret).res,
130                     random_data, logger, no_custom_messages.as_CustomMessageHandler());
131         } else {
132             this.graph_msg_handler = null;
133             this.peer_manager = PeerManager.of(channel_manager.as_ChannelMessageHandler(), no_custom_messages.as_RoutingMessageHandler(),
134                     ((Result_SecretKeyNoneZ.Result_SecretKeyNoneZ_OK)node_secret).res,
135                     random_data, logger, no_custom_messages.as_CustomMessageHandler());
136         }
137         NioPeerHandler nio_peer_handler = null;
138         try {
139             nio_peer_handler = new NioPeerHandler(this.peer_manager);
140         } catch (IOException e) {
141             throw new IllegalStateException("We should never fail to construct nio objects unless we're on a platform that cannot run LDK.");
142         }
143         this.nio_peer_handler = nio_peer_handler;
144         if (filter != null) {
145             for (ChannelMonitor monitor : monitors) {
146                 monitor.load_outputs_to_watch(filter);
147             }
148         }
149         router_rand_bytes = keys_interface.get_secure_random_bytes();
150     }
151
152     /**
153      * Constructs a channel manager from the given interface implementations
154      */
155     public ChannelManagerConstructor(Network network, UserConfig config, byte[] current_blockchain_tip_hash, int current_blockchain_tip_height,
156                                      KeysInterface keys_interface, FeeEstimator fee_estimator, ChainMonitor chain_monitor,
157                                      @Nullable NetworkGraph net_graph,
158                                      BroadcasterInterface tx_broadcaster, Logger logger) {
159         final IgnoringMessageHandler no_custom_messages = IgnoringMessageHandler.of();
160         channel_monitors = new TwoTuple_BlockHashChannelMonitorZ[0];
161         channel_manager_latest_block_hash = null;
162         this.chain_monitor = chain_monitor;
163         BestBlock block = BestBlock.of(current_blockchain_tip_hash, current_blockchain_tip_height);
164         ChainParameters params = ChainParameters.of(network, block);
165         channel_manager = ChannelManager.of(fee_estimator, chain_monitor.as_Watch(), tx_broadcaster, logger, keys_interface, config, params);
166         this.logger = logger;
167         byte[] random_data = keys_interface.get_secure_random_bytes();
168         this.net_graph = net_graph;
169         Result_SecretKeyNoneZ node_secret = keys_interface.get_node_secret(Recipient.LDKRecipient_Node);
170         assert node_secret.is_ok();
171         if (net_graph != null) {
172             //TODO: We really need to expose the Access here to let users prevent DoS issues
173             this.graph_msg_handler = NetGraphMsgHandler.of(net_graph, Option_AccessZ.none(), logger);
174             this.peer_manager = PeerManager.of(channel_manager.as_ChannelMessageHandler(),
175                     graph_msg_handler.as_RoutingMessageHandler(),
176                     ((Result_SecretKeyNoneZ.Result_SecretKeyNoneZ_OK)node_secret).res,
177                     random_data, logger, no_custom_messages.as_CustomMessageHandler());
178         } else {
179             this.graph_msg_handler = null;
180             this.peer_manager = PeerManager.of(channel_manager.as_ChannelMessageHandler(), no_custom_messages.as_RoutingMessageHandler(),
181                     ((Result_SecretKeyNoneZ.Result_SecretKeyNoneZ_OK)node_secret).res,
182                     random_data, logger, no_custom_messages.as_CustomMessageHandler());
183         }
184         NioPeerHandler nio_peer_handler = null;
185         try {
186             nio_peer_handler = new NioPeerHandler(this.peer_manager);
187         } catch (IOException e) {
188             throw new IllegalStateException("We should never fail to construct nio objects unless we're on a platform that cannot run LDK.");
189         }
190         this.nio_peer_handler = nio_peer_handler;
191         router_rand_bytes = keys_interface.get_secure_random_bytes();
192     }
193
194     /**
195      * Abstract interface which should handle Events and persist the ChannelManager. When you call chain_sync_completed
196      * a background thread is started which will automatically call these methods for you when events occur.
197      */
198     public interface EventHandler {
199         void handle_event(Event events);
200         void persist_manager(byte[] channel_manager_bytes);
201         void persist_network_graph(byte[] network_graph);
202     }
203
204     BackgroundProcessor background_processor = null;
205
206     /**
207      * Utility which adds all of the deserialized ChannelMonitors to the chain watch so that further updates from the
208      * ChannelManager are processed as normal.
209      *
210      * This also spawns a background thread which will call the appropriate methods on the provided
211      * EventHandler as required.
212      */
213     public void chain_sync_completed(EventHandler event_handler, @Nullable MultiThreadedLockableScore scorer) {
214         if (background_processor != null) { return; }
215         for (TwoTuple_BlockHashChannelMonitorZ monitor: channel_monitors) {
216             this.chain_monitor.as_Watch().watch_channel(monitor.get_b().get_funding_txo().get_a(), monitor.get_b());
217         }
218         org.ldk.structs.EventHandler ldk_handler = org.ldk.structs.EventHandler.new_impl(event_handler::handle_event);
219         if (this.net_graph != null && scorer != null) {
220             Router router = DefaultRouter.of(net_graph, logger, router_rand_bytes).as_Router();
221             this.payer = InvoicePayer.of(this.channel_manager.as_Payer(), router, scorer, this.logger, ldk_handler, RetryAttempts.of(3));
222 assert this.payer != null;
223             ldk_handler = this.payer.as_EventHandler();
224         }
225
226         background_processor = BackgroundProcessor.start(Persister.new_impl(new Persister.PersisterInterface() {
227             @Override
228             public Result_NoneErrorZ persist_manager(ChannelManager channel_manager) {
229                 event_handler.persist_manager(channel_manager.write());
230                 return Result_NoneErrorZ.ok();
231             }
232
233             @Override
234             public Result_NoneErrorZ persist_graph(NetworkGraph network_graph) {
235                 event_handler.persist_network_graph(network_graph.write());
236                 return Result_NoneErrorZ.ok();
237             }
238         }), ldk_handler, this.chain_monitor, this.channel_manager, this.graph_msg_handler, this.peer_manager, this.logger);
239     }
240
241     /**
242      * Interrupt the background thread, stopping the background handling of events.
243      */
244     public void interrupt() {
245         this.nio_peer_handler.interrupt();
246         this.background_processor.stop();
247     }
248 }