Update batteries and tests to latest upstream API
[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<ChannelMonitor, byte[]>[] 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[monitors.length];
69         for (int i = 0; i < monitors.length; i++) {
70             Result_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ res = UtilMethods.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             monitors[i] = ((Result_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ.Result_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ_OK) res).res.b;
75             this.channel_monitors[i] = new TwoTuple<>(monitors[i], ((Result_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ.Result_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ_OK)res).res.a);
76         }
77         Result_C2Tuple_BlockHashChannelManagerZDecodeErrorZ res =
78                 UtilMethods.BlockHashChannelManagerZ_read(channel_manager_serialized, keys_interface, fee_estimator, chain_monitor.as_Watch(), tx_broadcaster,
79                         logger, UserConfig.with_default(), monitors);
80         if (res instanceof Result_C2Tuple_BlockHashChannelManagerZDecodeErrorZ.Result_C2Tuple_BlockHashChannelManagerZDecodeErrorZ_Err) {
81             throw new InvalidSerializedDataException();
82         }
83         this.channel_manager = ((Result_C2Tuple_BlockHashChannelManagerZDecodeErrorZ.Result_C2Tuple_BlockHashChannelManagerZDecodeErrorZ_OK)res).res.b;
84         this.channel_manager_latest_block_hash = ((Result_C2Tuple_BlockHashChannelManagerZDecodeErrorZ.Result_C2Tuple_BlockHashChannelManagerZDecodeErrorZ_OK)res).res.a;
85         this.chain_monitor = chain_monitor;
86         this.router = router;
87         this.logger = logger;
88         byte[] random_data = keys_interface.get_secure_random_bytes();
89         if (router != null) {
90             this.peer_manager = PeerManager.of(channel_manager.as_ChannelMessageHandler(), router.as_RoutingMessageHandler(),
91                     keys_interface.get_node_secret(), random_data, logger, no_custom_messages.as_CustomMessageHandler());
92         } else {
93             this.peer_manager = PeerManager.of(channel_manager.as_ChannelMessageHandler(), (IgnoringMessageHandler.of()).as_RoutingMessageHandler(),
94                     keys_interface.get_node_secret(), random_data, logger, no_custom_messages.as_CustomMessageHandler());
95         }
96         NioPeerHandler nio_peer_handler = null;
97         try {
98             nio_peer_handler = new NioPeerHandler(this.peer_manager);
99         } catch (IOException e) {
100             throw new IllegalStateException("We should never fail to construct nio objects unless we're on a platform that cannot run LDK.");
101         }
102         this.nio_peer_handler = nio_peer_handler;
103         if (filter != null) {
104             for (ChannelMonitor monitor : monitors) {
105                 monitor.load_outputs_to_watch(filter);
106             }
107         }
108     }
109
110     /**
111      * Constructs a channel manager from the given interface implementations
112      */
113     public ChannelManagerConstructor(Network network, UserConfig config, byte[] current_blockchain_tip_hash, int current_blockchain_tip_height,
114                                      KeysInterface keys_interface, FeeEstimator fee_estimator, ChainMonitor chain_monitor,
115                                      @Nullable NetGraphMsgHandler router,
116                                      BroadcasterInterface tx_broadcaster, Logger logger) {
117         final IgnoringMessageHandler no_custom_messages = IgnoringMessageHandler.of();
118         channel_monitors = new TwoTuple[0];
119         channel_manager_latest_block_hash = null;
120         this.chain_monitor = chain_monitor;
121         this.router = router;
122         BestBlock block = BestBlock.of(current_blockchain_tip_hash, current_blockchain_tip_height);
123         ChainParameters params = ChainParameters.of(network, block);
124         channel_manager = ChannelManager.of(fee_estimator, chain_monitor.as_Watch(), tx_broadcaster, logger, keys_interface, config, params);
125         this.logger = logger;
126         byte[] random_data = keys_interface.get_secure_random_bytes();
127         if (router != null) {
128             this.peer_manager = PeerManager.of(channel_manager.as_ChannelMessageHandler(), router.as_RoutingMessageHandler(),
129                     keys_interface.get_node_secret(), random_data, logger, no_custom_messages.as_CustomMessageHandler());
130         } else {
131             this.peer_manager = PeerManager.of(channel_manager.as_ChannelMessageHandler(), (IgnoringMessageHandler.of()).as_RoutingMessageHandler(),
132                     keys_interface.get_node_secret(), random_data, logger, no_custom_messages.as_CustomMessageHandler());
133         }
134         NioPeerHandler nio_peer_handler = null;
135         try {
136             nio_peer_handler = new NioPeerHandler(this.peer_manager);
137         } catch (IOException e) {
138             throw new IllegalStateException("We should never fail to construct nio objects unless we're on a platform that cannot run LDK.");
139         }
140         this.nio_peer_handler = nio_peer_handler;
141     }
142
143     /**
144      * Abstract interface which should handle Events and persist the ChannelManager. When you call chain_sync_completed
145      * a background thread is started which will automatically call these methods for you when events occur.
146      */
147     public interface EventHandler {
148         void handle_event(Event events);
149         void persist_manager(byte[] channel_manager_bytes);
150     }
151
152     BackgroundProcessor background_processor = null;
153
154     /**
155      * Utility which adds all of the deserialized ChannelMonitors to the chain watch so that further updates from the
156      * ChannelManager are processed as normal.
157      *
158      * This also spawns a background thread which will call the appropriate methods on the provided
159      * EventHandler as required.
160      */
161     public void chain_sync_completed(EventHandler event_handler) {
162         if (background_processor != null) { return; }
163         for (TwoTuple<ChannelMonitor, byte[]> monitor: channel_monitors) {
164             this.chain_monitor.as_Watch().watch_channel(monitor.a.get_funding_txo().a, monitor.a);
165         }
166         background_processor = BackgroundProcessor.start(org.ldk.structs.ChannelManagerPersister.new_impl(channel_manager -> {
167             event_handler.persist_manager(channel_manager.write());
168             return Result_NoneErrorZ.ok();
169         }), org.ldk.structs.EventHandler.new_impl(event_handler::handle_event),
170         this.chain_monitor, this.channel_manager, this.router, this.peer_manager, this.logger);
171     }
172
173     /**
174      * Interrupt the background thread, stopping the background handling of events.
175      */
176     public void interrupt() {
177         this.background_processor.stop();
178         this.nio_peer_handler.interrupt();
179     }
180 }