[Java] Build an `OnionMessenger` in CMC, connect ChanMan for offers
[ldk-java] / src / main / java / org / ldk / batteries / ChannelManagerConstructor.java
1 package org.ldk.batteries;
2
3 import javax.annotation.Nullable;
4
5 import org.ldk.enums.Network;
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_ThirtyTwoBytesChannelMonitorZ[] channel_monitors;
49     /**
50      * A PeerManager which is constructed to pass messages and handle connections to peers.
51      *
52      * This is `null` until `chain_sync_completed` is called.
53      */
54     public PeerManager peer_manager = null;
55     /**
56      * A NioPeerHandler which manages a background thread to handle socket events and pass them to the peer_manager.
57      *
58      * This is `null` until `chain_sync_completed` is called.
59      */
60     public NioPeerHandler nio_peer_handler = null;
61
62     private final ChainMonitor chain_monitor;
63
64     /**
65      * The `NetworkGraph` deserialized from the byte given to the constructor when deserializing or the `NetworkGraph`
66      * given explicitly to the new-object constructor.
67      */
68     public final NetworkGraph net_graph;
69
70     /**
71      * A mutex holding the `ProbabilisticScorer` which was loaded on startup.
72      */
73     public final MultiThreadedLockableScore scorer;
74     /**
75      * We wrap the scorer in a MultiThreadedLockableScore which ultimately gates access to the scorer, however sometimes
76      * we want to expose underlying details of the scorer itself. Thus, we expose a safe version that takes the lock
77      * then returns a reference to this scorer.
78      */
79     private final ProbabilisticScorer prob_scorer;
80     private final Logger logger;
81     private final EntropySource entropy_source;
82     private final NodeSigner node_signer;
83
84     /**
85      * Exposes the `ProbabilisticScorer` wrapped inside a lock. Don't forget to `close` this lock when you're done with
86      * it so normal scoring operation can continue.
87      */
88     public class ScorerWrapper implements AutoCloseable {
89         private final ScoreUpdate lock;
90         public final ProbabilisticScorer prob_scorer;
91         private ScorerWrapper(ScoreUpdate lock, ProbabilisticScorer prob_scorer) {
92             this.lock = lock; this.prob_scorer = prob_scorer;
93         }
94         @Override public void close() throws Exception {
95             lock.destroy();
96         }
97     }
98     /**
99      * Gets the `ProbabilisticScorer` which backs the public lockable `scorer`. Don't forget to `close` the lock when
100      * you're done with it.
101      */
102     public ScorerWrapper get_locked_scorer() {
103         return new ScorerWrapper(this.scorer.as_LockableScore().write_lock(), this.prob_scorer);
104     }
105
106     /**
107      * A simple interface to provide routes to LDK.
108      */
109     public interface RouterWrapper {
110         /**
111          * Gets a route for the given payment.
112          *
113          * @param payment_hash is non-null for this-node-originated payments, however in the future trampoline or other
114          *                     HTLC re-routing may cause it to be null as we find routes for payments which we did not
115          *                     originate.
116          * @param payment_id is non-null for this-node-originated payments, however in the future trampoline or other
117          *                   HTLC re-routing may cause it to be null as we find routes for payments which we did not
118          *                   originate.
119          * @param default_router Provides a router which uses the LDK route-finder and a ProbabilisticScorer using the
120          *                       provided ProbabilisticScoringParameters. You may use this to fetch a "default" route,
121          *                       modifying or storing it as you wish before returning the route to LDK.
122          */
123         Result_RouteLightningErrorZ find_route(byte[] payer_node_id, RouteParameters route_params, ChannelDetails[] first_hops,
124             InFlightHtlcs inflight_htlcs, @Nullable byte[] payment_hash, @Nullable byte[] payment_id, DefaultRouter default_router);
125     }
126
127     /**
128      * Deserializes a channel manager and a set of channel monitors from the given serialized copies and interface implementations
129      *
130      * @param filter If provided, the outputs which were previously registered to be monitored for will be loaded into the filter.
131      *               Note that if the provided Watch is a ChainWatch and has an associated filter, the previously registered
132      *               outputs will be loaded when chain_sync_completed is called.
133      * @param router_wrapper If provided, routes will be fetched by calling the given router rather than an LDK `DefaultRouter`.
134      */
135     public ChannelManagerConstructor(byte[] channel_manager_serialized, byte[][] channel_monitors_serialized, UserConfig config,
136                                      EntropySource entropy_source, NodeSigner node_signer, SignerProvider signer_provider,
137                                      FeeEstimator fee_estimator, ChainMonitor chain_monitor,
138                                      @Nullable Filter filter, byte[] net_graph_serialized,
139                                      ProbabilisticScoringDecayParameters scoring_decay_params,
140                                      ProbabilisticScoringFeeParameters scoring_fee_params,
141                                      byte[] probabilistic_scorer_bytes, @Nullable RouterWrapper router_wrapper,
142                                      BroadcasterInterface tx_broadcaster, Logger logger) throws InvalidSerializedDataException {
143         this.entropy_source = entropy_source;
144         this.node_signer = node_signer;
145
146         Result_NetworkGraphDecodeErrorZ graph_res = NetworkGraph.read(net_graph_serialized, logger);
147         if (!graph_res.is_ok()) {
148             throw new InvalidSerializedDataException("Serialized Network Graph was corrupt");
149         }
150         this.net_graph = ((Result_NetworkGraphDecodeErrorZ.Result_NetworkGraphDecodeErrorZ_OK)graph_res).res;
151         assert(scoring_decay_params != null);
152         assert(probabilistic_scorer_bytes != null);
153         Result_ProbabilisticScorerDecodeErrorZ scorer_res = ProbabilisticScorer.read(probabilistic_scorer_bytes, scoring_decay_params, net_graph, logger);
154         if (!scorer_res.is_ok()) {
155             throw new InvalidSerializedDataException("Serialized ProbabilisticScorer was corrupt");
156         }
157         this.prob_scorer = ((Result_ProbabilisticScorerDecodeErrorZ.Result_ProbabilisticScorerDecodeErrorZ_OK)scorer_res).res;
158         this.scorer = MultiThreadedLockableScore.of(this.prob_scorer.as_Score());
159
160         assert(scoring_fee_params != null);
161         DefaultRouter default_router = DefaultRouter.of(this.net_graph, logger, entropy_source.get_secure_random_bytes(), scorer.as_LockableScore(), scoring_fee_params);
162         Router router;
163         if (router_wrapper != null) {
164             router = Router.new_impl(new Router.RouterInterface() {
165                 @Override public Result_RouteLightningErrorZ find_route(byte[] payer, RouteParameters route_params, ChannelDetails[] first_hops, InFlightHtlcs inflight_htlcs) {
166                     return router_wrapper.find_route(payer, route_params, first_hops, inflight_htlcs, null, null, default_router);
167                 }
168                 @Override public Result_RouteLightningErrorZ find_route_with_id(byte[] payer, RouteParameters route_params, ChannelDetails[] first_hops, InFlightHtlcs inflight_htlcs, byte[] payment_hash, byte[] payment_id) {
169                     return router_wrapper.find_route(payer, route_params, first_hops, inflight_htlcs, payment_hash, payment_id, default_router);
170                 }
171             });
172         } else {
173             router = default_router.as_Router();
174         }
175
176         final ChannelMonitor[] monitors = new ChannelMonitor[channel_monitors_serialized.length];
177         this.channel_monitors = new TwoTuple_ThirtyTwoBytesChannelMonitorZ[monitors.length];
178         HashSet<OutPoint> monitor_funding_set = new HashSet();
179         for (int i = 0; i < monitors.length; i++) {
180             Result_C2Tuple_ThirtyTwoBytesChannelMonitorZDecodeErrorZ res = UtilMethods.C2Tuple_ThirtyTwoBytesChannelMonitorZ_read(channel_monitors_serialized[i], entropy_source, signer_provider);
181             if (res instanceof Result_C2Tuple_ThirtyTwoBytesChannelMonitorZDecodeErrorZ.Result_C2Tuple_ThirtyTwoBytesChannelMonitorZDecodeErrorZ_Err) {
182                 throw new InvalidSerializedDataException("Serialized ChannelMonitor was corrupt");
183             }
184             byte[] block_hash = ((Result_C2Tuple_ThirtyTwoBytesChannelMonitorZDecodeErrorZ.Result_C2Tuple_ThirtyTwoBytesChannelMonitorZDecodeErrorZ_OK)res).res.get_a();
185             monitors[i] = ((Result_C2Tuple_ThirtyTwoBytesChannelMonitorZDecodeErrorZ.Result_C2Tuple_ThirtyTwoBytesChannelMonitorZDecodeErrorZ_OK) res).res.get_b();
186             this.channel_monitors[i] = TwoTuple_ThirtyTwoBytesChannelMonitorZ.of(block_hash, monitors[i]);
187             if (!monitor_funding_set.add(monitors[i].get_funding_txo().get_a()))
188                 throw new InvalidSerializedDataException("Set of ChannelMonitors contained duplicates (ie the same funding_txo was set on multiple monitors)");
189         }
190         Result_C2Tuple_ThirtyTwoBytesChannelManagerZDecodeErrorZ res =
191                 UtilMethods.C2Tuple_ThirtyTwoBytesChannelManagerZ_read(channel_manager_serialized, entropy_source,
192                         node_signer, signer_provider, fee_estimator, chain_monitor.as_Watch(),
193                         tx_broadcaster, router, logger, config, monitors);
194         if (!res.is_ok()) {
195             throw new InvalidSerializedDataException("Serialized ChannelManager was corrupt");
196         }
197         this.channel_manager = ((Result_C2Tuple_ThirtyTwoBytesChannelManagerZDecodeErrorZ.Result_C2Tuple_ThirtyTwoBytesChannelManagerZDecodeErrorZ_OK)res).res.get_b();
198         this.channel_manager_latest_block_hash = ((Result_C2Tuple_ThirtyTwoBytesChannelManagerZDecodeErrorZ.Result_C2Tuple_ThirtyTwoBytesChannelManagerZDecodeErrorZ_OK)res).res.get_a();
199         this.chain_monitor = chain_monitor;
200         this.logger = logger;
201         if (filter != null) {
202             for (ChannelMonitor monitor : monitors) {
203                 monitor.load_outputs_to_watch(filter);
204             }
205         }
206     }
207
208     /**
209      * Constructs a channel manager from the given interface implementations
210      *
211      * @param router_wrapper If provided, routes will be fetched by calling the given router rather than an LDK `DefaultRouter`.
212      */
213     public ChannelManagerConstructor(Network network, UserConfig config, byte[] current_blockchain_tip_hash, int current_blockchain_tip_height,
214                                      EntropySource entropy_source, NodeSigner node_signer, SignerProvider signer_provider,
215                                      FeeEstimator fee_estimator, ChainMonitor chain_monitor,
216                                      NetworkGraph net_graph, ProbabilisticScoringDecayParameters scoring_decay_params,
217                                      ProbabilisticScoringFeeParameters scoring_fee_params,
218                                      @Nullable RouterWrapper router_wrapper,
219                                      BroadcasterInterface tx_broadcaster, Logger logger) {
220         this.entropy_source = entropy_source;
221         this.node_signer = node_signer;
222         this.net_graph = net_graph;
223         assert(scoring_decay_params != null);
224         this.prob_scorer = ProbabilisticScorer.of(scoring_decay_params, net_graph, logger);
225         this.scorer = MultiThreadedLockableScore.of(this.prob_scorer.as_Score());
226
227         assert(scoring_fee_params != null);
228         DefaultRouter default_router = DefaultRouter.of(this.net_graph, logger, entropy_source.get_secure_random_bytes(), scorer.as_LockableScore(), scoring_fee_params);
229         Router router;
230         if (router_wrapper != null) {
231             router = Router.new_impl(new Router.RouterInterface() {
232                 @Override public Result_RouteLightningErrorZ find_route(byte[] payer, RouteParameters route_params, ChannelDetails[] first_hops, InFlightHtlcs inflight_htlcs) {
233                     return router_wrapper.find_route(payer, route_params, first_hops, inflight_htlcs, null, null, default_router);
234                 }
235                 @Override public Result_RouteLightningErrorZ find_route_with_id(byte[] payer, RouteParameters route_params, ChannelDetails[] first_hops, InFlightHtlcs inflight_htlcs, byte[] payment_hash, byte[] payment_id) {
236                     return router_wrapper.find_route(payer, route_params, first_hops, inflight_htlcs, payment_hash, payment_id, default_router);
237                 }
238             });
239         } else {
240             router = default_router.as_Router();
241         }
242         channel_monitors = new TwoTuple_ThirtyTwoBytesChannelMonitorZ[0];
243         channel_manager_latest_block_hash = null;
244         this.chain_monitor = chain_monitor;
245         BestBlock block = BestBlock.of(current_blockchain_tip_hash, current_blockchain_tip_height);
246         ChainParameters params = ChainParameters.of(network, block);
247         channel_manager = ChannelManager.of(fee_estimator, chain_monitor.as_Watch(), tx_broadcaster, router, logger,
248             entropy_source, node_signer, signer_provider, config, params, (int) (System.currentTimeMillis() / 1000));
249         this.logger = logger;
250     }
251
252     /**
253      * Abstract interface which should handle Events and persist the ChannelManager. When you call chain_sync_completed
254      * a background thread is started which will automatically call these methods for you when events occur.
255      */
256     public interface EventHandler {
257         void handle_event(Event events);
258         void persist_manager(byte[] channel_manager_bytes);
259         void persist_network_graph(byte[] network_graph);
260         void persist_scorer(byte[] scorer_bytes);
261     }
262
263     BackgroundProcessor background_processor = null;
264
265     /**
266      * Utility which adds all of the deserialized ChannelMonitors to the chain watch so that further updates from the
267      * ChannelManager are processed as normal.
268      *
269      * This also spawns a background thread which will call the appropriate methods on the provided
270      * EventHandler as required.
271      *
272      * @param use_p2p_graph_sync determines if we will sync the network graph from peers over the standard (but
273      *                           inefficient) lightning P2P protocol. Note that doing so currently requires trusting
274      *                           peers as no DoS mechanism is enforced to ensure we don't accept bogus gossip.
275      *                           Alternatively, you may sync the net_graph exposed in this object via Rapid Gossip Sync.
276      */
277     public void chain_sync_completed(EventHandler event_handler, boolean use_p2p_graph_sync) {
278         if (background_processor != null) { return; }
279         for (TwoTuple_ThirtyTwoBytesChannelMonitorZ monitor: channel_monitors) {
280             this.chain_monitor.as_Watch().watch_channel(monitor.get_b().get_funding_txo().get_a(), monitor.get_b());
281         }
282         org.ldk.structs.EventHandler ldk_handler = org.ldk.structs.EventHandler.new_impl(event_handler::handle_event);
283
284         final IgnoringMessageHandler ignoring_handler = IgnoringMessageHandler.of();
285         P2PGossipSync graph_msg_handler = P2PGossipSync.of(net_graph, Option_UtxoLookupZ.none(), logger);
286         RoutingMessageHandler routing_msg_handler;
287         if (use_p2p_graph_sync)
288             routing_msg_handler = graph_msg_handler.as_RoutingMessageHandler();
289         else
290             routing_msg_handler = ignoring_handler.as_RoutingMessageHandler();
291         OnionMessenger messenger = OnionMessenger.of(this.entropy_source, this.node_signer, this.logger, DefaultMessageRouter.of().as_MessageRouter(), channel_manager.as_OffersMessageHandler(), IgnoringMessageHandler.of().as_CustomOnionMessageHandler());
292         this.peer_manager = PeerManager.of(channel_manager.as_ChannelMessageHandler(),
293                 routing_msg_handler, messenger.as_OnionMessageHandler(),
294                 ignoring_handler.as_CustomMessageHandler(), (int)(System.currentTimeMillis() / 1000),
295                 this.entropy_source.get_secure_random_bytes(), logger, this.node_signer);
296
297         try {
298             this.nio_peer_handler = new NioPeerHandler(peer_manager);
299         } catch (IOException e) {
300             throw new IllegalStateException("We should never fail to construct nio objects unless we're on a platform that cannot run LDK.");
301         }
302
303         GossipSync gossip_sync;
304         if (use_p2p_graph_sync)
305             gossip_sync = GossipSync.p2_p(graph_msg_handler);
306         else
307             gossip_sync = GossipSync.none();
308
309         Option_WriteableScoreZ writeable_score = Option_WriteableScoreZ.some(scorer.as_WriteableScore());
310
311         background_processor = BackgroundProcessor.start(Persister.new_impl(new Persister.PersisterInterface() {
312             @Override
313             public Result_NoneIOErrorZ persist_manager(ChannelManager channel_manager) {
314                 event_handler.persist_manager(channel_manager.write());
315                 return Result_NoneIOErrorZ.ok();
316             }
317
318             @Override
319             public Result_NoneIOErrorZ persist_graph(NetworkGraph network_graph) {
320                 event_handler.persist_network_graph(network_graph.write());
321                 return Result_NoneIOErrorZ.ok();
322             }
323
324             @Override
325             public Result_NoneIOErrorZ persist_scorer(WriteableScore scorer) {
326                 event_handler.persist_scorer(scorer.write());
327                 return Result_NoneIOErrorZ.ok();
328             }
329         }), ldk_handler, this.chain_monitor, this.channel_manager, gossip_sync, peer_manager, this.logger, writeable_score);
330     }
331
332     /**
333      * Interrupt the background thread, stopping the background handling of events.
334      */
335     public void interrupt() {
336         if (this.nio_peer_handler != null)
337             this.nio_peer_handler.interrupt();
338         this.background_processor.stop();
339     }
340 }