8cf57536a5a0d58d94ab46dec31bca3f1755c865
[ldk-java] / src / main / java / org / ldk / batteries / ChannelManagerConstructor.java
1 package org.ldk.batteries;
2
3 import javax.annotation.Nullable;
4 import org.ldk.enums.Network;
5 import org.ldk.structs.*;
6 import org.ldk.util.TwoTuple;
7
8 import java.io.IOException;
9
10
11 /**
12  * A simple utility class which assists in constructing a fresh or deserializing from disk a ChannelManager and one or
13  * more ChannelMonitors.
14  *
15  * Also constructs a PeerManager and spawns a background thread to monitor for and notify you of relevant Events.
16  */
17 public class ChannelManagerConstructor {
18     /**
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.
21      */
22     public static class InvalidSerializedDataException extends Exception {}
23
24     /**
25      * The ChannelManager either deserialized or newly-constructed.
26      */
27     public final ChannelManager channel_manager;
28     /**
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.
31      */
32     public final byte[] channel_manager_latest_block_hash;
33     /**
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.
38      */
39     public final TwoTuple_BlockHashChannelMonitorZ[] channel_monitors;
40     /**
41      * A PeerManager which is constructed to pass messages and handle connections to peers.
42      */
43     public final PeerManager peer_manager;
44     /**
45      * A NioPeerHandler which manages a background thread to handle socket events and pass them to the peer_manager.
46      */
47     public final NioPeerHandler nio_peer_handler;
48
49     private final ChainMonitor chain_monitor;
50
51     private final Logger logger;
52
53     public final @Nullable NetGraphMsgHandler router;
54
55     /**
56      * Deserializes a channel manager and a set of channel monitors from the given serialized copies and interface implementations
57      *
58      * @param filter If provided, the outputs which were previously registered to be monitored for will be loaded into the filter.
59      *               Note that if the provided Watch is a ChainWatch and has an associated filter, the previously registered
60      *               outputs will be loaded when chain_sync_completed is called.
61      */
62     public ChannelManagerConstructor(byte[] channel_manager_serialized, byte[][] channel_monitors_serialized,
63                                      KeysInterface keys_interface, FeeEstimator fee_estimator, ChainMonitor chain_monitor, @Nullable Filter filter,
64                                      @Nullable NetGraphMsgHandler router,
65                                      BroadcasterInterface tx_broadcaster, Logger logger) throws InvalidSerializedDataException {
66         final IgnoringMessageHandler no_custom_messages = IgnoringMessageHandler.of();
67         final ChannelMonitor[] monitors = new ChannelMonitor[channel_monitors_serialized.length];
68         this.channel_monitors = new TwoTuple_BlockHashChannelMonitorZ[monitors.length];
69         for (int i = 0; i < monitors.length; i++) {
70             Result_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ res = UtilMethods.C2Tuple_BlockHashChannelMonitorZ_read(channel_monitors_serialized[i], keys_interface);
71             if (res instanceof Result_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ.Result_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ_Err) {
72                 throw new InvalidSerializedDataException();
73             }
74             byte[] block_hash = ((Result_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ.Result_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ_OK)res).res.get_a();
75             monitors[i] = ((Result_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ.Result_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ_OK) res).res.get_b();
76             this.channel_monitors[i] = TwoTuple_BlockHashChannelMonitorZ.of(block_hash, monitors[i]);
77         }
78         Result_C2Tuple_BlockHashChannelManagerZDecodeErrorZ res =
79                 UtilMethods.C2Tuple_BlockHashChannelManagerZ_read(channel_manager_serialized, keys_interface, fee_estimator, chain_monitor.as_Watch(), tx_broadcaster,
80                         logger, UserConfig.with_default(), monitors);
81         if (res instanceof Result_C2Tuple_BlockHashChannelManagerZDecodeErrorZ.Result_C2Tuple_BlockHashChannelManagerZDecodeErrorZ_Err) {
82             throw new InvalidSerializedDataException();
83         }
84         this.channel_manager = ((Result_C2Tuple_BlockHashChannelManagerZDecodeErrorZ.Result_C2Tuple_BlockHashChannelManagerZDecodeErrorZ_OK)res).res.get_b();
85         this.channel_manager_latest_block_hash = ((Result_C2Tuple_BlockHashChannelManagerZDecodeErrorZ.Result_C2Tuple_BlockHashChannelManagerZDecodeErrorZ_OK)res).res.get_a();
86         this.chain_monitor = chain_monitor;
87         this.router = router;
88         this.logger = logger;
89         byte[] random_data = keys_interface.get_secure_random_bytes();
90         if (router != null) {
91             this.peer_manager = PeerManager.of(channel_manager.as_ChannelMessageHandler(), router.as_RoutingMessageHandler(),
92                     keys_interface.get_node_secret(), random_data, logger, no_custom_messages.as_CustomMessageHandler());
93         } else {
94             this.peer_manager = PeerManager.of(channel_manager.as_ChannelMessageHandler(), (IgnoringMessageHandler.of()).as_RoutingMessageHandler(),
95                     keys_interface.get_node_secret(), random_data, logger, no_custom_messages.as_CustomMessageHandler());
96         }
97         NioPeerHandler nio_peer_handler = null;
98         try {
99             nio_peer_handler = new NioPeerHandler(this.peer_manager);
100         } catch (IOException e) {
101             throw new IllegalStateException("We should never fail to construct nio objects unless we're on a platform that cannot run LDK.");
102         }
103         this.nio_peer_handler = nio_peer_handler;
104         if (filter != null) {
105             for (ChannelMonitor monitor : monitors) {
106                 monitor.load_outputs_to_watch(filter);
107             }
108         }
109     }
110
111     /**
112      * Constructs a channel manager from the given interface implementations
113      */
114     public ChannelManagerConstructor(Network network, UserConfig config, byte[] current_blockchain_tip_hash, int current_blockchain_tip_height,
115                                      KeysInterface keys_interface, FeeEstimator fee_estimator, ChainMonitor chain_monitor,
116                                      @Nullable NetGraphMsgHandler router,
117                                      BroadcasterInterface tx_broadcaster, Logger logger) {
118         final IgnoringMessageHandler no_custom_messages = IgnoringMessageHandler.of();
119         channel_monitors = new TwoTuple_BlockHashChannelMonitorZ[0];
120         channel_manager_latest_block_hash = null;
121         this.chain_monitor = chain_monitor;
122         this.router = router;
123         BestBlock block = BestBlock.of(current_blockchain_tip_hash, current_blockchain_tip_height);
124         ChainParameters params = ChainParameters.of(network, block);
125         channel_manager = ChannelManager.of(fee_estimator, chain_monitor.as_Watch(), tx_broadcaster, logger, keys_interface, config, params);
126         this.logger = logger;
127         byte[] random_data = keys_interface.get_secure_random_bytes();
128         if (router != null) {
129             this.peer_manager = PeerManager.of(channel_manager.as_ChannelMessageHandler(), router.as_RoutingMessageHandler(),
130                     keys_interface.get_node_secret(), random_data, logger, no_custom_messages.as_CustomMessageHandler());
131         } else {
132             this.peer_manager = PeerManager.of(channel_manager.as_ChannelMessageHandler(), (IgnoringMessageHandler.of()).as_RoutingMessageHandler(),
133                     keys_interface.get_node_secret(), random_data, logger, no_custom_messages.as_CustomMessageHandler());
134         }
135         NioPeerHandler nio_peer_handler = null;
136         try {
137             nio_peer_handler = new NioPeerHandler(this.peer_manager);
138         } catch (IOException e) {
139             throw new IllegalStateException("We should never fail to construct nio objects unless we're on a platform that cannot run LDK.");
140         }
141         this.nio_peer_handler = nio_peer_handler;
142     }
143
144     /**
145      * Abstract interface which should handle Events and persist the ChannelManager. When you call chain_sync_completed
146      * a background thread is started which will automatically call these methods for you when events occur.
147      */
148     public interface EventHandler {
149         void handle_event(Event events);
150         void persist_manager(byte[] channel_manager_bytes);
151     }
152
153     BackgroundProcessor background_processor = null;
154
155     /**
156      * Utility which adds all of the deserialized ChannelMonitors to the chain watch so that further updates from the
157      * ChannelManager are processed as normal.
158      *
159      * This also spawns a background thread which will call the appropriate methods on the provided
160      * EventHandler as required.
161      */
162     public void chain_sync_completed(EventHandler event_handler) {
163         if (background_processor != null) { return; }
164         for (TwoTuple_BlockHashChannelMonitorZ monitor: channel_monitors) {
165             this.chain_monitor.as_Watch().watch_channel(monitor.get_b().get_funding_txo().get_a(), monitor.get_b());
166         }
167         background_processor = BackgroundProcessor.start(org.ldk.structs.ChannelManagerPersister.new_impl(channel_manager -> {
168             event_handler.persist_manager(channel_manager.write());
169             return Result_NoneErrorZ.ok();
170         }), org.ldk.structs.EventHandler.new_impl(event_handler::handle_event),
171         this.chain_monitor, this.channel_manager, this.router, this.peer_manager, this.logger);
172     }
173
174     /**
175      * Interrupt the background thread, stopping the background handling of events.
176      */
177     public void interrupt() {
178         this.background_processor.stop();
179         this.nio_peer_handler.interrupt();
180     }
181 }