246c21a49adfc4629b547610a682e0757e4b9701
[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          * This is `null` until `chain_sync_completed` is called.
57      */
58     public NioPeerHandler nio_peer_handler = null;
59     /**
60      * If a `NetworkGraph` is provided to the constructor *and* a `LockableScore` is provided to
61          * `chain_sync_completed`, this will be non-null after `chain_sync_completed` returns.
62          *
63      * It should be used to send payments instead of doing so directly via the `channel_manager`.
64          *
65      * When payments are made through this, they are automatically retried and the provided Scorer
66      * will be updated with payment failure data.
67      */
68     @Nullable public InvoicePayer payer;
69
70     private final ChainMonitor chain_monitor;
71
72     /**
73      * The `NetworkGraph` deserialized from the byte given to the constructor when deserializing or the `NetworkGraph`
74      * given explicitly to the new-object constructor.
75      */
76     @Nullable public final NetworkGraph net_graph;
77     @Nullable private final P2PGossipSync graph_msg_handler;
78     private final Logger logger;
79
80     private final byte[] router_rand_bytes;
81
82     /**
83      * Deserializes a channel manager and a set of channel monitors from the given serialized copies and interface implementations
84      *
85      * @param filter If provided, the outputs which were previously registered to be monitored for will be loaded into the filter.
86      *               Note that if the provided Watch is a ChainWatch and has an associated filter, the previously registered
87      *               outputs will be loaded when chain_sync_completed is called.
88      */
89     public ChannelManagerConstructor(byte[] channel_manager_serialized, byte[][] channel_monitors_serialized, UserConfig config,
90                                      KeysInterface keys_interface, FeeEstimator fee_estimator, ChainMonitor chain_monitor,
91                                      @Nullable Filter filter, @Nullable byte[] net_graph_serialized,
92                                      BroadcasterInterface tx_broadcaster, Logger logger) throws InvalidSerializedDataException {
93         final IgnoringMessageHandler ignoring_handler = IgnoringMessageHandler.of();
94         final ChannelMonitor[] monitors = new ChannelMonitor[channel_monitors_serialized.length];
95         this.channel_monitors = new TwoTuple_BlockHashChannelMonitorZ[monitors.length];
96         HashSet<OutPoint> monitor_funding_set = new HashSet();
97         for (int i = 0; i < monitors.length; i++) {
98             Result_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ res = UtilMethods.C2Tuple_BlockHashChannelMonitorZ_read(channel_monitors_serialized[i], keys_interface);
99             if (res instanceof Result_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ.Result_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ_Err) {
100                 throw new InvalidSerializedDataException("Serialized ChannelMonitor was corrupt");
101             }
102             byte[] block_hash = ((Result_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ.Result_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ_OK)res).res.get_a();
103             monitors[i] = ((Result_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ.Result_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ_OK) res).res.get_b();
104             this.channel_monitors[i] = TwoTuple_BlockHashChannelMonitorZ.of(block_hash, monitors[i]);
105             if (!monitor_funding_set.add(monitors[i].get_funding_txo().get_a()))
106                 throw new InvalidSerializedDataException("Set of ChannelMonitors contained duplicates (ie the same funding_txo was set on multiple monitors)");
107         }
108         Result_C2Tuple_BlockHashChannelManagerZDecodeErrorZ res =
109                 UtilMethods.C2Tuple_BlockHashChannelManagerZ_read(channel_manager_serialized, keys_interface, fee_estimator, chain_monitor.as_Watch(), tx_broadcaster,
110                         logger, config, monitors);
111         if (!res.is_ok()) {
112             throw new InvalidSerializedDataException("Serialized ChannelManager was corrupt");
113         }
114         this.channel_manager = ((Result_C2Tuple_BlockHashChannelManagerZDecodeErrorZ.Result_C2Tuple_BlockHashChannelManagerZDecodeErrorZ_OK)res).res.get_b();
115         this.channel_manager_latest_block_hash = ((Result_C2Tuple_BlockHashChannelManagerZDecodeErrorZ.Result_C2Tuple_BlockHashChannelManagerZDecodeErrorZ_OK)res).res.get_a();
116         this.chain_monitor = chain_monitor;
117         this.logger = logger;
118         byte[] random_data = keys_interface.get_secure_random_bytes();
119         if (net_graph_serialized != null) {
120             Result_NetworkGraphDecodeErrorZ graph_res = NetworkGraph.read(net_graph_serialized, logger);
121             if (!graph_res.is_ok()) {
122                 throw new InvalidSerializedDataException("Serialized Network Graph was corrupt");
123             }
124             this.net_graph = ((Result_NetworkGraphDecodeErrorZ.Result_NetworkGraphDecodeErrorZ_OK)graph_res).res;
125         } else {
126             this.net_graph = null;
127         }
128         Result_SecretKeyNoneZ node_secret = keys_interface.get_node_secret(Recipient.LDKRecipient_Node);
129         assert node_secret.is_ok();
130         if (net_graph != null) {
131             //TODO: We really need to expose the Access here to let users prevent DoS issues
132             this.graph_msg_handler = P2PGossipSync.of(net_graph, Option_AccessZ.none(), logger);
133             this.peer_manager = PeerManager.of(channel_manager.as_ChannelMessageHandler(),
134                     graph_msg_handler.as_RoutingMessageHandler(),
135                     ignoring_handler.as_OnionMessageHandler(),
136                     ((Result_SecretKeyNoneZ.Result_SecretKeyNoneZ_OK)node_secret).res,
137                     (int)(System.currentTimeMillis() / 1000),
138                     random_data, logger, ignoring_handler.as_CustomMessageHandler());
139         } else {
140             this.graph_msg_handler = null;
141             this.peer_manager = PeerManager.of(channel_manager.as_ChannelMessageHandler(),
142                     ignoring_handler.as_RoutingMessageHandler(),
143                     ignoring_handler.as_OnionMessageHandler(),
144                     ((Result_SecretKeyNoneZ.Result_SecretKeyNoneZ_OK)node_secret).res,
145                     (int)(System.currentTimeMillis() / 1000),
146                     random_data, logger, ignoring_handler.as_CustomMessageHandler());
147         }
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 ignoring_handler = 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                     ignoring_handler.as_OnionMessageHandler(),
181                     ((Result_SecretKeyNoneZ.Result_SecretKeyNoneZ_OK)node_secret).res,
182                     (int)(System.currentTimeMillis() / 1000),
183                     random_data, logger, ignoring_handler.as_CustomMessageHandler());
184         } else {
185             this.graph_msg_handler = null;
186             this.peer_manager = PeerManager.of(channel_manager.as_ChannelMessageHandler(),
187                     ignoring_handler.as_RoutingMessageHandler(),
188                     ignoring_handler.as_OnionMessageHandler(),
189                     ((Result_SecretKeyNoneZ.Result_SecretKeyNoneZ_OK)node_secret).res,
190                     (int)(System.currentTimeMillis() / 1000),
191                     random_data, logger, ignoring_handler.as_CustomMessageHandler());
192         }
193         router_rand_bytes = keys_interface.get_secure_random_bytes();
194     }
195
196     /**
197      * Abstract interface which should handle Events and persist the ChannelManager. When you call chain_sync_completed
198      * a background thread is started which will automatically call these methods for you when events occur.
199      */
200     public interface EventHandler {
201         void handle_event(Event events);
202         void persist_manager(byte[] channel_manager_bytes);
203         void persist_network_graph(byte[] network_graph);
204         void persist_scorer(byte[] scorer_bytes);
205     }
206
207     BackgroundProcessor background_processor = null;
208
209     /**
210      * Utility which adds all of the deserialized ChannelMonitors to the chain watch so that further updates from the
211      * ChannelManager are processed as normal.
212      *
213      * This also spawns a background thread which will call the appropriate methods on the provided
214      * EventHandler as required.
215      */
216     public void chain_sync_completed(EventHandler event_handler, @Nullable MultiThreadedLockableScore scorer) {
217         try {
218             this.nio_peer_handler = new NioPeerHandler(this.peer_manager);
219         } catch (IOException e) {
220             throw new IllegalStateException("We should never fail to construct nio objects unless we're on a platform that cannot run LDK.");
221         }
222
223         if (background_processor != null) { return; }
224         for (TwoTuple_BlockHashChannelMonitorZ monitor: channel_monitors) {
225             this.chain_monitor.as_Watch().watch_channel(monitor.get_b().get_funding_txo().get_a(), monitor.get_b());
226         }
227         org.ldk.structs.EventHandler ldk_handler = org.ldk.structs.EventHandler.new_impl(event_handler::handle_event);
228         if (this.net_graph != null && scorer != null) {
229             Router router = DefaultRouter.of(net_graph, logger, router_rand_bytes, scorer.as_LockableScore()).as_Router();
230             this.payer = InvoicePayer.of(this.channel_manager.as_Payer(), router, this.logger, ldk_handler, Retry.attempts(3));
231             ldk_handler = this.payer.as_EventHandler();
232         }
233
234         GossipSync gossip_sync;
235         if (this.graph_msg_handler == null)
236             gossip_sync = GossipSync.none();
237         else
238             gossip_sync = GossipSync.p2_p(this.graph_msg_handler);
239
240         Option_WriteableScoreZ writeable_score;
241         if (scorer != null)
242             writeable_score = Option_WriteableScoreZ.some(scorer.as_WriteableScore());
243         else
244             writeable_score = Option_WriteableScoreZ.none();
245
246         background_processor = BackgroundProcessor.start(Persister.new_impl(new Persister.PersisterInterface() {
247             @Override
248             public Result_NoneErrorZ persist_manager(ChannelManager channel_manager) {
249                 event_handler.persist_manager(channel_manager.write());
250                 return Result_NoneErrorZ.ok();
251             }
252
253             @Override
254             public Result_NoneErrorZ persist_graph(NetworkGraph network_graph) {
255                 event_handler.persist_network_graph(network_graph.write());
256                 return Result_NoneErrorZ.ok();
257             }
258
259             @Override
260             public Result_NoneErrorZ persist_scorer(WriteableScore scorer) {
261                 event_handler.persist_scorer(scorer.write());
262                 return Result_NoneErrorZ.ok();
263             }
264         }), ldk_handler, this.chain_monitor, this.channel_manager, gossip_sync, this.peer_manager, this.logger, writeable_score);
265     }
266
267     /**
268      * Interrupt the background thread, stopping the background handling of events.
269      */
270     public void interrupt() {
271         if (this.nio_peer_handler != null)
272             this.nio_peer_handler.interrupt();
273         this.background_processor.stop();
274     }
275 }