1 package org.ldk.batteries;
3 import javax.annotation.Nullable;
4 import org.ldk.enums.Network;
5 import org.ldk.enums.Recipient;
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 public final PeerManager peer_manager;
54 * A NioPeerHandler which manages a background thread to handle socket events and pass them to the peer_manager.
56 public final NioPeerHandler nio_peer_handler;
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.
61 * It should be used to send payments instead of doing so directly via the `channel_manager`.
63 * When payments are made through this, they are automatically retried and the provided Scorer
64 * will be updated with payment failure data.
66 @Nullable public InvoicePayer payer;
68 private final ChainMonitor chain_monitor;
71 * The `NetworkGraph` deserialized from the byte given to the constructor when deserializing or the `NetworkGraph`
72 * given explicitly to the new-object constructor.
74 @Nullable public final NetworkGraph net_graph;
75 @Nullable private final P2PGossipSync graph_msg_handler;
76 private final Logger logger;
78 private final byte[] router_rand_bytes;
81 * Deserializes a channel manager and a set of channel monitors from the given serialized copies and interface implementations
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.
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 ignoring_handler = 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");
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)");
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);
110 throw new InvalidSerializedDataException("Serialized ChannelManager was corrupt");
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");
122 this.net_graph = ((Result_NetworkGraphDecodeErrorZ.Result_NetworkGraphDecodeErrorZ_OK)graph_res).res;
124 this.net_graph = null;
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 ignoring_handler.as_OnionMessageHandler(),
134 ((Result_SecretKeyNoneZ.Result_SecretKeyNoneZ_OK)node_secret).res,
135 System.currentTimeMillis() / 1000,
136 random_data, logger, ignoring_handler.as_CustomMessageHandler());
138 this.graph_msg_handler = null;
139 this.peer_manager = PeerManager.of(channel_manager.as_ChannelMessageHandler(),
140 ignoring_handler.as_RoutingMessageHandler(),
141 ignoring_handler.as_OnionMessageHandler(),
142 ((Result_SecretKeyNoneZ.Result_SecretKeyNoneZ_OK)node_secret).res,
143 System.currentTimeMillis() / 1000,
144 random_data, logger, ignoring_handler.as_CustomMessageHandler());
146 NioPeerHandler nio_peer_handler = null;
148 nio_peer_handler = new NioPeerHandler(this.peer_manager);
149 } catch (IOException e) {
150 throw new IllegalStateException("We should never fail to construct nio objects unless we're on a platform that cannot run LDK.");
152 this.nio_peer_handler = nio_peer_handler;
153 if (filter != null) {
154 for (ChannelMonitor monitor : monitors) {
155 monitor.load_outputs_to_watch(filter);
158 router_rand_bytes = keys_interface.get_secure_random_bytes();
162 * Constructs a channel manager from the given interface implementations
164 public ChannelManagerConstructor(Network network, UserConfig config, byte[] current_blockchain_tip_hash, int current_blockchain_tip_height,
165 KeysInterface keys_interface, FeeEstimator fee_estimator, ChainMonitor chain_monitor,
166 @Nullable NetworkGraph net_graph,
167 BroadcasterInterface tx_broadcaster, Logger logger) {
168 final IgnoringMessageHandler ignoring_handler = IgnoringMessageHandler.of();
169 channel_monitors = new TwoTuple_BlockHashChannelMonitorZ[0];
170 channel_manager_latest_block_hash = null;
171 this.chain_monitor = chain_monitor;
172 BestBlock block = BestBlock.of(current_blockchain_tip_hash, current_blockchain_tip_height);
173 ChainParameters params = ChainParameters.of(network, block);
174 channel_manager = ChannelManager.of(fee_estimator, chain_monitor.as_Watch(), tx_broadcaster, logger, keys_interface, config, params);
175 this.logger = logger;
176 byte[] random_data = keys_interface.get_secure_random_bytes();
177 this.net_graph = net_graph;
178 Result_SecretKeyNoneZ node_secret = keys_interface.get_node_secret(Recipient.LDKRecipient_Node);
179 assert node_secret.is_ok();
180 if (net_graph != null) {
181 //TODO: We really need to expose the Access here to let users prevent DoS issues
182 this.graph_msg_handler = P2PGossipSync.of(net_graph, Option_AccessZ.none(), logger);
183 this.peer_manager = PeerManager.of(channel_manager.as_ChannelMessageHandler(),
184 graph_msg_handler.as_RoutingMessageHandler(),
185 ignoring_handler.as_OnionMessageHandler(),
186 ((Result_SecretKeyNoneZ.Result_SecretKeyNoneZ_OK)node_secret).res,
187 System.currentTimeMillis() / 1000,
188 random_data, logger, ignoring_handler.as_CustomMessageHandler());
190 this.graph_msg_handler = null;
191 this.peer_manager = PeerManager.of(channel_manager.as_ChannelMessageHandler(),
192 ignoring_handler.as_RoutingMessageHandler(),
193 ignoring_handler.as_OnionMessageHandler(),
194 ((Result_SecretKeyNoneZ.Result_SecretKeyNoneZ_OK)node_secret).res,
195 System.currentTimeMillis() / 1000,
196 random_data, logger, ignoring_handler.as_CustomMessageHandler());
198 NioPeerHandler nio_peer_handler = null;
200 nio_peer_handler = new NioPeerHandler(this.peer_manager);
201 } catch (IOException e) {
202 throw new IllegalStateException("We should never fail to construct nio objects unless we're on a platform that cannot run LDK.");
204 this.nio_peer_handler = nio_peer_handler;
205 router_rand_bytes = keys_interface.get_secure_random_bytes();
209 * Abstract interface which should handle Events and persist the ChannelManager. When you call chain_sync_completed
210 * a background thread is started which will automatically call these methods for you when events occur.
212 public interface EventHandler {
213 void handle_event(Event events);
214 void persist_manager(byte[] channel_manager_bytes);
215 void persist_network_graph(byte[] network_graph);
216 void persist_scorer(byte[] scorer_bytes);
219 BackgroundProcessor background_processor = null;
222 * Utility which adds all of the deserialized ChannelMonitors to the chain watch so that further updates from the
223 * ChannelManager are processed as normal.
225 * This also spawns a background thread which will call the appropriate methods on the provided
226 * EventHandler as required.
228 public void chain_sync_completed(EventHandler event_handler, @Nullable MultiThreadedLockableScore scorer) {
229 if (background_processor != null) { return; }
230 for (TwoTuple_BlockHashChannelMonitorZ monitor: channel_monitors) {
231 this.chain_monitor.as_Watch().watch_channel(monitor.get_b().get_funding_txo().get_a(), monitor.get_b());
233 org.ldk.structs.EventHandler ldk_handler = org.ldk.structs.EventHandler.new_impl(event_handler::handle_event);
234 if (this.net_graph != null && scorer != null) {
235 Router router = DefaultRouter.of(net_graph, logger, router_rand_bytes, scorer.as_LockableScore()).as_Router();
236 this.payer = InvoicePayer.of(this.channel_manager.as_Payer(), router, this.logger, ldk_handler, Retry.attempts(3));
237 ldk_handler = this.payer.as_EventHandler();
240 GossipSync gossip_sync;
241 if (this.graph_msg_handler == null)
242 gossip_sync = GossipSync.none();
244 gossip_sync = GossipSync.p2_p(this.graph_msg_handler);
246 Option_WriteableScoreZ writeable_score;
248 writeable_score = Option_WriteableScoreZ.some(scorer.as_WriteableScore());
250 writeable_score = Option_WriteableScoreZ.none();
252 background_processor = BackgroundProcessor.start(Persister.new_impl(new Persister.PersisterInterface() {
254 public Result_NoneErrorZ persist_manager(ChannelManager channel_manager) {
255 event_handler.persist_manager(channel_manager.write());
256 return Result_NoneErrorZ.ok();
260 public Result_NoneErrorZ persist_graph(NetworkGraph network_graph) {
261 event_handler.persist_network_graph(network_graph.write());
262 return Result_NoneErrorZ.ok();
266 public Result_NoneErrorZ persist_scorer(WriteableScore scorer) {
267 event_handler.persist_scorer(scorer.write());
268 return Result_NoneErrorZ.ok();
270 }), ldk_handler, this.chain_monitor, this.channel_manager, gossip_sync, this.peer_manager, this.logger, writeable_score);
274 * Interrupt the background thread, stopping the background handling of events.
276 public void interrupt() {
277 this.nio_peer_handler.interrupt();
278 this.background_processor.stop();