1 package org.ldk.batteries;
3 import javax.annotation.Nullable;
5 import org.ldk.enums.Network;
6 import org.ldk.structs.*;
8 import java.io.IOException;
9 import java.util.HashSet;
13 * A simple utility class which assists in constructing a fresh or deserializing from disk a ChannelManager and one or
14 * more ChannelMonitors.
16 * Also constructs a PeerManager and spawns a background thread to monitor for and notify you of relevant Events.
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
22 public class ChannelManagerConstructor {
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.
27 public static class InvalidSerializedDataException extends Exception {
28 InvalidSerializedDataException(String reason) {
34 * The ChannelManager either deserialized or newly-constructed.
36 public final ChannelManager channel_manager;
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.
41 public final byte[] channel_manager_latest_block_hash;
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.
48 public final TwoTuple_BlockHashChannelMonitorZ[] channel_monitors;
50 * A PeerManager which is constructed to pass messages and handle connections to peers.
52 * This is `null` until `chain_sync_completed` is called.
54 public PeerManager peer_manager = null;
56 * A NioPeerHandler which manages a background thread to handle socket events and pass them to the peer_manager.
58 * This is `null` until `chain_sync_completed` is called.
60 public NioPeerHandler nio_peer_handler = null;
62 private final ChainMonitor chain_monitor;
65 * The `NetworkGraph` deserialized from the byte given to the constructor when deserializing or the `NetworkGraph`
66 * given explicitly to the new-object constructor.
68 public final NetworkGraph net_graph;
71 * A mutex holding the `ProbabilisticScorer` which was loaded on startup.
73 public final MultiThreadedLockableScore scorer;
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.
79 private final ProbabilisticScorer prob_scorer;
80 private final Logger logger;
81 private final KeysManager keys_manager;
84 * Exposes the `ProbabilisticScorer` wrapped inside a lock. Don't forget to `close` this lock when you're done with
85 * it so normal scoring operation can continue.
87 public class ScorerWrapper implements AutoCloseable {
88 private final Score lock;
89 public final ProbabilisticScorer prob_scorer;
90 private ScorerWrapper(Score lock, ProbabilisticScorer prob_scorer) {
91 this.lock = lock; this.prob_scorer = prob_scorer;
93 @Override public void close() throws Exception {
98 * Gets the `ProbabilisticScorer` which backs the public lockable `scorer`. Don't forget to `close` the lock when
99 * you're done with it.
101 public ScorerWrapper get_locked_scorer() {
102 return new ScorerWrapper(this.scorer.as_LockableScore().lock(), this.prob_scorer);
106 * A simple interface to provide routes to LDK.
108 public interface RouterWrapper {
110 * Gets a route for the given payment.
112 * @param payment_hash is non-null for this-node-originated payments, however in the future trampoline or other
113 * HTLC re-routing may cause it to be null as we find routes for payments which we did not
115 * @param payment_id is non-null for this-node-originated payments, however in the future trampoline or other
116 * HTLC re-routing may cause it to be null as we find routes for payments which we did not
118 * @param default_router Provides a router which uses the LDK route-finder and a ProbabilisticScorer using the
119 * provided ProbabilisticScoringParameters. You may use this to fetch a "default" route,
120 * modifying or storing it as you wish before returning the route to LDK.
122 Result_RouteLightningErrorZ find_route(byte[] payer_node_id, RouteParameters route_params, ChannelDetails[] first_hops,
123 InFlightHtlcs inflight_htlcs, @Nullable byte[] payment_hash, @Nullable byte[] payment_id, DefaultRouter default_router);
127 * Deserializes a channel manager and a set of channel monitors from the given serialized copies and interface implementations
129 * @param filter If provided, the outputs which were previously registered to be monitored for will be loaded into the filter.
130 * Note that if the provided Watch is a ChainWatch and has an associated filter, the previously registered
131 * outputs will be loaded when chain_sync_completed is called.
132 * @param router_wrapper If provided, routes will be fetched by calling the given router rather than an LDK `DefaultRouter`.
134 public ChannelManagerConstructor(byte[] channel_manager_serialized, byte[][] channel_monitors_serialized, UserConfig config,
135 KeysManager keys_manager, FeeEstimator fee_estimator, ChainMonitor chain_monitor,
136 @Nullable Filter filter, byte[] net_graph_serialized,
137 ProbabilisticScoringParameters scoring_params, byte[] probabilistic_scorer_bytes,
138 @Nullable RouterWrapper router_wrapper,
139 BroadcasterInterface tx_broadcaster, Logger logger) throws InvalidSerializedDataException {
140 this.keys_manager = keys_manager;
141 EntropySource entropy_source = keys_manager.as_EntropySource();
143 Result_NetworkGraphDecodeErrorZ graph_res = NetworkGraph.read(net_graph_serialized, logger);
144 if (!graph_res.is_ok()) {
145 throw new InvalidSerializedDataException("Serialized Network Graph was corrupt");
147 this.net_graph = ((Result_NetworkGraphDecodeErrorZ.Result_NetworkGraphDecodeErrorZ_OK)graph_res).res;
148 assert(scoring_params != null);
149 assert(probabilistic_scorer_bytes != null);
150 Result_ProbabilisticScorerDecodeErrorZ scorer_res = ProbabilisticScorer.read(probabilistic_scorer_bytes, scoring_params, net_graph, logger);
151 if (!scorer_res.is_ok()) {
152 throw new InvalidSerializedDataException("Serialized ProbabilisticScorer was corrupt");
154 this.prob_scorer = ((Result_ProbabilisticScorerDecodeErrorZ.Result_ProbabilisticScorerDecodeErrorZ_OK)scorer_res).res;
155 this.scorer = MultiThreadedLockableScore.of(this.prob_scorer.as_Score());
157 DefaultRouter default_router = DefaultRouter.of(this.net_graph, logger, entropy_source.get_secure_random_bytes(), scorer.as_LockableScore());
159 if (router_wrapper != null) {
160 router = Router.new_impl(new Router.RouterInterface() {
161 @Override public Result_RouteLightningErrorZ find_route(byte[] payer, RouteParameters route_params, ChannelDetails[] first_hops, InFlightHtlcs inflight_htlcs) {
162 return router_wrapper.find_route(payer, route_params, first_hops, inflight_htlcs, null, null, default_router);
164 @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) {
165 return router_wrapper.find_route(payer, route_params, first_hops, inflight_htlcs, payment_hash, payment_id, default_router);
169 router = default_router.as_Router();
172 final ChannelMonitor[] monitors = new ChannelMonitor[channel_monitors_serialized.length];
173 this.channel_monitors = new TwoTuple_BlockHashChannelMonitorZ[monitors.length];
174 HashSet<OutPoint> monitor_funding_set = new HashSet();
175 for (int i = 0; i < monitors.length; i++) {
176 Result_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ res = UtilMethods.C2Tuple_BlockHashChannelMonitorZ_read(channel_monitors_serialized[i], entropy_source, keys_manager.as_SignerProvider());
177 if (res instanceof Result_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ.Result_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ_Err) {
178 throw new InvalidSerializedDataException("Serialized ChannelMonitor was corrupt");
180 byte[] block_hash = ((Result_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ.Result_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ_OK)res).res.get_a();
181 monitors[i] = ((Result_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ.Result_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ_OK) res).res.get_b();
182 this.channel_monitors[i] = TwoTuple_BlockHashChannelMonitorZ.of(block_hash, monitors[i]);
183 if (!monitor_funding_set.add(monitors[i].get_funding_txo().get_a()))
184 throw new InvalidSerializedDataException("Set of ChannelMonitors contained duplicates (ie the same funding_txo was set on multiple monitors)");
186 Result_C2Tuple_BlockHashChannelManagerZDecodeErrorZ res =
187 UtilMethods.C2Tuple_BlockHashChannelManagerZ_read(channel_manager_serialized, keys_manager.as_EntropySource(),
188 keys_manager.as_NodeSigner(), keys_manager.as_SignerProvider(), fee_estimator, chain_monitor.as_Watch(),
189 tx_broadcaster, router, logger, config, monitors);
191 throw new InvalidSerializedDataException("Serialized ChannelManager was corrupt");
193 this.channel_manager = ((Result_C2Tuple_BlockHashChannelManagerZDecodeErrorZ.Result_C2Tuple_BlockHashChannelManagerZDecodeErrorZ_OK)res).res.get_b();
194 this.channel_manager_latest_block_hash = ((Result_C2Tuple_BlockHashChannelManagerZDecodeErrorZ.Result_C2Tuple_BlockHashChannelManagerZDecodeErrorZ_OK)res).res.get_a();
195 this.chain_monitor = chain_monitor;
196 this.logger = logger;
197 if (filter != null) {
198 for (ChannelMonitor monitor : monitors) {
199 monitor.load_outputs_to_watch(filter);
205 * Constructs a channel manager from the given interface implementations
207 * @param router_wrapper If provided, routes will be fetched by calling the given router rather than an LDK `DefaultRouter`.
209 public ChannelManagerConstructor(Network network, UserConfig config, byte[] current_blockchain_tip_hash, int current_blockchain_tip_height,
210 KeysManager keys_manager, FeeEstimator fee_estimator, ChainMonitor chain_monitor,
211 NetworkGraph net_graph, ProbabilisticScoringParameters scoring_params,
212 @Nullable RouterWrapper router_wrapper,
213 BroadcasterInterface tx_broadcaster, Logger logger) {
214 this.keys_manager = keys_manager;
215 EntropySource entropy_source = keys_manager.as_EntropySource();
217 this.net_graph = net_graph;
218 assert(scoring_params != null);
219 this.prob_scorer = ProbabilisticScorer.of(scoring_params, net_graph, logger);
220 this.scorer = MultiThreadedLockableScore.of(this.prob_scorer.as_Score());
222 DefaultRouter default_router = DefaultRouter.of(this.net_graph, logger, entropy_source.get_secure_random_bytes(), scorer.as_LockableScore());
224 if (router_wrapper != null) {
225 router = Router.new_impl(new Router.RouterInterface() {
226 @Override public Result_RouteLightningErrorZ find_route(byte[] payer, RouteParameters route_params, ChannelDetails[] first_hops, InFlightHtlcs inflight_htlcs) {
227 return router_wrapper.find_route(payer, route_params, first_hops, inflight_htlcs, null, null, default_router);
229 @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) {
230 return router_wrapper.find_route(payer, route_params, first_hops, inflight_htlcs, payment_hash, payment_id, default_router);
234 router = default_router.as_Router();
236 channel_monitors = new TwoTuple_BlockHashChannelMonitorZ[0];
237 channel_manager_latest_block_hash = null;
238 this.chain_monitor = chain_monitor;
239 BestBlock block = BestBlock.of(current_blockchain_tip_hash, current_blockchain_tip_height);
240 ChainParameters params = ChainParameters.of(network, block);
241 channel_manager = ChannelManager.of(fee_estimator, chain_monitor.as_Watch(), tx_broadcaster, router, logger,
242 keys_manager.as_EntropySource(), keys_manager.as_NodeSigner(), keys_manager.as_SignerProvider(), config, params);
243 this.logger = logger;
247 * Abstract interface which should handle Events and persist the ChannelManager. When you call chain_sync_completed
248 * a background thread is started which will automatically call these methods for you when events occur.
250 public interface EventHandler {
251 void handle_event(Event events);
252 void persist_manager(byte[] channel_manager_bytes);
253 void persist_network_graph(byte[] network_graph);
254 void persist_scorer(byte[] scorer_bytes);
257 BackgroundProcessor background_processor = null;
260 * Utility which adds all of the deserialized ChannelMonitors to the chain watch so that further updates from the
261 * ChannelManager are processed as normal.
263 * This also spawns a background thread which will call the appropriate methods on the provided
264 * EventHandler as required.
266 * @param use_p2p_graph_sync determines if we will sync the network graph from peers over the standard (but
267 * inefficient) lightning P2P protocol. Note that doing so currently requires trusting
268 * peers as no DoS mechanism is enforced to ensure we don't accept bogus gossip.
269 * Alternatively, you may sync the net_graph exposed in this object via Rapid Gossip Sync.
271 public void chain_sync_completed(EventHandler event_handler, boolean use_p2p_graph_sync) {
272 if (background_processor != null) { return; }
273 for (TwoTuple_BlockHashChannelMonitorZ monitor: channel_monitors) {
274 this.chain_monitor.as_Watch().watch_channel(monitor.get_b().get_funding_txo().get_a(), monitor.get_b());
276 org.ldk.structs.EventHandler ldk_handler = org.ldk.structs.EventHandler.new_impl(event_handler::handle_event);
278 final IgnoringMessageHandler ignoring_handler = IgnoringMessageHandler.of();
279 P2PGossipSync graph_msg_handler = P2PGossipSync.of(net_graph, Option_UtxoLookupZ.none(), logger);
280 this.peer_manager = PeerManager.of(channel_manager.as_ChannelMessageHandler(),
281 ignoring_handler.as_RoutingMessageHandler(), ignoring_handler.as_OnionMessageHandler(),
282 (int)(System.currentTimeMillis() / 1000), this.keys_manager.as_EntropySource().get_secure_random_bytes(),
283 logger, ignoring_handler.as_CustomMessageHandler(), keys_manager.as_NodeSigner());
286 this.nio_peer_handler = new NioPeerHandler(peer_manager);
287 } catch (IOException e) {
288 throw new IllegalStateException("We should never fail to construct nio objects unless we're on a platform that cannot run LDK.");
291 GossipSync gossip_sync;
292 if (use_p2p_graph_sync)
293 gossip_sync = GossipSync.none();
295 gossip_sync = GossipSync.p2_p(graph_msg_handler);
297 Option_WriteableScoreZ writeable_score = Option_WriteableScoreZ.some(scorer.as_WriteableScore());
299 background_processor = BackgroundProcessor.start(Persister.new_impl(new Persister.PersisterInterface() {
301 public Result_NoneErrorZ persist_manager(ChannelManager channel_manager) {
302 event_handler.persist_manager(channel_manager.write());
303 return Result_NoneErrorZ.ok();
307 public Result_NoneErrorZ persist_graph(NetworkGraph network_graph) {
308 event_handler.persist_network_graph(network_graph.write());
309 return Result_NoneErrorZ.ok();
313 public Result_NoneErrorZ persist_scorer(WriteableScore scorer) {
314 event_handler.persist_scorer(scorer.write());
315 return Result_NoneErrorZ.ok();
317 }), ldk_handler, this.chain_monitor, this.channel_manager, gossip_sync, peer_manager, this.logger, writeable_score);
321 * Interrupt the background thread, stopping the background handling of events.
323 public void interrupt() {
324 if (this.nio_peer_handler != null)
325 this.nio_peer_handler.interrupt();
326 this.background_processor.stop();