d64c0d6e60d063c53b8dbad808a479e81a981f7d
[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.structs.*;
6 import org.ldk.util.TwoTuple;
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         if (net_graph != null) {
108             //TODO: We really need to expose the Access here to let users prevent DoS issues
109             this.graph_msg_handler = NetGraphMsgHandler.of(net_graph, Option_AccessZ.none(), logger);
110             this.peer_manager = PeerManager.of(channel_manager.as_ChannelMessageHandler(),
111                     graph_msg_handler.as_RoutingMessageHandler(),
112                     keys_interface.get_node_secret(), random_data, logger, no_custom_messages.as_CustomMessageHandler());
113         } else {
114             this.graph_msg_handler = null;
115             this.peer_manager = PeerManager.of(channel_manager.as_ChannelMessageHandler(), no_custom_messages.as_RoutingMessageHandler(),
116                     keys_interface.get_node_secret(), random_data, logger, no_custom_messages.as_CustomMessageHandler());
117         }
118         NioPeerHandler nio_peer_handler = null;
119         try {
120             nio_peer_handler = new NioPeerHandler(this.peer_manager);
121         } catch (IOException e) {
122             throw new IllegalStateException("We should never fail to construct nio objects unless we're on a platform that cannot run LDK.");
123         }
124         this.nio_peer_handler = nio_peer_handler;
125         if (filter != null) {
126             for (ChannelMonitor monitor : monitors) {
127                 monitor.load_outputs_to_watch(filter);
128             }
129         }
130     }
131
132     /**
133      * Constructs a channel manager from the given interface implementations
134      */
135     public ChannelManagerConstructor(Network network, UserConfig config, byte[] current_blockchain_tip_hash, int current_blockchain_tip_height,
136                                      KeysInterface keys_interface, FeeEstimator fee_estimator, ChainMonitor chain_monitor,
137                                      @Nullable NetworkGraph net_graph,
138                                      BroadcasterInterface tx_broadcaster, Logger logger) {
139         final IgnoringMessageHandler no_custom_messages = IgnoringMessageHandler.of();
140         channel_monitors = new TwoTuple_BlockHashChannelMonitorZ[0];
141         channel_manager_latest_block_hash = null;
142         this.chain_monitor = chain_monitor;
143         BestBlock block = BestBlock.of(current_blockchain_tip_hash, current_blockchain_tip_height);
144         ChainParameters params = ChainParameters.of(network, block);
145         channel_manager = ChannelManager.of(fee_estimator, chain_monitor.as_Watch(), tx_broadcaster, logger, keys_interface, config, params);
146         this.logger = logger;
147         byte[] random_data = keys_interface.get_secure_random_bytes();
148         this.net_graph = net_graph;
149         if (net_graph != null) {
150             //TODO: We really need to expose the Access here to let users prevent DoS issues
151             this.graph_msg_handler = NetGraphMsgHandler.of(net_graph, Option_AccessZ.none(), logger);
152             this.peer_manager = PeerManager.of(channel_manager.as_ChannelMessageHandler(),
153                     graph_msg_handler.as_RoutingMessageHandler(),
154                     keys_interface.get_node_secret(), random_data, logger, no_custom_messages.as_CustomMessageHandler());
155         } else {
156             this.graph_msg_handler = null;
157             this.peer_manager = PeerManager.of(channel_manager.as_ChannelMessageHandler(), no_custom_messages.as_RoutingMessageHandler(),
158                     keys_interface.get_node_secret(), random_data, logger, no_custom_messages.as_CustomMessageHandler());
159         }
160         NioPeerHandler nio_peer_handler = null;
161         try {
162             nio_peer_handler = new NioPeerHandler(this.peer_manager);
163         } catch (IOException e) {
164             throw new IllegalStateException("We should never fail to construct nio objects unless we're on a platform that cannot run LDK.");
165         }
166         this.nio_peer_handler = nio_peer_handler;
167     }
168
169     /**
170      * Abstract interface which should handle Events and persist the ChannelManager. When you call chain_sync_completed
171      * a background thread is started which will automatically call these methods for you when events occur.
172      */
173     public interface EventHandler {
174         void handle_event(Event events);
175         void persist_manager(byte[] channel_manager_bytes);
176     }
177
178     BackgroundProcessor background_processor = null;
179
180     /**
181      * Utility which adds all of the deserialized ChannelMonitors to the chain watch so that further updates from the
182      * ChannelManager are processed as normal.
183      *
184      * This also spawns a background thread which will call the appropriate methods on the provided
185      * EventHandler as required.
186      */
187     public void chain_sync_completed(EventHandler event_handler, @Nullable MultiThreadedLockableScore scorer) {
188         if (background_processor != null) { return; }
189         for (TwoTuple_BlockHashChannelMonitorZ monitor: channel_monitors) {
190             this.chain_monitor.as_Watch().watch_channel(monitor.get_b().get_funding_txo().get_a(), monitor.get_b());
191         }
192         org.ldk.structs.EventHandler ldk_handler = org.ldk.structs.EventHandler.new_impl(event_handler::handle_event);
193         if (this.net_graph != null && scorer != null) {
194             Router router = DefaultRouter.of(net_graph, logger).as_Router();
195             this.payer = InvoicePayer.of(this.channel_manager.as_Payer(), router, scorer, this.logger, ldk_handler, RetryAttempts.of(3));
196 assert this.payer != null;
197             ldk_handler = this.payer.as_EventHandler();
198         }
199
200         background_processor = BackgroundProcessor.start(org.ldk.structs.ChannelManagerPersister.new_impl(channel_manager -> {
201             event_handler.persist_manager(channel_manager.write());
202             return Result_NoneErrorZ.ok();
203         }), ldk_handler, this.chain_monitor, this.channel_manager, this.graph_msg_handler, this.peer_manager, this.logger);
204     }
205
206     /**
207      * Interrupt the background thread, stopping the background handling of events.
208      */
209     public void interrupt() {
210         this.nio_peer_handler.interrupt();
211         this.background_processor.stop();
212     }
213 }