Skip to content

Commit d54d5dd

Browse files
authored
Merge pull request #16 from TheBlueMatt/2021-03-background-manager-persister
Adapt ChannelManagerConstructor to persist ChannelManager + handle events
2 parents 24971cb + 423fdb0 commit d54d5dd

File tree

12 files changed

+131
-41
lines changed

12 files changed

+131
-41
lines changed

.github/workflows/build.yml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ jobs:
3030
cd ..
3131
git clone https://github.com/lightningdevkit/ldk-c-bindings
3232
- name: Rebuild C bindings, and check the sample app builds + links
33-
run: cd ldk-c-bindings && ./genbindings.sh ../rust-lightning && cd ..
33+
run: cd ldk-c-bindings && ./genbindings.sh ../rust-lightning true && cd ..
3434
- name: Build Java/TS Debug Bindings
3535
run: ./genbindings.sh ./ldk-c-bindings/ "-I/usr/lib/jvm/java-11-openjdk-amd64/include/ -I/usr/lib/jvm/java-11-openjdk-amd64/include/linux/" true false
3636
- name: Run Java Tests against Debug Bindings

liblightningjni_debug.so

24.7 KB
Binary file not shown.

liblightningjni_release.so

18.5 KB
Binary file not shown.

src/main/java/org/ldk/batteries/ChannelManagerConstructor.java

Lines changed: 62 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@ public static class InvalidSerializedDataException extends Exception {}
3434
*/
3535
public final TwoTuple<ChannelMonitor, byte[]>[] channel_monitors;
3636

37-
private final Watch chain_watch;
37+
private final ChainMonitor chain_monitor;
3838

