1 package org.ldk.batteries;
3 import javax.annotation.Nullable;
4 import org.ldk.enums.Network;
5 import org.ldk.structs.*;
6 import org.ldk.util.TwoTuple;
8 import java.io.IOException;
12 * A simple utility class which assists in constructing a fresh or deserializing from disk a ChannelManager and one or
13 * more ChannelMonitors.
15 * Also constructs a PeerManager and spawns a background thread to monitor for and notify you of relevant Events.
17 public class ChannelManagerConstructor {
19 * An Exception that indicates the serialized data is invalid and has been corrupted on disk. You should attempt to
20 * restore from a backup if there is one which is known to be current. Otherwise, funds may have been lost.
22 public static class InvalidSerializedDataException extends Exception {}
25 * The ChannelManager either deserialized or newly-constructed.
27 public final ChannelManager channel_manager;
29 * The latest block has the channel manager saw. If this is non-null it is a 32-byte block hash.
30 * You should sync the blockchain starting with the block that builds on this block.
32 public final byte[] channel_manager_latest_block_hash;
34 * A list of ChannelMonitors and the last block they each saw. You should sync the blockchain on each individually
35 * starting with the block that builds on the hash given.
36 * After doing so (and syncing the blockchain on the channel manager as well), you should call chain_sync_completed()
37 * and then continue to normal application operation.
39 public final TwoTuple<ChannelMonitor, byte[]>[] channel_monitors;
41 * A PeerManager which is constructed to pass messages and handle connections to peers.
43 public final PeerManager peer_manager;
45 * A NioPeerHandler which manages a background thread to handle socket events and pass them to the peer_manager.
47 public final NioPeerHandler nio_peer_handler;
49 private final ChainMonitor chain_monitor;
51 private final Logger logger;
54 * Deserializes a channel manager and a set of channel monitors from the given serialized copies and interface implementations
56 * @param filter If provided, the outputs which were previously registered to be monitored for will be loaded into the filter.
57 * Note that if the provided Watch is a ChainWatch and has an associated filter, the previously registered
58 * outputs will be loaded when chain_sync_completed is called.
60 public ChannelManagerConstructor(byte[] channel_manager_serialized, byte[][] channel_monitors_serialized,
61 KeysInterface keys_interface, FeeEstimator fee_estimator, ChainMonitor chain_monitor, @Nullable Filter filter,
62 @Nullable NetGraphMsgHandler router,
63 BroadcasterInterface tx_broadcaster, Logger logger) throws InvalidSerializedDataException {
64 final ChannelMonitor[] monitors = new ChannelMonitor[channel_monitors_serialized.length];
65 this.channel_monitors = new TwoTuple[monitors.length];
66 for (int i = 0; i < monitors.length; i++) {
67 Result_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ res = UtilMethods.BlockHashChannelMonitorZ_read(channel_monitors_serialized[i], keys_interface);
68 if (res instanceof Result_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ.Result_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ_Err) {
69 throw new InvalidSerializedDataException();
71 monitors[i] = ((Result_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ.Result_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ_OK) res).res.b;
72 this.channel_monitors[i] = new TwoTuple<>(monitors[i], ((Result_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ.Result_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ_OK)res).res.a);
74 Result_C2Tuple_BlockHashChannelManagerZDecodeErrorZ res =
75 UtilMethods.BlockHashChannelManagerZ_read(channel_manager_serialized, keys_interface, fee_estimator, chain_monitor.as_Watch(), tx_broadcaster,
76 logger, UserConfig.with_default(), monitors);
77 if (res instanceof Result_C2Tuple_BlockHashChannelManagerZDecodeErrorZ.Result_C2Tuple_BlockHashChannelManagerZDecodeErrorZ_Err) {
78 throw new InvalidSerializedDataException();
80 this.channel_manager = ((Result_C2Tuple_BlockHashChannelManagerZDecodeErrorZ.Result_C2Tuple_BlockHashChannelManagerZDecodeErrorZ_OK)res).res.b;
81 this.channel_manager_latest_block_hash = ((Result_C2Tuple_BlockHashChannelManagerZDecodeErrorZ.Result_C2Tuple_BlockHashChannelManagerZDecodeErrorZ_OK)res).res.a;
82 this.chain_monitor = chain_monitor;
84 byte[] random_data = keys_interface.get_secure_random_bytes();
86 this.peer_manager = PeerManager.of(channel_manager.as_ChannelMessageHandler(), router.as_RoutingMessageHandler(), keys_interface.get_node_secret(), random_data, logger);
88 this.peer_manager = PeerManager.of(channel_manager.as_ChannelMessageHandler(), (IgnoringMessageHandler.of()).as_RoutingMessageHandler(), keys_interface.get_node_secret(), random_data, logger);
90 NioPeerHandler nio_peer_handler = null;
92 nio_peer_handler = new NioPeerHandler(this.peer_manager);
93 } catch (IOException e) {
94 throw new IllegalStateException("We should never fail to construct nio objects unless we're on a platform that cannot run LDK.");
96 this.nio_peer_handler = nio_peer_handler;
98 for (ChannelMonitor monitor : monitors) {
99 monitor.load_outputs_to_watch(filter);
105 * Constructs a channel manager from the given interface implementations
107 public ChannelManagerConstructor(Network network, UserConfig config, byte[] current_blockchain_tip_hash, int current_blockchain_tip_height,
108 KeysInterface keys_interface, FeeEstimator fee_estimator, ChainMonitor chain_monitor,
109 @Nullable NetGraphMsgHandler router,
110 BroadcasterInterface tx_broadcaster, Logger logger) {
111 channel_monitors = new TwoTuple[0];
112 channel_manager_latest_block_hash = null;
113 this.chain_monitor = chain_monitor;
114 BestBlock block = BestBlock.of(current_blockchain_tip_hash, current_blockchain_tip_height);
115 ChainParameters params = ChainParameters.of(network, block);
116 channel_manager = ChannelManager.of(fee_estimator, chain_monitor.as_Watch(), tx_broadcaster, logger, keys_interface, config, params);
117 this.logger = logger;
118 byte[] random_data = keys_interface.get_secure_random_bytes();
119 if (router != null) {
120 this.peer_manager = PeerManager.of(channel_manager.as_ChannelMessageHandler(), router.as_RoutingMessageHandler(), keys_interface.get_node_secret(), random_data, logger);
122 this.peer_manager = PeerManager.of(channel_manager.as_ChannelMessageHandler(), (IgnoringMessageHandler.of()).as_RoutingMessageHandler(), keys_interface.get_node_secret(), random_data, logger);
124 NioPeerHandler nio_peer_handler = null;
126 nio_peer_handler = new NioPeerHandler(this.peer_manager);
127 } catch (IOException e) {
128 throw new IllegalStateException("We should never fail to construct nio objects unless we're on a platform that cannot run LDK.");
130 this.nio_peer_handler = nio_peer_handler;
134 * Abstract interface which should handle Events and persist the ChannelManager. When you call chain_sync_completed
135 * a background thread is started which will automatically call these methods for you when events occur.
137 public interface ChannelManagerPersister {
138 void handle_event(Event events);
139 void persist_manager(byte[] channel_manager_bytes);
142 BackgroundProcessor background_processor = null;
145 * Utility which adds all of the deserialized ChannelMonitors to the chain watch so that further updates from the
146 * ChannelManager are processed as normal.
148 * This also spawns a background thread which will call the appropriate methods on the provided
149 * ChannelManagerPersister as required.
151 public void chain_sync_completed(ChannelManagerPersister persister) {
152 if (background_processor != null) { return; }
153 for (TwoTuple<ChannelMonitor, byte[]> monitor: channel_monitors) {
154 this.chain_monitor.as_Watch().watch_channel(monitor.a.get_funding_txo().a, monitor.a);
156 background_processor = BackgroundProcessor.start(org.ldk.structs.ChannelManagerPersister.new_impl(channel_manager -> {
157 persister.persist_manager(channel_manager.write());
158 return Result_NoneErrorZ.ok();
159 }), EventHandler.new_impl(persister::handle_event),
160 this.chain_monitor, this.channel_manager, this.peer_manager, this.logger);
164 * Interrupt the background thread, stopping the background handling of events.
166 public void interrupt() {
167 this.background_processor.stop();
168 this.nio_peer_handler.interrupt();