1 package org.ldk.structs;
3 import org.ldk.impl.bindings;
4 import org.ldk.enums.*;
6 import java.util.Arrays;
10 * Manager which keeps track of a number of channels and sends messages to the appropriate
11 * channel, also tracking HTLC preimages and forwarding onion packets appropriately.
13 * Implements ChannelMessageHandler, handling the multi-channel parts and passing things through
14 * to individual Channels.
16 * Implements Writeable to write out all channel state to disk. Implies peer_disconnected() for
17 * all peers during write/read (though does not modify this instance, only the instance being
18 * serialized). This will result in any channels which have not yet exchanged funding_created (ie
19 * called funding_transaction_generated for outbound channels).
21 * Note that you can be a bit lazier about writing out ChannelManager than you can be with
22 * ChannelMonitors. With ChannelMonitors you MUST write each monitor update out to disk before
23 * returning from chain::Watch::watch_/update_channel, with ChannelManagers, writing updates
24 * happens out-of-band (and will prevent any other ChannelManager operations from occurring during
25 * the serialization process). If the deserialized version is out-of-date compared to the
26 * ChannelMonitors passed by reference to read(), those channels will be force-closed based on the
27 * ChannelMonitor state and no funds will be lost (mod on-chain transaction fees).
29 * Note that the deserializer is only implemented for (BlockHash, ChannelManager), which
30 * tells you the last block hash which was block_connect()ed. You MUST rescan any blocks along
31 * the \"reorg path\" (ie call block_disconnected() until you get to a common block and then call
32 * block_connected() to step towards your best block) upon deserialization before using the
35 * Note that ChannelManager is responsible for tracking liveness of its channels and generating
36 * ChannelUpdate messages informing peers that the channel is temporarily disabled. To avoid
37 * spam due to quick disconnection/reconnection, updates are not sent until the channel has been
38 * offline for a full minute. In order to track this, you must call
39 * timer_chan_freshness_every_min roughly once per minute, though it doesn't have to be perfect.
41 * Rather than using a plain ChannelManager, it is preferable to use either a SimpleArcChannelManager
42 * a SimpleRefChannelManager, for conciseness. See their documentation for more details, but
43 * essentially you should default to using a SimpleRefChannelManager, and use a
44 * SimpleArcChannelManager when you require a ChannelManager with a static lifetime, such as when
45 * you're using lightning-net-tokio.
47 @SuppressWarnings("unchecked") // We correctly assign various generic arrays
48 public class ChannelManager extends CommonBase {
49 ChannelManager(Object _dummy, long ptr) { super(ptr); }
50 @Override @SuppressWarnings("deprecation")
51 protected void finalize() throws Throwable {
53 if (ptr != 0) { bindings.ChannelManager_free(ptr); }
57 * Constructs a new ChannelManager to hold several channels and route between them.
59 * This is the main \"logic hub\" for all channel-related actions, and implements
60 * ChannelMessageHandler.
62 * Non-proportional fees are fixed according to our risk using the provided fee estimator.
64 * panics if channel_value_satoshis is >= `MAX_FUNDING_SATOSHIS`!
66 * Users need to notify the new ChannelManager when a new block is connected or
67 * disconnected using its `block_connected` and `block_disconnected` methods, starting
68 * from after `params.latest_hash`.
70 public static ChannelManager constructor_new(FeeEstimator fee_est, Watch chain_monitor, BroadcasterInterface tx_broadcaster, Logger logger, KeysInterface keys_manager, UserConfig config, LDKNetwork params_network_arg, byte[] params_latest_hash_arg, long params_latest_height_arg) {
71 long ret = bindings.ChannelManager_new(fee_est == null ? 0 : fee_est.ptr, chain_monitor == null ? 0 : chain_monitor.ptr, tx_broadcaster == null ? 0 : tx_broadcaster.ptr, logger == null ? 0 : logger.ptr, keys_manager == null ? 0 : keys_manager.ptr, config == null ? 0 : config.ptr & ~1, bindings.ChainParameters_new(params_network_arg, params_latest_hash_arg, params_latest_height_arg));
72 ChannelManager ret_hu_conv = new ChannelManager(null, ret);
73 ret_hu_conv.ptrs_to.add(ret_hu_conv);
74 ret_hu_conv.ptrs_to.add(fee_est);
75 ret_hu_conv.ptrs_to.add(chain_monitor);
76 ret_hu_conv.ptrs_to.add(tx_broadcaster);
77 ret_hu_conv.ptrs_to.add(logger);
78 ret_hu_conv.ptrs_to.add(keys_manager);
79 ret_hu_conv.ptrs_to.add(config);
84 * Creates a new outbound channel to the given remote node and with the given value.
86 * user_id will be provided back as user_channel_id in FundingGenerationReady and
87 * FundingBroadcastSafe events to allow tracking of which events correspond with which
88 * create_channel call. Note that user_channel_id defaults to 0 for inbound channels, so you
89 * may wish to avoid using 0 for user_id here.
91 * If successful, will generate a SendOpenChannel message event, so you should probably poll
92 * PeerManager::process_events afterwards.
94 * Raises APIError::APIMisuseError when channel_value_satoshis > 2**24 or push_msat is
95 * greater than channel_value_satoshis * 1k or channel_value_satoshis is < 1000.
97 public Result_NoneAPIErrorZ create_channel(byte[] their_network_key, long channel_value_satoshis, long push_msat, long user_id, UserConfig override_config) {
98 long ret = bindings.ChannelManager_create_channel(this.ptr, their_network_key, channel_value_satoshis, push_msat, user_id, override_config == null ? 0 : override_config.ptr & ~1);
99 Result_NoneAPIErrorZ ret_hu_conv = Result_NoneAPIErrorZ.constr_from_ptr(ret);
100 this.ptrs_to.add(override_config);
105 * Gets the list of open channels, in random order. See ChannelDetail field documentation for
108 public ChannelDetails[] list_channels() {
109 long[] ret = bindings.ChannelManager_list_channels(this.ptr);
110 ChannelDetails[] ret_conv_16_arr = new ChannelDetails[ret.length];
111 for (int q = 0; q < ret.length; q++) {
112 long ret_conv_16 = ret[q];
113 ChannelDetails ret_conv_16_hu_conv = new ChannelDetails(null, ret_conv_16);
114 ret_conv_16_hu_conv.ptrs_to.add(this);
115 ret_conv_16_arr[q] = ret_conv_16_hu_conv;
117 return ret_conv_16_arr;
121 * Gets the list of usable channels, in random order. Useful as an argument to
122 * get_route to ensure non-announced channels are used.
124 * These are guaranteed to have their is_live value set to true, see the documentation for
125 * ChannelDetails::is_live for more info on exactly what the criteria are.
127 public ChannelDetails[] list_usable_channels() {
128 long[] ret = bindings.ChannelManager_list_usable_channels(this.ptr);
129 ChannelDetails[] ret_conv_16_arr = new ChannelDetails[ret.length];
130 for (int q = 0; q < ret.length; q++) {
131 long ret_conv_16 = ret[q];
132 ChannelDetails ret_conv_16_hu_conv = new ChannelDetails(null, ret_conv_16);
133 ret_conv_16_hu_conv.ptrs_to.add(this);
134 ret_conv_16_arr[q] = ret_conv_16_hu_conv;
136 return ret_conv_16_arr;
140 * Begins the process of closing a channel. After this call (plus some timeout), no new HTLCs
141 * will be accepted on the given channel, and after additional timeout/the closing of all
142 * pending HTLCs, the channel will be closed on chain.
144 * May generate a SendShutdown message event on success, which should be relayed.
146 public Result_NoneAPIErrorZ close_channel(byte[] channel_id) {
147 long ret = bindings.ChannelManager_close_channel(this.ptr, channel_id);
148 Result_NoneAPIErrorZ ret_hu_conv = Result_NoneAPIErrorZ.constr_from_ptr(ret);
153 * Force closes a channel, immediately broadcasting the latest local commitment transaction to
154 * the chain and rejecting new HTLCs on the given channel. Fails if channel_id is unknown to the manager.
156 public Result_NoneAPIErrorZ force_close_channel(byte[] channel_id) {
157 long ret = bindings.ChannelManager_force_close_channel(this.ptr, channel_id);
158 Result_NoneAPIErrorZ ret_hu_conv = Result_NoneAPIErrorZ.constr_from_ptr(ret);
163 * Force close all channels, immediately broadcasting the latest local commitment transaction
164 * for each to the chain and rejecting new HTLCs on each.
166 public void force_close_all_channels() {
167 bindings.ChannelManager_force_close_all_channels(this.ptr);
171 * Sends a payment along a given route.
173 * Value parameters are provided via the last hop in route, see documentation for RouteHop
174 * fields for more info.
176 * Note that if the payment_hash already exists elsewhere (eg you're sending a duplicative
177 * payment), we don't do anything to stop you! We always try to ensure that if the provided
178 * next hop knows the preimage to payment_hash they can claim an additional amount as
179 * specified in the last hop in the route! Thus, you should probably do your own
180 * payment_preimage tracking (which you should already be doing as they represent \"proof of
181 * payment\") and prevent double-sends yourself.
183 * May generate SendHTLCs message(s) event on success, which should be relayed.
185 * Each path may have a different return value, and PaymentSendValue may return a Vec with
186 * each entry matching the corresponding-index entry in the route paths, see
187 * PaymentSendFailure for more info.
189 * In general, a path may raise:
190 * APIError::RouteError when an invalid route or forwarding parameter (cltv_delta, fee,
191 * node public key) is specified.
192 * APIError::ChannelUnavailable if the next-hop channel is not available for updates
193 * (including due to previous monitor update failure or new permanent monitor update
195 * APIError::MonitorUpdateFailed if a new monitor update failure prevented sending the
198 * Note that depending on the type of the PaymentSendFailure the HTLC may have been
199 * irrevocably committed to on our end. In such a case, do NOT retry the payment with a
200 * different route unless you intend to pay twice!
202 * payment_secret is unrelated to payment_hash (or PaymentPreimage) and exists to authenticate
203 * the sender to the recipient and prevent payment-probing (deanonymization) attacks. For
204 * newer nodes, it will be provided to you in the invoice. If you do not have one, the Route
205 * must not contain multiple paths as multi-path payments require a recipient-provided
207 * If a payment_secret *is* provided, we assume that the invoice had the payment_secret feature
208 * bit set (either as required or as available). If multiple paths are present in the Route,
209 * we assume the invoice had the basic_mpp feature set.
211 public Result_NonePaymentSendFailureZ send_payment(Route route, byte[] payment_hash, byte[] payment_secret) {
212 long ret = bindings.ChannelManager_send_payment(this.ptr, route == null ? 0 : route.ptr & ~1, payment_hash, payment_secret);
213 Result_NonePaymentSendFailureZ ret_hu_conv = Result_NonePaymentSendFailureZ.constr_from_ptr(ret);
214 this.ptrs_to.add(route);
219 * Call this upon creation of a funding transaction for the given channel.
221 * Note that ALL inputs in the transaction pointed to by funding_txo MUST spend SegWit outputs
222 * or your counterparty can steal your funds!
224 * Panics if a funding transaction has already been provided for this channel.
226 * May panic if the funding_txo is duplicative with some other channel (note that this should
227 * be trivially prevented by using unique funding transaction keys per-channel).
229 public void funding_transaction_generated(byte[] temporary_channel_id, OutPoint funding_txo) {
230 bindings.ChannelManager_funding_transaction_generated(this.ptr, temporary_channel_id, funding_txo == null ? 0 : funding_txo.ptr & ~1);
231 this.ptrs_to.add(funding_txo);
235 * Generates a signed node_announcement from the given arguments and creates a
236 * BroadcastNodeAnnouncement event. Note that such messages will be ignored unless peers have
237 * seen a channel_announcement from us (ie unless we have public channels open).
239 * RGB is a node \"color\" and alias is a printable human-readable string to describe this node
240 * to humans. They carry no in-protocol meaning.
242 * addresses represent the set (possibly empty) of socket addresses on which this node accepts
243 * incoming connections. These will be broadcast to the network, publicly tying these
244 * addresses together. If you wish to preserve user privacy, addresses should likely contain
245 * only Tor Onion addresses.
247 * Panics if addresses is absurdly large (more than 500).
249 public void broadcast_node_announcement(byte[] rgb, byte[] alias, NetAddress[] addresses) {
250 bindings.ChannelManager_broadcast_node_announcement(this.ptr, rgb, alias, Arrays.stream(addresses).mapToLong(addresses_conv_12 -> addresses_conv_12.ptr).toArray());
251 /* TODO 2 NetAddress */;
255 * Processes HTLCs which are pending waiting on random forward delay.
257 * Should only really ever be called in response to a PendingHTLCsForwardable event.
258 * Will likely generate further events.
260 public void process_pending_htlc_forwards() {
261 bindings.ChannelManager_process_pending_htlc_forwards(this.ptr);
265 * If a peer is disconnected we mark any channels with that peer as 'disabled'.
266 * After some time, if channels are still disabled we need to broadcast a ChannelUpdate
267 * to inform the network about the uselessness of these channels.
269 * This method handles all the details, and must be called roughly once per minute.
271 * Note that in some rare cases this may generate a `chain::Watch::update_channel` call.
273 public void timer_chan_freshness_every_min() {
274 bindings.ChannelManager_timer_chan_freshness_every_min(this.ptr);
278 * Indicates that the preimage for payment_hash is unknown or the received amount is incorrect
279 * after a PaymentReceived event, failing the HTLC back to its origin and freeing resources
280 * along the path (including in our own channel on which we received it).
281 * Returns false if no payment was found to fail backwards, true if the process of failing the
282 * HTLC backwards has been started.
284 public boolean fail_htlc_backwards(byte[] payment_hash, byte[] payment_secret) {
285 boolean ret = bindings.ChannelManager_fail_htlc_backwards(this.ptr, payment_hash, payment_secret);
290 * Provides a payment preimage in response to a PaymentReceived event, returning true and
291 * generating message events for the net layer to claim the payment, if possible. Thus, you
292 * should probably kick the net layer to go send messages if this returns true!
294 * You must specify the expected amounts for this HTLC, and we will only claim HTLCs
295 * available within a few percent of the expected amount. This is critical for several
296 * reasons : a) it avoids providing senders with `proof-of-payment` (in the form of the
297 * payment_preimage without having provided the full value and b) it avoids certain
298 * privacy-breaking recipient-probing attacks which may reveal payment activity to
299 * motivated attackers.
301 * Note that the privacy concerns in (b) are not relevant in payments with a payment_secret
302 * set. Thus, for such payments we will claim any payments which do not under-pay.
304 * May panic if called except in response to a PaymentReceived event.
306 public boolean claim_funds(byte[] payment_preimage, byte[] payment_secret, long expected_amount) {
307 boolean ret = bindings.ChannelManager_claim_funds(this.ptr, payment_preimage, payment_secret, expected_amount);
312 * Gets the node_id held by this ChannelManager
314 public byte[] get_our_node_id() {
315 byte[] ret = bindings.ChannelManager_get_our_node_id(this.ptr);
320 * Restores a single, given channel to normal operation after a
321 * ChannelMonitorUpdateErr::TemporaryFailure was returned from a channel monitor update
324 * All ChannelMonitor updates up to and including highest_applied_update_id must have been
325 * fully committed in every copy of the given channels' ChannelMonitors.
327 * Note that there is no effect to calling with a highest_applied_update_id other than the
328 * current latest ChannelMonitorUpdate and one call to this function after multiple
329 * ChannelMonitorUpdateErr::TemporaryFailures is fine. The highest_applied_update_id field
330 * exists largely only to prevent races between this and concurrent update_monitor calls.
332 * Thus, the anticipated use is, at a high level:
333 * 1) You register a chain::Watch with this ChannelManager,
334 * 2) it stores each update to disk, and begins updating any remote (eg watchtower) copies of
335 * said ChannelMonitors as it can, returning ChannelMonitorUpdateErr::TemporaryFailures
336 * any time it cannot do so instantly,
337 * 3) update(s) are applied to each remote copy of a ChannelMonitor,
338 * 4) once all remote copies are updated, you call this function with the update_id that
339 * completed, and once it is the latest the Channel will be re-enabled.
341 public void channel_monitor_updated(OutPoint funding_txo, long highest_applied_update_id) {
342 bindings.ChannelManager_channel_monitor_updated(this.ptr, funding_txo == null ? 0 : funding_txo.ptr & ~1, highest_applied_update_id);
343 this.ptrs_to.add(funding_txo);
347 * Constructs a new MessageSendEventsProvider which calls the relevant methods on this_arg.
348 * This copies the `inner` pointer in this_arg and thus the returned MessageSendEventsProvider must be freed before this_arg is
350 public MessageSendEventsProvider as_MessageSendEventsProvider() {
351 long ret = bindings.ChannelManager_as_MessageSendEventsProvider(this.ptr);
352 MessageSendEventsProvider ret_hu_conv = new MessageSendEventsProvider(null, ret);
353 ret_hu_conv.ptrs_to.add(this);
358 * Constructs a new EventsProvider which calls the relevant methods on this_arg.
359 * This copies the `inner` pointer in this_arg and thus the returned EventsProvider must be freed before this_arg is
361 public EventsProvider as_EventsProvider() {
362 long ret = bindings.ChannelManager_as_EventsProvider(this.ptr);
363 EventsProvider ret_hu_conv = new EventsProvider(null, ret);
364 ret_hu_conv.ptrs_to.add(this);
369 * Constructs a new Listen which calls the relevant methods on this_arg.
370 * This copies the `inner` pointer in this_arg and thus the returned Listen must be freed before this_arg is
372 public Listen as_Listen() {
373 long ret = bindings.ChannelManager_as_Listen(this.ptr);
374 Listen ret_hu_conv = new Listen(null, ret);
375 ret_hu_conv.ptrs_to.add(this);
380 * Updates channel state based on transactions seen in a connected block.
382 public void block_connected(byte[] header, TwoTuple<Long, byte[]>[] txdata, int height) {
383 bindings.ChannelManager_block_connected(this.ptr, header, Arrays.stream(txdata).mapToLong(txdata_conv_24 -> bindings.C2Tuple_usizeTransactionZ_new(txdata_conv_24.a, txdata_conv_24.b)).toArray(), height);
384 /* TODO 2 TwoTuple<Long, byte[]> */;
388 * Updates channel state based on a disconnected block.
390 * If necessary, the channel may be force-closed without letting the counterparty participate
393 public void block_disconnected(byte[] header) {
394 bindings.ChannelManager_block_disconnected(this.ptr, header);
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
402 * Note that the feature `allow_wallclock_use` must be enabled to use this function.
404 public boolean await_persistable_update_timeout(long max_wait) {
405 boolean ret = bindings.ChannelManager_await_persistable_update_timeout(this.ptr, max_wait);
410 * Blocks until ChannelManager needs to be persisted. Only one listener on
411 * `await_persistable_update` or `await_persistable_update_timeout` is guaranteed to be woken
414 public void await_persistable_update() {
415 bindings.ChannelManager_await_persistable_update(this.ptr);
419 * Constructs a new ChannelMessageHandler which calls the relevant methods on this_arg.
420 * This copies the `inner` pointer in this_arg and thus the returned ChannelMessageHandler must be freed before this_arg is
422 public ChannelMessageHandler as_ChannelMessageHandler() {
423 long ret = bindings.ChannelManager_as_ChannelMessageHandler(this.ptr);
424 ChannelMessageHandler ret_hu_conv = new ChannelMessageHandler(null, ret);
425 ret_hu_conv.ptrs_to.add(this);
430 * Serialize the ChannelManager object into a byte array which can be read by ChannelManager_read
432 public byte[] write() {
433 byte[] ret = bindings.ChannelManager_write(this.ptr);