Add support for InvoicePayer to ChannelManagerConstructor and test
[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      * If a `NetworkGraph` is provided to the constructor *and* a `LockableScore` is provided to
50          * `chain_sync_completed`, this will be non-null after `chain_sync_completed` returns.
51          *
52      * It should be used to send payments instead of doing so directly via the `channel_manager`.
53          *
54      * When payments are made through this, they are automatically retried and the provided Scorer
55      * will be updated with payment failure data.
56      */
57     @Nullable public InvoicePayer payer;
58
59     private final ChainMonitor chain_monitor;
60     @Nullable private final NetworkGraph net_graph;
61     @Nullable private final NetGraphMsgHandler graph_msg_handler;
62     private final Logger logger;
63
64     /**
65      * Deserializes a channel manager and a set of channel monitors from the given serialized copies and interface implementations
66      *
67      * @param filter If provided, the outputs which were previously registered to be monitored for will be loaded into the filter.
68      *               Note that if the provided Watch is a ChainWatch and has an associated filter, the previously registered
69      *               outputs will be loaded when chain_sync_completed is called.
70      */
71     public ChannelManagerConstructor(byte[] channel_manager_serialized, byte[][] channel_monitors_serialized,
72                                      KeysInterface keys_interface, FeeEstimator fee_estimator, ChainMonitor chain_monitor, @Nullable Filter filter,
73                                      @Nullable NetworkGraph net_graph,
74                                      BroadcasterInterface tx_broadcaster, Logger logger) throws InvalidSerializedDataException {
75         final IgnoringMessageHandler no_custom_messages = IgnoringMessageHandler.of();
76         final ChannelMonitor[] monitors = new ChannelMonitor[channel_monitors_serialized.length];
77         this.channel_monitors = new TwoTuple_BlockHashChannelMonitorZ[monitors.length];
78         for (int i = 0; i < monitors.length; i++) {
79             Result_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ res = UtilMethods.C2Tuple_BlockHashChannelMonitorZ_read(channel_monitors_serialized[i], keys_interface);
80             if (res instanceof Result_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ.Result_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ_Err) {
81                 throw new InvalidSerializedDataException();
82             }
83             byte[] block_hash = ((Result_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ.Result_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ_OK)res).res.get_a();
84             monitors[i] = ((Result_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ.Result_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ_OK) res).res.get_b();
85             this.channel_monitors[i] = TwoTuple_BlockHashChannelMonitorZ.of(block_hash, monitors[i]);
86         }
87         Result_C2Tuple_BlockHashChannelManagerZDecodeErrorZ res =
88                 UtilMethods.C2Tuple_BlockHashChannelManagerZ_read(channel_manager_serialized, keys_interface, fee_estimator, chain_monitor.as_Watch(), tx_broadcaster,
89                         logger, UserConfig.with_default(), monitors);
90         if (res instanceof Result_C2Tuple_BlockHashChannelManagerZDecodeErrorZ.Result_C2Tuple_BlockHashChannelManagerZDecodeErrorZ_Err) {
91             throw new InvalidSerializedDataException();
92         }
93         this.channel_manager = ((Result_C2Tuple_BlockHashChannelManagerZDecodeErrorZ.Result_C2Tuple_BlockHashChannelManagerZDecodeErrorZ_OK)res).res.get_b();
94         this.channel_manager_latest_block_hash = ((Result_C2Tuple_BlockHashChannelManagerZDecodeErrorZ.Result_C2Tuple_BlockHashChannelManagerZDecodeErrorZ_OK)res).res.get_a();
95         this.chain_monitor = chain_monitor;
96         this.logger = logger;
97         byte[] random_data = keys_interface.get_secure_random_bytes();
98         this.net_graph = net_graph;
99         if (net_graph != null) {
100             //TODO: We really need to expose the Access here to let users prevent DoS issues
101             this.graph_msg_handler = NetGraphMsgHandler.of(net_graph, Option_AccessZ.none(), logger);
102             this.peer_manager = PeerManager.of(channel_manager.as_ChannelMessageHandler(),
103                     graph_msg_handler.as_RoutingMessageHandler(),
104                     keys_interface.get_node_secret(), random_data, logger, no_custom_messages.as_CustomMessageHandler());
105         } else {
106             this.graph_msg_handler = null;
107             this.peer_manager = PeerManager.of(channel_manager.as_ChannelMessageHandler(), no_custom_messages.as_RoutingMessageHandler(),
108                     keys_interface.get_node_secret(), random_data, logger, no_custom_messages.as_CustomMessageHandler());
109         }
110         NioPeerHandler nio_peer_handler = null;
111         try {
112             nio_peer_handler = new NioPeerHandler(this.peer_manager);
113         } catch (IOException e) {
114             throw new IllegalStateException("We should never fail to construct nio objects unless we're on a platform that cannot run LDK.");
115         }
116         this.nio_peer_handler = nio_peer_handler;
117         if (filter != null) {
118             for (ChannelMonitor monitor : monitors) {
119                 monitor.load_outputs_to_watch(filter);
120             }
121         }
122     }
123
124     /**
125      * Constructs a channel manager from the given interface implementations
126      */
127     public ChannelManagerConstructor(Network network, UserConfig config, byte[] current_blockchain_tip_hash, int current_blockchain_tip_height,
128                                      KeysInterface keys_interface, FeeEstimator fee_estimator, ChainMonitor chain_monitor,
129                                      @Nullable NetworkGraph net_graph,
130                                      BroadcasterInterface tx_broadcaster, Logger logger) {
131         final IgnoringMessageHandler no_custom_messages = IgnoringMessageHandler.of();
132         channel_monitors = new TwoTuple_BlockHashChannelMonitorZ[0];
133         channel_manager_latest_block_hash = null;
134         this.chain_monitor = chain_monitor;
135         BestBlock block = BestBlock.of(current_blockchain_tip_hash, current_blockchain_tip_height);
136         ChainParameters params = ChainParameters.of(network, block);
137         channel_manager = ChannelManager.of(fee_estimator, chain_monitor.as_Watch(), tx_broadcaster, logger, keys_interface, config, params);
138         this.logger = logger;
139         byte[] random_data = keys_interface.get_secure_random_bytes();
140         this.net_graph = net_graph;
141         if (net_graph != null) {
142             //TODO: We really need to expose the Access here to let users prevent DoS issues
143             this.graph_msg_handler = NetGraphMsgHandler.of(net_graph, Option_AccessZ.none(), logger);
144             this.peer_manager = PeerManager.of(channel_manager.as_ChannelMessageHandler(),
145                     graph_msg_handler.as_RoutingMessageHandler(),
146                     keys_interface.get_node_secret(), random_data, logger, no_custom_messages.as_CustomMessageHandler());
147         } else {
148             this.graph_msg_handler = null;
149             this.peer_manager = PeerManager.of(channel_manager.as_ChannelMessageHandler(), no_custom_messages.as_RoutingMessageHandler(),
150                     keys_interface.get_node_secret(), random_data, logger, no_custom_messages.as_CustomMessageHandler());
151         }
152         NioPeerHandler nio_peer_handler = null;
153         try {
154             nio_peer_handler = new NioPeerHandler(this.peer_manager);
155         } catch (IOException e) {
156             throw new IllegalStateException("We should never fail to construct nio objects unless we're on a platform that cannot run LDK.");
157         }
158         this.nio_peer_handler = nio_peer_handler;
159     }
160
161     /**
162      * Abstract interface which should handle Events and persist the ChannelManager. When you call chain_sync_completed
163      * a background thread is started which will automatically call these methods for you when events occur.
164      */
165     public interface EventHandler {
166         void handle_event(Event events);
167         void persist_manager(byte[] channel_manager_bytes);
168     }
169
170     BackgroundProcessor background_processor = null;
171
172     /**
173      * Utility which adds all of the deserialized ChannelMonitors to the chain watch so that further updates from the
174      * ChannelManager are processed as normal.
175      *
176      * This also spawns a background thread which will call the appropriate methods on the provided
177      * EventHandler as required.
178      */
179     public void chain_sync_completed(EventHandler event_handler, @Nullable LockableScore scorer) {
180         if (background_processor != null) { return; }
181         for (TwoTuple_BlockHashChannelMonitorZ monitor: channel_monitors) {
182             this.chain_monitor.as_Watch().watch_channel(monitor.get_b().get_funding_txo().get_a(), monitor.get_b());
183         }
184         org.ldk.structs.EventHandler ldk_handler = org.ldk.structs.EventHandler.new_impl(event_handler::handle_event);
185         if (this.net_graph != null && scorer != null) {
186             Router router = DefaultRouter.of(net_graph, logger).as_Router();
187             this.payer = InvoicePayer.of(this.channel_manager.as_Payer(), router, scorer, this.logger, ldk_handler, RetryAttempts.of(3));
188 assert this.payer != null;
189             ldk_handler = this.payer.as_EventHandler();
190         }
191
192         background_processor = BackgroundProcessor.start(org.ldk.structs.ChannelManagerPersister.new_impl(channel_manager -> {
193             event_handler.persist_manager(channel_manager.write());
194             return Result_NoneErrorZ.ok();
195         }), ldk_handler, this.chain_monitor, this.channel_manager, this.graph_msg_handler, this.peer_manager, this.logger);
196     }
197
198     /**
199      * Interrupt the background thread, stopping the background handling of events.
200      */
201     public void interrupt() {
202         this.background_processor.stop();
203         this.nio_peer_handler.interrupt();
204     }
205 }