3939
/**
4040
* Deserializes a channel manager and a set of channel monitors from the given serialized copies and interface implementations
@@ -44,7 +44,7 @@ public static class InvalidSerializedDataException extends Exception {}
4444
* outputs will be loaded when chain_sync_completed is called.
4545
*/
4646
public ChannelManagerConstructor(byte[] channel_manager_serialized, byte[][] channel_monitors_serialized,
47-
KeysInterface keys_interface, FeeEstimator fee_estimator, Watch chain_watch, @Nullable Filter filter,
47+
KeysInterface keys_interface, FeeEstimator fee_estimator, ChainMonitor chain_monitor, @Nullable Filter filter,
4848
BroadcasterInterface tx_broadcaster, Logger logger) throws InvalidSerializedDataException {
4949
final ChannelMonitor[] monitors = new ChannelMonitor[channel_monitors_serialized.length];
5050
this.channel_monitors = new TwoTuple[monitors.length];
@@ -57,14 +57,14 @@ public ChannelManagerConstructor(byte[] channel_manager_serialized, byte[][] cha
5757
this.channel_monitors[i] = new TwoTuple<>(monitors[i], ((Result_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ.Result_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ_OK)res).res.a);
5858
}
5959
Result_C2Tuple_BlockHashChannelManagerZDecodeErrorZ res =
60-
UtilMethods.constructor_BlockHashChannelManagerZ_read(channel_manager_serialized, keys_interface, fee_estimator, chain_watch, tx_broadcaster,
60+
UtilMethods.constructor_BlockHashChannelManagerZ_read(channel_manager_serialized, keys_interface, fee_estimator, chain_monitor.as_Watch(), tx_broadcaster,
6161
logger, UserConfig.constructor_default(), monitors);
6262
if (res instanceof Result_C2Tuple_BlockHashChannelManagerZDecodeErrorZ.Result_C2Tuple_BlockHashChannelManagerZDecodeErrorZ_Err) {
6363
throw new InvalidSerializedDataException();
6464
}
6565
this.channel_manager = ((Result_C2Tuple_BlockHashChannelManagerZDecodeErrorZ.Result_C2Tuple_BlockHashChannelManagerZDecodeErrorZ_OK)res).res.b;
6666
this.channel_manager_latest_block_hash = ((Result_C2Tuple_BlockHashChannelManagerZDecodeErrorZ.Result_C2Tuple_BlockHashChannelManagerZDecodeErrorZ_OK)res).res.a;
67-
this.chain_watch = chain_watch;
67+
this.chain_monitor = chain_monitor;
6868
if (filter != null) {
6969
for (ChannelMonitor monitor : monitors) {
7070
monitor.load_outputs_to_watch(filter);
@@ -76,21 +76,74 @@ public ChannelManagerConstructor(byte[] channel_manager_serialized, byte[][] cha
7676
* Constructs a channel manager from the given interface implementations
7777
*/
7878
public ChannelManagerConstructor(LDKNetwork network, UserConfig config, byte[] current_blockchain_tip_hash, int current_blockchain_tip_height,
79-
KeysInterface keys_interface, FeeEstimator fee_estimator, Watch chain_watch,
79+
KeysInterface keys_interface, FeeEstimator fee_estimator, ChainMonitor chain_monitor,
8080
BroadcasterInterface tx_broadcaster, Logger logger) throws InvalidSerializedDataException {
8181
channel_monitors = new TwoTuple[0];
8282
channel_manager_latest_block_hash = null;
83-
this.chain_watch = chain_watch;
84-
channel_manager = ChannelManager.constructor_new(fee_estimator, chain_watch, tx_broadcaster, logger, keys_interface, config, network, current_blockchain_tip_hash, current_blockchain_tip_height);
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);
8585
}
8686

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+
8799
/**
88100
* Utility which adds all of the deserialized ChannelMonitors to the chain watch so that further updates from the
89101
* 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.
90105
*/
91-
public void chain_sync_completed() {
106+
public void chain_sync_completed(ChannelManagerPersister persister) {
107+
if (persister_thread != null) { return; }
92108
for (TwoTuple<ChannelMonitor, byte[]> monitor: channel_monitors) {
93-
this.chain_watch.watch_channel(monitor.a.get_funding_txo().a, monitor.a);
109+
this.chain_monitor.as_Watch().watch_channel(monitor.a.get_funding_txo().a, monitor.a);
94110
}
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) { }
95148
}
96149
}

src/main/java/org/ldk/impl/bindings.java

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2163,6 +2163,8 @@ public interface LDKSocketDescriptor {
21632163
public static native void ChannelManager_block_connected(long this_arg, byte[] header, long[] txdata, int height);
21642164
// void ChannelManager_block_disconnected(const struct LDKChannelManager *NONNULL_PTR this_arg, const uint8_t (*header)[80]);
21652165
public static native void ChannelManager_block_disconnected(long this_arg, byte[] header);
2166+
// MUST_USE_RES bool ChannelManager_await_persistable_update_timeout(const struct LDKChannelManager *NONNULL_PTR this_arg, uint64_t max_wait);
2167+
public static native boolean ChannelManager_await_persistable_update_timeout(long this_arg, long max_wait);
21662168
// void ChannelManager_await_persistable_update(const struct LDKChannelManager *NONNULL_PTR this_arg);
21672169
public static native void ChannelManager_await_persistable_update(long this_arg);
21682170
// struct LDKChannelMessageHandler ChannelManager_as_ChannelMessageHandler(const struct LDKChannelManager *NONNULL_PTR this_arg);

src/main/java/org/ldk/structs/ChannelManager.java

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -394,6 +394,18 @@ public void block_disconnected(byte[] header) {
394394
bindings.ChannelManager_block_disconnected(this.ptr, header);
395395
}
396396

397+
/**
398+
* Blocks until ChannelManager needs to be persisted or a timeout is reached. It returns a bool
399+
* indicating whether persistence is necessary. Only one listener on
400+
* `await_persistable_update` or `await_persistable_update_timeout` is guaranteed to be woken
401+
* up.
402+
* Note that the feature `allow_wallclock_use` must be enabled to use this function.
403+
*/
404+
public boolean await_persistable_update_timeout(long max_wait) {
405+
boolean ret = bindings.ChannelManager_await_persistable_update_timeout(this.ptr, max_wait);
406+
return ret;
407+
}
408+
397409
/**
398410
* Blocks until ChannelManager needs to be persisted. Only one listener on
399411
* `await_persistable_update` or `await_persistable_update_timeout` is guaranteed to be woken

src/main/jni/bindings.c

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12722,6 +12722,14 @@ JNIEXPORT void JNICALL Java_org_ldk_impl_bindings_ChannelManager_1block_1disconn
1272212722
ChannelManager_block_disconnected(&this_arg_conv, header_ref);
1272312723
}
1272412724

12725+
JNIEXPORT jboolean JNICALL Java_org_ldk_impl_bindings_ChannelManager_1await_1persistable_1update_1timeout(JNIEnv *env, jclass clz, int64_t this_arg, int64_t max_wait) {
12726+
LDKChannelManager this_arg_conv;
12727+
this_arg_conv.inner = (void*)(this_arg & (~1));
12728+
this_arg_conv.is_owned = false;
12729+
jboolean ret_val = ChannelManager_await_persistable_update_timeout(&this_arg_conv, max_wait);
12730+
return ret_val;
12731+
}
12732+
1272512733
JNIEXPORT void JNICALL Java_org_ldk_impl_bindings_ChannelManager_1await_1persistable_1update(JNIEnv *env, jclass clz, int64_t this_arg) {
1272612734
LDKChannelManager this_arg_conv;
1272712735
this_arg_conv.inner = (void*)(this_arg & (~1));

src/main/jni/org_ldk_impl_bindings.h

Lines changed: 8 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

src/test/java/org/ldk/HumanObjectPeerTest.java

Lines changed: 17 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,8 @@
11
package org.ldk;
22

33
import org.bitcoinj.core.*;
4-
import org.bitcoinj.core.Transaction;
54
import org.bitcoinj.script.Script;
65
import org.junit.jupiter.api.Test;
7-
import org.ldk.batteries.ChannelManagerConstructor;
86
import org.ldk.batteries.NioPeerHandler;
97
import org.ldk.enums.LDKNetwork;
108
import org.ldk.impl.bindings;
@@ -287,38 +285,26 @@ private void bind_nio() {
287285
Object ptr_to;
288286
Peer(Peer orig) {
289287
this(null, orig.seed);
290-
if (!break_cross_peer_refs) {
291-
ChannelMonitor[] monitors = new ChannelMonitor[1];
292-
synchronized (monitors) {
293-
assert orig.monitors.size() == 1;
288+
// TODO: Optionally test ChannelManagerConstructor
289+
ChannelMonitor[] monitors = new ChannelMonitor[1];
290+
synchronized (monitors) {
291+
assert orig.monitors.size() == 1;
292+
if (!break_cross_peer_refs) {
294293
monitors[0] = orig.monitors.values().stream().iterator().next();
295-
}
296-
byte[] serialized = orig.chan_manager.write();
297-
Result_C2Tuple_BlockHashChannelManagerZDecodeErrorZ read_res =
298-
UtilMethods.constructor_BlockHashChannelManagerZ_read(serialized, this.keys_interface, this.fee_estimator, this.chain_watch, this.tx_broadcaster, this.logger, UserConfig.constructor_default(), monitors);
299-
assert read_res instanceof Result_C2Tuple_BlockHashChannelManagerZDecodeErrorZ.Result_C2Tuple_BlockHashChannelManagerZDecodeErrorZ_OK;
300-
this.chan_manager = ((Result_C2Tuple_BlockHashChannelManagerZDecodeErrorZ.Result_C2Tuple_BlockHashChannelManagerZDecodeErrorZ_OK) read_res).res.b;
301-
this.chain_watch.watch_channel(monitors[0].get_funding_txo().a, monitors[0]);
302-
} else {
303-
final ArrayList<byte[]> channel_monitors = new ArrayList();
304-
synchronized (monitors) {
305-
assert orig.monitors.size() == 1;
306-
channel_monitors.add(orig.monitors.values().stream().iterator().next().write());
307-
}
308-
byte[] serialized = orig.chan_manager.write();
309-
try {
310-
ChannelManagerConstructor constructed = new ChannelManagerConstructor(serialized, channel_monitors.toArray(new byte[1][]), this.keys_interface, this.fee_estimator, this.chain_watch, this.filter, this.tx_broadcaster, this.logger);
311-
this.chan_manager = constructed.channel_manager;
312-
constructed.chain_sync_completed();
313-
if (use_filter && !use_manual_watch) {
314-
// With a manual watch we don't actually use the filter object at all.
315-
assert this.filter_additions.containsAll(orig.filter_additions) &&
316-
orig.filter_additions.containsAll(this.filter_additions);
317-
}
318-
} catch (ChannelManagerConstructor.InvalidSerializedDataException e) {
319-
assert false;
294+
} else {
295+
byte[] serialized = orig.monitors.values().stream().iterator().next().write();
296+
Result_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ res =
297+
UtilMethods.constructor_BlockHashChannelMonitorZ_read(serialized, this.keys_interface);
298+
assert res instanceof Result_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ.Result_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ_OK;
299+
monitors[0] = ((Result_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ.Result_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ_OK) res).res.b;
320300
}
321301
}
302+
byte[] serialized = orig.chan_manager.write();
303+
Result_C2Tuple_BlockHashChannelManagerZDecodeErrorZ read_res =
304+
UtilMethods.constructor_BlockHashChannelManagerZ_read(serialized, this.keys_interface, this.fee_estimator, this.chain_watch, this.tx_broadcaster, this.logger, UserConfig.constructor_default(), monitors);
305+
assert read_res instanceof Result_C2Tuple_BlockHashChannelManagerZDecodeErrorZ.Result_C2Tuple_BlockHashChannelManagerZDecodeErrorZ_OK;
306+
this.chan_manager = ((Result_C2Tuple_BlockHashChannelManagerZDecodeErrorZ.Result_C2Tuple_BlockHashChannelManagerZDecodeErrorZ_OK) read_res).res.b;
307+
this.chain_watch.watch_channel(monitors[0].get_funding_txo().a, monitors[0]);
322308
if (!break_cross_peer_refs && (use_manual_watch || use_km_wrapper)) {
323309
// When we pass monitors[0] into chain_watch.watch_channel we create a reference from the new Peer to a
324310
// field in the old peer, preventing freeing of the original Peer until the new Peer is freed. Thus, we

ts/bindings.c

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11492,6 +11492,14 @@ void __attribute__((visibility("default"))) TS_ChannelManager_block_disconnecte
1149211492
ChannelManager_block_disconnected(&this_arg_conv, header_ref);
1149311493
}
1149411494

11495+
jboolean __attribute__((visibility("default"))) TS_ChannelManager_await_persistable_update_timeout(uint32_t this_arg, int64_t max_wait) {
11496+
LDKChannelManager this_arg_conv;
11497+
this_arg_conv.inner = (void*)(this_arg & (~1));
11498+
this_arg_conv.is_owned = false;
11499+
jboolean ret_val = ChannelManager_await_persistable_update_timeout(&this_arg_conv, max_wait);
11500+
return ret_val;
11501+
}
11502+
1149511503
void __attribute__((visibility("default"))) TS_ChannelManager_await_persistable_update(uint32_t this_arg) {
1149611504
LDKChannelManager this_arg_conv;
1149711505
this_arg_conv.inner = (void*)(this_arg & (~1));

0 commit comments

Comments
 (0)