1 package org.ldk.batteries;
3 import org.jetbrains.annotations.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;
91 try { nio_peer_handler = new NioPeerHandler(this.peer_manager); } catch (IOException e) { assert false; }
92 this.nio_peer_handler = nio_peer_handler;
94 for (ChannelMonitor monitor : monitors) {
95 monitor.load_outputs_to_watch(filter);
101 * Constructs a channel manager from the given interface implementations
103 public ChannelManagerConstructor(Network network, UserConfig config, byte[] current_blockchain_tip_hash, int current_blockchain_tip_height,
104 KeysInterface keys_interface, FeeEstimator fee_estimator, ChainMonitor chain_monitor,
105 @Nullable NetGraphMsgHandler router,
106 BroadcasterInterface tx_broadcaster, Logger logger) {
107 channel_monitors = new TwoTuple[0];
108 channel_manager_latest_block_hash = null;
109 this.chain_monitor = chain_monitor;
110 BestBlock block = BestBlock.of(current_blockchain_tip_hash, current_blockchain_tip_height);
111 ChainParameters params = ChainParameters.of(network, block);
112 channel_manager = ChannelManager.of(fee_estimator, chain_monitor.as_Watch(), tx_broadcaster, logger, keys_interface, config, params);
113 this.logger = logger;
114 byte[] random_data = keys_interface.get_secure_random_bytes();
115 if (router != null) {
116 this.peer_manager = PeerManager.of(channel_manager.as_ChannelMessageHandler(), router.as_RoutingMessageHandler(), keys_interface.get_node_secret(), random_data, logger);
118 this.peer_manager = PeerManager.of(channel_manager.as_ChannelMessageHandler(), (IgnoringMessageHandler.of()).as_RoutingMessageHandler(), keys_interface.get_node_secret(), random_data, logger);
120 NioPeerHandler nio_peer_handler = null;
121 try { nio_peer_handler = new NioPeerHandler(this.peer_manager); } catch (IOException e) { assert false; }
122 this.nio_peer_handler = nio_peer_handler;
126 * Abstract interface which should handle Events and persist the ChannelManager. When you call chain_sync_completed
127 * a background thread is started which will automatically call these methods for you when events occur.
129 public interface ChannelManagerPersister {
130 void handle_event(Event events);
131 void persist_manager(byte[] channel_manager_bytes);
134 BackgroundProcessor background_processor = null;
137 * Utility which adds all of the deserialized ChannelMonitors to the chain watch so that further updates from the
138 * ChannelManager are processed as normal.
140 * This also spawns a background thread which will call the appropriate methods on the provided
141 * ChannelManagerPersister as required.
143 public void chain_sync_completed(ChannelManagerPersister persister) {
144 if (background_processor != null) { return; }
145 for (TwoTuple<ChannelMonitor, byte[]> monitor: channel_monitors) {
146 this.chain_monitor.as_Watch().watch_channel(monitor.a.get_funding_txo().a, monitor.a);
148 background_processor = BackgroundProcessor.start(org.ldk.structs.ChannelManagerPersister.new_impl(channel_manager -> {
149 persister.persist_manager(channel_manager.write());
150 return Result_NoneErrorZ.ok();
151 }), EventHandler.new_impl(persister::handle_event),
152 this.chain_monitor, this.channel_manager, this.peer_manager, this.logger);
156 * Interrupt the background thread, stopping the background handling of events.
158 public void interrupt() {
159 this.background_processor.stop();
160 this.nio_peer_handler.interrupt();