Adapt ChannelManagerConstructor to persist ChannelManager + handle events
[ldk-java] / src / main / java / org / ldk / batteries / ChannelManagerConstructor.java
1 package org.ldk.batteries;
2
3 import org.jetbrains.annotations.Nullable;
4 import org.ldk.enums.LDKNetwork;
5 import org.ldk.structs.*;
6 import org.ldk.util.TwoTuple;
7
8
9 /**
10  * A simple utility class which assists in constructing a fresh or deserializing from disk a ChannelManager and one or
11  * more ChannelMonitors.
12  */
13 public class ChannelManagerConstructor {
14     /**
15      * An Exception that indicates the serialized data is invalid and has been corrupted on disk. You should attempt to
16      * restore from a backup if there is one which is known to be current. Otherwise, funds may have been lost.
17      */
18     public static class InvalidSerializedDataException extends Exception {}
19
20     /**
21      * The ChannelManager either deserialized or newly-constructed.
22      */
23     public final ChannelManager channel_manager;
24     /**
25      * The latest block has the channel manager saw. If this is non-null it is a 32-byte block hash.
26      * You should sync the blockchain starting with the block that builds on this block.
27      */
28     public final byte[] channel_manager_latest_block_hash;
29     /**
30      * A list of ChannelMonitors and the last block they each saw. You should sync the blockchain on each individually
31      * starting with the block that builds on the hash given.
32      * After doing so (and syncing the blockchain on the channel manager as well), you should call chain_sync_completed()
33      * and then continue to normal application operation.
34      */
35     public final TwoTuple<ChannelMonitor, byte[]>[] channel_monitors;
36
37     private final ChainMonitor chain_monitor;
38
39     /**
40      * Deserializes a channel manager and a set of channel monitors from the given serialized copies and interface implementations
41      *
42      * @param filter If provided, the outputs which were previously registered to be monitored for will be loaded into the filter.
43      *               Note that if the provided Watch is a ChainWatch and has an associated filter, the previously registered
44      *               outputs will be loaded when chain_sync_completed is called.
45      */
46     public ChannelManagerConstructor(byte[] channel_manager_serialized, byte[][] channel_monitors_serialized,
47                                      KeysInterface keys_interface, FeeEstimator fee_estimator, ChainMonitor chain_monitor, @Nullable Filter filter,
48                                      BroadcasterInterface tx_broadcaster, Logger logger) throws InvalidSerializedDataException {
49         final ChannelMonitor[] monitors = new ChannelMonitor[channel_monitors_serialized.length];
50         this.channel_monitors = new TwoTuple[monitors.length];
51         for (int i = 0; i < monitors.length; i++) {
52             Result_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ res = UtilMethods.constructor_BlockHashChannelMonitorZ_read(channel_monitors_serialized[i], keys_interface);
53             if (res instanceof Result_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ.Result_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ_Err) {
54                 throw new InvalidSerializedDataException();
55             }
56             monitors[i] = ((Result_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ.Result_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ_OK) res).res.b;
57             this.channel_monitors[i] = new TwoTuple<>(monitors[i], ((Result_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ.Result_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ_OK)res).res.a);
58         }
59         Result_C2Tuple_BlockHashChannelManagerZDecodeErrorZ res =
60                 UtilMethods.constructor_BlockHashChannelManagerZ_read(channel_manager_serialized, keys_interface, fee_estimator, chain_monitor.as_Watch(), tx_broadcaster,
61                         logger, UserConfig.constructor_default(), monitors);
62         if (res instanceof Result_C2Tuple_BlockHashChannelManagerZDecodeErrorZ.Result_C2Tuple_BlockHashChannelManagerZDecodeErrorZ_Err) {
63             throw new InvalidSerializedDataException();
64         }
65         this.channel_manager = ((Result_C2Tuple_BlockHashChannelManagerZDecodeErrorZ.Result_C2Tuple_BlockHashChannelManagerZDecodeErrorZ_OK)res).res.b;
66         this.channel_manager_latest_block_hash = ((Result_C2Tuple_BlockHashChannelManagerZDecodeErrorZ.Result_C2Tuple_BlockHashChannelManagerZDecodeErrorZ_OK)res).res.a;
67         this.chain_monitor = chain_monitor;
68         if (filter != null) {
69             for (ChannelMonitor monitor : monitors) {
70                 monitor.load_outputs_to_watch(filter);
71             }
72         }
73     }
74
75     /**
76      * Constructs a channel manager from the given interface implementations
77      */
78     public ChannelManagerConstructor(LDKNetwork network, UserConfig config, byte[] current_blockchain_tip_hash, int current_blockchain_tip_height,
79                                      KeysInterface keys_interface, FeeEstimator fee_estimator, ChainMonitor chain_monitor,
80                                      BroadcasterInterface tx_broadcaster, Logger logger) throws InvalidSerializedDataException {
81         channel_monitors = new TwoTuple[0];
82         channel_manager_latest_block_hash = null;
83         this.chain_monitor = chain_monitor;
84         channel_manager = ChannelManager.constructor_new(fee_estimator, chain_monitor.as_Watch(), tx_broadcaster, logger, keys_interface, config, network, current_blockchain_tip_hash, current_blockchain_tip_height);
85     }
86
87     /**
88      * Abstract interface which should handle Events and persist the ChannelManager. When you call chain_sync_completed
89      * a background thread is started which will automatically call these methods for you when events occur.
90      */
91     public interface ChannelManagerPersister {
92         void handle_events(Event[] events);
93         void persist_manager(byte[] channel_manager_bytes);
94     }
95
96     Thread persister_thread = null;
97     volatile boolean shutdown = false;
98
99     /**
100      * Utility which adds all of the deserialized ChannelMonitors to the chain watch so that further updates from the
101      * ChannelManager are processed as normal.
102      *
103      * This also spawns a background thread which will call the appropriate methods on the provided
104      * ChannelManagerPersister as required.
105      */
106     public void chain_sync_completed(ChannelManagerPersister persister) {
107         if (persister_thread != null) { return; }
108         for (TwoTuple<ChannelMonitor, byte[]> monitor: channel_monitors) {
109             this.chain_monitor.as_Watch().watch_channel(monitor.a.get_funding_txo().a, monitor.a);
110         }
111         persister_thread = new Thread(() -> {
112             long lastTimerTick = System.currentTimeMillis();
113             while (true) {
114                 boolean need_persist = this.channel_manager.await_persistable_update_timeout(1);
115                 Event[] events = this.channel_manager.as_EventsProvider().get_and_clear_pending_events();
116                 if (events.length != 0) {
117                     persister.handle_events(events);
118                     need_persist = true;
119                 }
120                 events = this.chain_monitor.as_EventsProvider().get_and_clear_pending_events();
121                 if (events.length != 0) {
122                     persister.handle_events(events);
123                     need_persist = true;
124                 }
125                 if (need_persist) {
126                     persister.persist_manager(this.channel_manager.write());
127                 }
128                 if (shutdown) {
129                     return;
130                 }
131                 if (lastTimerTick < System.currentTimeMillis() - 60 * 1000) {
132                     this.channel_manager.timer_chan_freshness_every_min();
133                     lastTimerTick = System.currentTimeMillis();
134                 }
135             }
136         }, "NioPeerHandler NIO Thread");
137         persister_thread.start();
138     }
139
140     /**
141      * Interrupt the background thread, stopping the background handling of
142      */
143     public void interrupt() {
144         shutdown = true;
145         try {
146             persister_thread.join();
147         } catch (InterruptedException ignored) { }
148     }
149 }