029fac792e0b407be50b8eeeb7ffe625ec4be2d0
[ldk-java] / src / main / java / org / ldk / batteries / ChannelManagerConstructor.java
1 package org.ldk.batteries;
2
3 import javax.annotation.Nullable;
4
5 import org.ldk.enums.Network;
6 import org.ldk.structs.*;
7
8 import java.io.IOException;
9 import java.util.HashSet;
10
11
12 /**
13  * A simple utility class which assists in constructing a fresh or deserializing from disk a ChannelManager and one or
14  * more ChannelMonitors.
15  *
16  * Also constructs a PeerManager and spawns a background thread to monitor for and notify you of relevant Events.
17  *
18  * Note that you must ensure you hold a reference to any constructed ChannelManagerConstructor objects to ensure you
19  * continue to receive events generated by the background thread which will be stopped if this object is garbage
20  * collected.
21  */
22 public class ChannelManagerConstructor {
23     /**
24      * An Exception that indicates the serialized data is invalid and has been corrupted on disk. You should attempt to
25      * restore from a backup if there is one which is known to be current. Otherwise, funds may have been lost.
26      */
27     public static class InvalidSerializedDataException extends Exception {
28         InvalidSerializedDataException(String reason) {
29             super(reason);
30         }
31     }
32
33     /**
34      * The ChannelManager either deserialized or newly-constructed.
35      */
36     public final ChannelManager channel_manager;
37     /**
38      * The latest block has the channel manager saw. If this is non-null it is a 32-byte block hash.
39      * You should sync the blockchain starting with the block that builds on this block.
40      */
41     public final byte[] channel_manager_latest_block_hash;
42     /**
43      * A list of ChannelMonitors and the last block they each saw. You should sync the blockchain on each individually
44      * starting with the block that builds on the hash given.
45      * After doing so (and syncing the blockchain on the channel manager as well), you should call chain_sync_completed()
46      * and then continue to normal application operation.
47      */
48     public final TwoTuple_BlockHashChannelMonitorZ[] channel_monitors;
49     /**
50      * A PeerManager which is constructed to pass messages and handle connections to peers.
51      *
52      * This is `null` until `chain_sync_completed` is called.
53      */
54     public PeerManager peer_manager = null;
55     /**
56      * A NioPeerHandler which manages a background thread to handle socket events and pass them to the peer_manager.
57          *
58          * This is `null` until `chain_sync_completed` is called.
59      */
60     public NioPeerHandler nio_peer_handler = null;
61
62     private final ChainMonitor chain_monitor;
63
64     /**
65      * The `NetworkGraph` deserialized from the byte given to the constructor when deserializing or the `NetworkGraph`
66      * given explicitly to the new-object constructor.
67      */
68     public final NetworkGraph net_graph;
69
70     /**
71      * A mutex holding the `ProbabilisticScorer` which was loaded on startup.
72      */
73     public final MultiThreadedLockableScore scorer;
74     /**
75      * We wrap the scorer in a MultiThreadedLockableScore which ultimately gates access to the scorer, however sometimes
76      * we want to expose underlying details of the scorer itself. Thus, we expose a safe version that takes the lock
77      * then returns a reference to this scorer.
78      */
79     @Nullable private final ProbabilisticScorer prob_scorer;
80     private final Logger logger;
81     private final KeysManager keys_manager;
82
83     /**
84      * Deserializes a channel manager and a set of channel monitors from the given serialized copies and interface implementations
85      *
86      * @param filter If provided, the outputs which were previously registered to be monitored for will be loaded into the filter.
87      *               Note that if the provided Watch is a ChainWatch and has an associated filter, the previously registered
88      *               outputs will be loaded when chain_sync_completed is called.
89      */
90     public ChannelManagerConstructor(byte[] channel_manager_serialized, byte[][] channel_monitors_serialized, UserConfig config,
91                                      KeysManager keys_manager, FeeEstimator fee_estimator, ChainMonitor chain_monitor,
92                                      @Nullable Filter filter, byte[] net_graph_serialized,
93                                      ProbabilisticScoringParameters scoring_params, byte[] probabilistic_scorer_bytes,
94                                      BroadcasterInterface tx_broadcaster, Logger logger) throws InvalidSerializedDataException {
95         this.keys_manager = keys_manager;
96         EntropySource entropy_source = keys_manager.as_EntropySource();
97
98         Result_NetworkGraphDecodeErrorZ graph_res = NetworkGraph.read(net_graph_serialized, logger);
99         if (!graph_res.is_ok()) {
100             throw new InvalidSerializedDataException("Serialized Network Graph was corrupt");
101         }
102         this.net_graph = ((Result_NetworkGraphDecodeErrorZ.Result_NetworkGraphDecodeErrorZ_OK)graph_res).res;
103         assert(scoring_params != null);
104         assert(probabilistic_scorer_bytes != null);
105         Result_ProbabilisticScorerDecodeErrorZ scorer_res = ProbabilisticScorer.read(probabilistic_scorer_bytes, scoring_params, net_graph, logger);
106         if (!scorer_res.is_ok()) {
107             throw new InvalidSerializedDataException("Serialized ProbabilisticScorer was corrupt");
108         }
109         this.prob_scorer = ((Result_ProbabilisticScorerDecodeErrorZ.Result_ProbabilisticScorerDecodeErrorZ_OK)scorer_res).res;
110         this.scorer = MultiThreadedLockableScore.of(this.prob_scorer.as_Score());
111         DefaultRouter router = DefaultRouter.of(this.net_graph, logger, entropy_source.get_secure_random_bytes(), scorer.as_LockableScore());
112
113         final ChannelMonitor[] monitors = new ChannelMonitor[channel_monitors_serialized.length];
114         this.channel_monitors = new TwoTuple_BlockHashChannelMonitorZ[monitors.length];
115         HashSet<OutPoint> monitor_funding_set = new HashSet();
116         for (int i = 0; i < monitors.length; i++) {
117             Result_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ res = UtilMethods.C2Tuple_BlockHashChannelMonitorZ_read(channel_monitors_serialized[i], entropy_source, keys_manager.as_SignerProvider());
118             if (res instanceof Result_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ.Result_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ_Err) {
119                 throw new InvalidSerializedDataException("Serialized ChannelMonitor was corrupt");
120             }
121             byte[] block_hash = ((Result_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ.Result_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ_OK)res).res.get_a();
122             monitors[i] = ((Result_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ.Result_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ_OK) res).res.get_b();
123             this.channel_monitors[i] = TwoTuple_BlockHashChannelMonitorZ.of(block_hash, monitors[i]);
124             if (!monitor_funding_set.add(monitors[i].get_funding_txo().get_a()))
125                 throw new InvalidSerializedDataException("Set of ChannelMonitors contained duplicates (ie the same funding_txo was set on multiple monitors)");
126         }
127         Result_C2Tuple_BlockHashChannelManagerZDecodeErrorZ res =
128                 UtilMethods.C2Tuple_BlockHashChannelManagerZ_read(channel_manager_serialized, keys_manager.as_EntropySource(),
129                         keys_manager.as_NodeSigner(), keys_manager.as_SignerProvider(), fee_estimator, chain_monitor.as_Watch(),
130                         tx_broadcaster, router.as_Router(), logger, config, monitors);
131         if (!res.is_ok()) {
132             throw new InvalidSerializedDataException("Serialized ChannelManager was corrupt");
133         }
134         this.channel_manager = ((Result_C2Tuple_BlockHashChannelManagerZDecodeErrorZ.Result_C2Tuple_BlockHashChannelManagerZDecodeErrorZ_OK)res).res.get_b();
135         this.channel_manager_latest_block_hash = ((Result_C2Tuple_BlockHashChannelManagerZDecodeErrorZ.Result_C2Tuple_BlockHashChannelManagerZDecodeErrorZ_OK)res).res.get_a();
136         this.chain_monitor = chain_monitor;
137         this.logger = logger;
138         if (filter != null) {
139             for (ChannelMonitor monitor : monitors) {
140                 monitor.load_outputs_to_watch(filter);
141             }
142         }
143     }
144
145     /**
146      * Constructs a channel manager from the given interface implementations
147      */
148     public ChannelManagerConstructor(Network network, UserConfig config, byte[] current_blockchain_tip_hash, int current_blockchain_tip_height,
149                                      KeysManager keys_manager, FeeEstimator fee_estimator, ChainMonitor chain_monitor,
150                                      NetworkGraph net_graph, ProbabilisticScoringParameters scoring_params,
151                                      BroadcasterInterface tx_broadcaster, Logger logger) {
152         this.keys_manager = keys_manager;
153         EntropySource entropy_source = keys_manager.as_EntropySource();
154
155         this.net_graph = net_graph;
156         assert(scoring_params != null);
157         this.prob_scorer = ProbabilisticScorer.of(scoring_params, net_graph, logger);
158         this.scorer = MultiThreadedLockableScore.of(this.prob_scorer.as_Score());
159         DefaultRouter router = DefaultRouter.of(this.net_graph, logger, entropy_source.get_secure_random_bytes(), scorer.as_LockableScore());
160
161         channel_monitors = new TwoTuple_BlockHashChannelMonitorZ[0];
162         channel_manager_latest_block_hash = null;
163         this.chain_monitor = chain_monitor;
164         BestBlock block = BestBlock.of(current_blockchain_tip_hash, current_blockchain_tip_height);
165         ChainParameters params = ChainParameters.of(network, block);
166         channel_manager = ChannelManager.of(fee_estimator, chain_monitor.as_Watch(), tx_broadcaster, router.as_Router(), logger,
167             keys_manager.as_EntropySource(), keys_manager.as_NodeSigner(), keys_manager.as_SignerProvider(), config, params);
168         this.logger = logger;
169     }
170
171     /**
172      * Abstract interface which should handle Events and persist the ChannelManager. When you call chain_sync_completed
173      * a background thread is started which will automatically call these methods for you when events occur.
174      */
175     public interface EventHandler {
176         void handle_event(Event events);
177         void persist_manager(byte[] channel_manager_bytes);
178         void persist_network_graph(byte[] network_graph);
179         void persist_scorer(byte[] scorer_bytes);
180     }
181
182     BackgroundProcessor background_processor = null;
183
184     /**
185      * Utility which adds all of the deserialized ChannelMonitors to the chain watch so that further updates from the
186      * ChannelManager are processed as normal.
187      *
188      * This also spawns a background thread which will call the appropriate methods on the provided
189      * EventHandler as required.
190      *
191      * @param use_p2p_graph_sync determines if we will sync the network graph from peers over the standard (but
192      *                           inefficient) lightning P2P protocol. Note that doing so currently requires trusting
193      *                           peers as no DoS mechanism is enforced to ensure we don't accept bogus gossip.
194      *                           Alternatively, you may sync the net_graph exposed in this object via Rapid Gossip Sync.
195      */
196     public void chain_sync_completed(EventHandler event_handler, boolean use_p2p_graph_sync) {
197         if (background_processor != null) { return; }
198         for (TwoTuple_BlockHashChannelMonitorZ monitor: channel_monitors) {
199             this.chain_monitor.as_Watch().watch_channel(monitor.get_b().get_funding_txo().get_a(), monitor.get_b());
200         }
201         org.ldk.structs.EventHandler ldk_handler = org.ldk.structs.EventHandler.new_impl(event_handler::handle_event);
202
203         final IgnoringMessageHandler ignoring_handler = IgnoringMessageHandler.of();
204         P2PGossipSync graph_msg_handler = P2PGossipSync.of(net_graph, Option_UtxoLookupZ.none(), logger);
205         this.peer_manager = PeerManager.of(channel_manager.as_ChannelMessageHandler(),
206                 ignoring_handler.as_RoutingMessageHandler(), ignoring_handler.as_OnionMessageHandler(),
207                 (int)(System.currentTimeMillis() / 1000), this.keys_manager.as_EntropySource().get_secure_random_bytes(),
208                 logger, ignoring_handler.as_CustomMessageHandler(), keys_manager.as_NodeSigner());
209
210         try {
211             this.nio_peer_handler = new NioPeerHandler(peer_manager);
212         } catch (IOException e) {
213             throw new IllegalStateException("We should never fail to construct nio objects unless we're on a platform that cannot run LDK.");
214         }
215
216         GossipSync gossip_sync;
217         if (use_p2p_graph_sync)
218             gossip_sync = GossipSync.none();
219         else
220             gossip_sync = GossipSync.p2_p(graph_msg_handler);
221
222         Option_WriteableScoreZ writeable_score = Option_WriteableScoreZ.some(scorer.as_WriteableScore());
223
224         background_processor = BackgroundProcessor.start(Persister.new_impl(new Persister.PersisterInterface() {
225             @Override
226             public Result_NoneErrorZ persist_manager(ChannelManager channel_manager) {
227                 event_handler.persist_manager(channel_manager.write());
228                 return Result_NoneErrorZ.ok();
229             }
230
231             @Override
232             public Result_NoneErrorZ persist_graph(NetworkGraph network_graph) {
233                 event_handler.persist_network_graph(network_graph.write());
234                 return Result_NoneErrorZ.ok();
235             }
236
237             @Override
238             public Result_NoneErrorZ persist_scorer(WriteableScore scorer) {
239                 event_handler.persist_scorer(scorer.write());
240                 return Result_NoneErrorZ.ok();
241             }
242         }), ldk_handler, this.chain_monitor, this.channel_manager, gossip_sync, peer_manager, this.logger, writeable_score);
243     }
244
245     /**
246      * Interrupt the background thread, stopping the background handling of events.
247      */
248     public void interrupt() {
249         if (this.nio_peer_handler != null)
250             this.nio_peer_handler.interrupt();
251         this.background_processor.stop();
252     }
253 }