109acbe39f505afa9cf1c272a9ef08b4e039511b
[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 no_custom_messages = 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                     ((Result_SecretKeyNoneZ.Result_SecretKeyNoneZ_OK)node_secret).res,
134                     random_data, logger, no_custom_messages.as_CustomMessageHandler());
135         } else {
136             this.graph_msg_handler = null;
137             this.peer_manager = PeerManager.of(channel_manager.as_ChannelMessageHandler(), no_custom_messages.as_RoutingMessageHandler(),
138                     ((Result_SecretKeyNoneZ.Result_SecretKeyNoneZ_OK)node_secret).res,
139                     random_data, logger, no_custom_messages.as_CustomMessageHandler());
140         }
141         NioPeerHandler nio_peer_handler = null;
142         try {
143             nio_peer_handler = new NioPeerHandler(this.peer_manager);
144         } catch (IOException e) {
145             throw new IllegalStateException("We should never fail to construct nio objects unless we're on a platform that cannot run LDK.");
146         }
147         this.nio_peer_handler = nio_peer_handler;
148         if (filter != null) {
149             for (ChannelMonitor monitor : monitors) {
150                 monitor.load_outputs_to_watch(filter);
151             }
152         }
153         router_rand_bytes = keys_interface.get_secure_random_bytes();
154     }
155
156     /**
157      * Constructs a channel manager from the given interface implementations
158      */
159     public ChannelManagerConstructor(Network network, UserConfig config, byte[] current_blockchain_tip_hash, int current_blockchain_tip_height,
160                                      KeysInterface keys_interface, FeeEstimator fee_estimator, ChainMonitor chain_monitor,
161                                      @Nullable NetworkGraph net_graph,
162                                      BroadcasterInterface tx_broadcaster, Logger logger) {
163         final IgnoringMessageHandler no_custom_messages = IgnoringMessageHandler.of();
164         channel_monitors = new TwoTuple_BlockHashChannelMonitorZ[0];
165         channel_manager_latest_block_hash = null;
166         this.chain_monitor = chain_monitor;
167         BestBlock block = BestBlock.of(current_blockchain_tip_hash, current_blockchain_tip_height);
168         ChainParameters params = ChainParameters.of(network, block);
169         channel_manager = ChannelManager.of(fee_estimator, chain_monitor.as_Watch(), tx_broadcaster, logger, keys_interface, config, params);
170         this.logger = logger;
171         byte[] random_data = keys_interface.get_secure_random_bytes();
172         this.net_graph = net_graph;
173         Result_SecretKeyNoneZ node_secret = keys_interface.get_node_secret(Recipient.LDKRecipient_Node);
174         assert node_secret.is_ok();
175         if (net_graph != null) {
176             //TODO: We really need to expose the Access here to let users prevent DoS issues
177             this.graph_msg_handler = P2PGossipSync.of(net_graph, Option_AccessZ.none(), logger);
178             this.peer_manager = PeerManager.of(channel_manager.as_ChannelMessageHandler(),
179                     graph_msg_handler.as_RoutingMessageHandler(),
180                     ((Result_SecretKeyNoneZ.Result_SecretKeyNoneZ_OK)node_secret).res,
181                     random_data, logger, no_custom_messages.as_CustomMessageHandler());
182         } else {
183             this.graph_msg_handler = null;
184             this.peer_manager = PeerManager.of(channel_manager.as_ChannelMessageHandler(), no_custom_messages.as_RoutingMessageHandler(),
185                     ((Result_SecretKeyNoneZ.Result_SecretKeyNoneZ_OK)node_secret).res,
186                     random_data, logger, no_custom_messages.as_CustomMessageHandler());
187         }
188         NioPeerHandler nio_peer_handler = null;
189         try {
190             nio_peer_handler = new NioPeerHandler(this.peer_manager);
191         } catch (IOException e) {
192             throw new IllegalStateException("We should never fail to construct nio objects unless we're on a platform that cannot run LDK.");
193         }
194         this.nio_peer_handler = nio_peer_handler;
195         router_rand_bytes = keys_interface.get_secure_random_bytes();
196     }
197
198     /**
199      * Abstract interface which should handle Events and persist the ChannelManager. When you call chain_sync_completed
200      * a background thread is started which will automatically call these methods for you when events occur.
201      */
202     public interface EventHandler {
203         void handle_event(Event events);
204         void persist_manager(byte[] channel_manager_bytes);
205         void persist_network_graph(byte[] network_graph);
206         void persist_scorer(byte[] scorer_bytes);
207     }
208
209     BackgroundProcessor background_processor = null;
210
211     /**
212      * Utility which adds all of the deserialized ChannelMonitors to the chain watch so that further updates from the
213      * ChannelManager are processed as normal.
214      *
215      * This also spawns a background thread which will call the appropriate methods on the provided
216      * EventHandler as required.
217      */
218     public void chain_sync_completed(EventHandler event_handler, @Nullable MultiThreadedLockableScore scorer) {
219         if (background_processor != null) { return; }
220         for (TwoTuple_BlockHashChannelMonitorZ monitor: channel_monitors) {
221             this.chain_monitor.as_Watch().watch_channel(monitor.get_b().get_funding_txo().get_a(), monitor.get_b());
222         }
223         org.ldk.structs.EventHandler ldk_handler = org.ldk.structs.EventHandler.new_impl(event_handler::handle_event);
224         if (this.net_graph != null && scorer != null) {
225             Router router = DefaultRouter.of(net_graph, logger, router_rand_bytes).as_Router();
226             this.payer = InvoicePayer.of(this.channel_manager.as_Payer(), router, scorer, this.logger, ldk_handler, Retry.attempts(3));
227 assert this.payer != null;
228             ldk_handler = this.payer.as_EventHandler();
229         }
230
231         GossipSync gossip_sync;
232         if (this.graph_msg_handler == null)
233             gossip_sync = GossipSync.none();
234         else
235             gossip_sync = GossipSync.p2_p(this.graph_msg_handler);
236
237         background_processor = BackgroundProcessor.start(Persister.new_impl(new Persister.PersisterInterface() {
238             @Override
239             public Result_NoneErrorZ persist_manager(ChannelManager channel_manager) {
240                 event_handler.persist_manager(channel_manager.write());
241                 return Result_NoneErrorZ.ok();
242             }
243
244             @Override
245             public Result_NoneErrorZ persist_graph(NetworkGraph network_graph) {
246                 event_handler.persist_network_graph(network_graph.write());
247                 return Result_NoneErrorZ.ok();
248             }
249
250             @Override
251             public Result_NoneErrorZ persist_scorer(MultiThreadedLockableScore scorer) {
252                 event_handler.persist_scorer(scorer.write());
253                 return Result_NoneErrorZ.ok();
254             }
255         }), ldk_handler, this.chain_monitor, this.channel_manager, gossip_sync, this.peer_manager, this.logger, scorer);
256     }
257
258     /**
259      * Interrupt the background thread, stopping the background handling of events.
260      */
261     public void interrupt() {
262         this.nio_peer_handler.interrupt();
263         this.background_processor.stop();
264     }
265 }