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_tick_occurred 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, BestBlock params_best_block_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_best_block_arg == null ? 0 : params_best_block_arg.ptr & ~1));
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);
80 ret_hu_conv.ptrs_to.add(params_best_block_arg);
85 * Gets the current configuration applied to all new channels, as
87 public UserConfig get_current_default_configuration() {
88 long ret = bindings.ChannelManager_get_current_default_configuration(this.ptr);
89 UserConfig ret_hu_conv = new UserConfig(null, ret);
90 ret_hu_conv.ptrs_to.add(this);
95 * Creates a new outbound channel to the given remote node and with the given value.
97 * user_id will be provided back as user_channel_id in FundingGenerationReady events to allow
98 * tracking of which events correspond with which create_channel call. Note that the
99 * user_channel_id defaults to 0 for inbound channels, so you may wish to avoid using 0 for
100 * user_id here. user_id has no meaning inside of LDK, it is simply copied to events and
103 * If successful, will generate a SendOpenChannel message event, so you should probably poll
104 * PeerManager::process_events afterwards.
106 * Raises APIError::APIMisuseError when channel_value_satoshis > 2**24 or push_msat is
107 * greater than channel_value_satoshis * 1k or channel_value_satoshis is < 1000.
109 public Result_NoneAPIErrorZ create_channel(byte[] their_network_key, long channel_value_satoshis, long push_msat, long user_id, UserConfig override_config) {
110 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);
111 Result_NoneAPIErrorZ ret_hu_conv = Result_NoneAPIErrorZ.constr_from_ptr(ret);
112 this.ptrs_to.add(override_config);
117 * Gets the list of open channels, in random order. See ChannelDetail field documentation for
120 public ChannelDetails[] list_channels() {
121 long[] ret = bindings.ChannelManager_list_channels(this.ptr);
122 ChannelDetails[] ret_conv_16_arr = new ChannelDetails[ret.length];
123 for (int q = 0; q < ret.length; q++) {
124 long ret_conv_16 = ret[q];
125 ChannelDetails ret_conv_16_hu_conv = new ChannelDetails(null, ret_conv_16);
126 ret_conv_16_hu_conv.ptrs_to.add(this);
127 ret_conv_16_arr[q] = ret_conv_16_hu_conv;
129 return ret_conv_16_arr;
133 * Gets the list of usable channels, in random order. Useful as an argument to
134 * get_route to ensure non-announced channels are used.
136 * These are guaranteed to have their is_live value set to true, see the documentation for
137 * ChannelDetails::is_live for more info on exactly what the criteria are.
139 public ChannelDetails[] list_usable_channels() {
140 long[] ret = bindings.ChannelManager_list_usable_channels(this.ptr);
141 ChannelDetails[] ret_conv_16_arr = new ChannelDetails[ret.length];
142 for (int q = 0; q < ret.length; q++) {
143 long ret_conv_16 = ret[q];
144 ChannelDetails ret_conv_16_hu_conv = new ChannelDetails(null, ret_conv_16);
145 ret_conv_16_hu_conv.ptrs_to.add(this);
146 ret_conv_16_arr[q] = ret_conv_16_hu_conv;
148 return ret_conv_16_arr;
152 * Begins the process of closing a channel. After this call (plus some timeout), no new HTLCs
153 * will be accepted on the given channel, and after additional timeout/the closing of all
154 * pending HTLCs, the channel will be closed on chain.
156 * May generate a SendShutdown message event on success, which should be relayed.
158 public Result_NoneAPIErrorZ close_channel(byte[] channel_id) {
159 long ret = bindings.ChannelManager_close_channel(this.ptr, channel_id);
160 Result_NoneAPIErrorZ ret_hu_conv = Result_NoneAPIErrorZ.constr_from_ptr(ret);
165 * Force closes a channel, immediately broadcasting the latest local commitment transaction to
166 * the chain and rejecting new HTLCs on the given channel. Fails if channel_id is unknown to the manager.
168 public Result_NoneAPIErrorZ force_close_channel(byte[] channel_id) {
169 long ret = bindings.ChannelManager_force_close_channel(this.ptr, channel_id);
170 Result_NoneAPIErrorZ ret_hu_conv = Result_NoneAPIErrorZ.constr_from_ptr(ret);
175 * Force close all channels, immediately broadcasting the latest local commitment transaction
176 * for each to the chain and rejecting new HTLCs on each.
178 public void force_close_all_channels() {
179 bindings.ChannelManager_force_close_all_channels(this.ptr);
183 * Sends a payment along a given route.
185 * Value parameters are provided via the last hop in route, see documentation for RouteHop
186 * fields for more info.
188 * Note that if the payment_hash already exists elsewhere (eg you're sending a duplicative
189 * payment), we don't do anything to stop you! We always try to ensure that if the provided
190 * next hop knows the preimage to payment_hash they can claim an additional amount as
191 * specified in the last hop in the route! Thus, you should probably do your own
192 * payment_preimage tracking (which you should already be doing as they represent \"proof of
193 * payment\") and prevent double-sends yourself.
195 * May generate SendHTLCs message(s) event on success, which should be relayed.
197 * Each path may have a different return value, and PaymentSendValue may return a Vec with
198 * each entry matching the corresponding-index entry in the route paths, see
199 * PaymentSendFailure for more info.
201 * In general, a path may raise:
202 * APIError::RouteError when an invalid route or forwarding parameter (cltv_delta, fee,
203 * node public key) is specified.
204 * APIError::ChannelUnavailable if the next-hop channel is not available for updates
205 * (including due to previous monitor update failure or new permanent monitor update
207 * APIError::MonitorUpdateFailed if a new monitor update failure prevented sending the
210 * Note that depending on the type of the PaymentSendFailure the HTLC may have been
211 * irrevocably committed to on our end. In such a case, do NOT retry the payment with a
212 * different route unless you intend to pay twice!
214 * payment_secret is unrelated to payment_hash (or PaymentPreimage) and exists to authenticate
215 * the sender to the recipient and prevent payment-probing (deanonymization) attacks. For
216 * newer nodes, it will be provided to you in the invoice. If you do not have one, the Route
217 * must not contain multiple paths as multi-path payments require a recipient-provided
219 * If a payment_secret *is* provided, we assume that the invoice had the payment_secret feature
220 * bit set (either as required or as available). If multiple paths are present in the Route,
221 * we assume the invoice had the basic_mpp feature set.
223 public Result_NonePaymentSendFailureZ send_payment(Route route, byte[] payment_hash, byte[] payment_secret) {
224 long ret = bindings.ChannelManager_send_payment(this.ptr, route == null ? 0 : route.ptr & ~1, payment_hash, payment_secret);
225 Result_NonePaymentSendFailureZ ret_hu_conv = Result_NonePaymentSendFailureZ.constr_from_ptr(ret);
226 this.ptrs_to.add(route);
231 * Call this upon creation of a funding transaction for the given channel.
233 * Returns an [`APIError::APIMisuseError`] if the funding_transaction spent non-SegWit outputs
234 * or if no output was found which matches the parameters in [`Event::FundingGenerationReady`].
236 * Panics if a funding transaction has already been provided for this channel.
238 * May panic if the output found in the funding transaction is duplicative with some other
239 * channel (note that this should be trivially prevented by using unique funding transaction
242 * Do NOT broadcast the funding transaction yourself. When we have safely received our
243 * counterparty's signature the funding transaction will automatically be broadcast via the
244 * [`BroadcasterInterface`] provided when this `ChannelManager` was constructed.
246 * Note that this includes RBF or similar transaction replacement strategies - lightning does
247 * not currently support replacing a funding transaction on an existing channel. Instead,
248 * create a new channel with a conflicting funding transaction.
250 public Result_NoneAPIErrorZ funding_transaction_generated(byte[] temporary_channel_id, byte[] funding_transaction) {
251 long ret = bindings.ChannelManager_funding_transaction_generated(this.ptr, temporary_channel_id, funding_transaction);
252 Result_NoneAPIErrorZ ret_hu_conv = Result_NoneAPIErrorZ.constr_from_ptr(ret);
257 * Generates a signed node_announcement from the given arguments and creates a
258 * BroadcastNodeAnnouncement event. Note that such messages will be ignored unless peers have
259 * seen a channel_announcement from us (ie unless we have public channels open).
261 * RGB is a node \"color\" and alias is a printable human-readable string to describe this node
262 * to humans. They carry no in-protocol meaning.
264 * addresses represent the set (possibly empty) of socket addresses on which this node accepts
265 * incoming connections. These will be broadcast to the network, publicly tying these
266 * addresses together. If you wish to preserve user privacy, addresses should likely contain
267 * only Tor Onion addresses.
269 * Panics if addresses is absurdly large (more than 500).
271 public void broadcast_node_announcement(byte[] rgb, byte[] alias, NetAddress[] addresses) {
272 bindings.ChannelManager_broadcast_node_announcement(this.ptr, rgb, alias, Arrays.stream(addresses).mapToLong(addresses_conv_12 -> addresses_conv_12.ptr).toArray());
273 /* TODO 2 NetAddress */;
277 * Processes HTLCs which are pending waiting on random forward delay.
279 * Should only really ever be called in response to a PendingHTLCsForwardable event.
280 * Will likely generate further events.
282 public void process_pending_htlc_forwards() {
283 bindings.ChannelManager_process_pending_htlc_forwards(this.ptr);
287 * If a peer is disconnected we mark any channels with that peer as 'disabled'.
288 * After some time, if channels are still disabled we need to broadcast a ChannelUpdate
289 * to inform the network about the uselessness of these channels.
291 * This method handles all the details, and must be called roughly once per minute.
293 * Note that in some rare cases this may generate a `chain::Watch::update_channel` call.
295 public void timer_tick_occurred() {
296 bindings.ChannelManager_timer_tick_occurred(this.ptr);
300 * Indicates that the preimage for payment_hash is unknown or the received amount is incorrect
301 * after a PaymentReceived event, failing the HTLC back to its origin and freeing resources
302 * along the path (including in our own channel on which we received it).
303 * Returns false if no payment was found to fail backwards, true if the process of failing the
304 * HTLC backwards has been started.
306 public boolean fail_htlc_backwards(byte[] payment_hash, byte[] payment_secret) {
307 boolean ret = bindings.ChannelManager_fail_htlc_backwards(this.ptr, payment_hash, payment_secret);
312 * Provides a payment preimage in response to a PaymentReceived event, returning true and
313 * generating message events for the net layer to claim the payment, if possible. Thus, you
314 * should probably kick the net layer to go send messages if this returns true!
316 * You must specify the expected amounts for this HTLC, and we will only claim HTLCs
317 * available within a few percent of the expected amount. This is critical for several
318 * reasons : a) it avoids providing senders with `proof-of-payment` (in the form of the
319 * payment_preimage without having provided the full value and b) it avoids certain
320 * privacy-breaking recipient-probing attacks which may reveal payment activity to
321 * motivated attackers.
323 * Note that the privacy concerns in (b) are not relevant in payments with a payment_secret
324 * set. Thus, for such payments we will claim any payments which do not under-pay.
326 * May panic if called except in response to a PaymentReceived event.
328 public boolean claim_funds(byte[] payment_preimage, byte[] payment_secret, long expected_amount) {
329 boolean ret = bindings.ChannelManager_claim_funds(this.ptr, payment_preimage, payment_secret, expected_amount);
334 * Gets the node_id held by this ChannelManager
336 public byte[] get_our_node_id() {
337 byte[] ret = bindings.ChannelManager_get_our_node_id(this.ptr);
342 * Restores a single, given channel to normal operation after a
343 * ChannelMonitorUpdateErr::TemporaryFailure was returned from a channel monitor update
346 * All ChannelMonitor updates up to and including highest_applied_update_id must have been
347 * fully committed in every copy of the given channels' ChannelMonitors.
349 * Note that there is no effect to calling with a highest_applied_update_id other than the
350 * current latest ChannelMonitorUpdate and one call to this function after multiple
351 * ChannelMonitorUpdateErr::TemporaryFailures is fine. The highest_applied_update_id field
352 * exists largely only to prevent races between this and concurrent update_monitor calls.
354 * Thus, the anticipated use is, at a high level:
355 * 1) You register a chain::Watch with this ChannelManager,
356 * 2) it stores each update to disk, and begins updating any remote (eg watchtower) copies of
357 * said ChannelMonitors as it can, returning ChannelMonitorUpdateErr::TemporaryFailures
358 * any time it cannot do so instantly,
359 * 3) update(s) are applied to each remote copy of a ChannelMonitor,
360 * 4) once all remote copies are updated, you call this function with the update_id that
361 * completed, and once it is the latest the Channel will be re-enabled.
363 public void channel_monitor_updated(OutPoint funding_txo, long highest_applied_update_id) {
364 bindings.ChannelManager_channel_monitor_updated(this.ptr, funding_txo == null ? 0 : funding_txo.ptr & ~1, highest_applied_update_id);
365 this.ptrs_to.add(funding_txo);
369 * Constructs a new MessageSendEventsProvider which calls the relevant methods on this_arg.
370 * This copies the `inner` pointer in this_arg and thus the returned MessageSendEventsProvider must be freed before this_arg is
372 public MessageSendEventsProvider as_MessageSendEventsProvider() {
373 long ret = bindings.ChannelManager_as_MessageSendEventsProvider(this.ptr);
374 MessageSendEventsProvider ret_hu_conv = new MessageSendEventsProvider(null, ret);
375 ret_hu_conv.ptrs_to.add(this);
380 * Constructs a new EventsProvider which calls the relevant methods on this_arg.
381 * This copies the `inner` pointer in this_arg and thus the returned EventsProvider must be freed before this_arg is
383 public EventsProvider as_EventsProvider() {
384 long ret = bindings.ChannelManager_as_EventsProvider(this.ptr);
385 EventsProvider ret_hu_conv = new EventsProvider(null, ret);
386 ret_hu_conv.ptrs_to.add(this);
391 * Constructs a new Listen which calls the relevant methods on this_arg.
392 * This copies the `inner` pointer in this_arg and thus the returned Listen must be freed before this_arg is
394 public Listen as_Listen() {
395 long ret = bindings.ChannelManager_as_Listen(this.ptr);
396 Listen ret_hu_conv = new Listen(null, ret);
397 ret_hu_conv.ptrs_to.add(this);
402 * Updates channel state to take note of transactions which were confirmed in the given block
403 * at the given height.
405 * Note that you must still call (or have called) [`update_best_block`] with the block
406 * information which is included here.
408 * This method may be called before or after [`update_best_block`] for a given block's
409 * transaction data and may be called multiple times with additional transaction data for a
412 * This method may be called for a previous block after an [`update_best_block`] call has
413 * been made for a later block, however it must *not* be called with transaction data from a
414 * block which is no longer in the best chain (ie where [`update_best_block`] has already
415 * been informed about a blockchain reorganization which no longer includes the block which
416 * corresponds to `header`).
418 * [`update_best_block`]: `Self::update_best_block`
420 public void transactions_confirmed(byte[] header, int height, TwoTuple<Long, byte[]>[] txdata) {
421 bindings.ChannelManager_transactions_confirmed(this.ptr, header, height, Arrays.stream(txdata).mapToLong(txdata_conv_24 -> bindings.C2Tuple_usizeTransactionZ_new(txdata_conv_24.a, txdata_conv_24.b)).toArray());
422 /* TODO 2 TwoTuple<Long, byte[]> */;
426 * Updates channel state with the current best blockchain tip. You should attempt to call this
427 * quickly after a new block becomes available, however if multiple new blocks become
428 * available at the same time, only a single `update_best_block()` call needs to be made.
430 * This method should also be called immediately after any block disconnections, once at the
431 * reorganization fork point, and once with the new chain tip. Calling this method at the
432 * blockchain reorganization fork point ensures we learn when a funding transaction which was
433 * previously confirmed is reorganized out of the blockchain, ensuring we do not continue to
434 * accept payments which cannot be enforced on-chain.
436 * In both the block-connection and block-disconnection case, this method may be called either
437 * once per block connected or disconnected, or simply at the fork point and new tip(s),
438 * skipping any intermediary blocks.
440 public void update_best_block(byte[] header, int height) {
441 bindings.ChannelManager_update_best_block(this.ptr, header, height);
445 * Gets the set of txids which should be monitored for their confirmation state.
447 * If you're providing information about reorganizations via [`transaction_unconfirmed`], this
448 * is the set of transactions which you may need to call [`transaction_unconfirmed`] for.
450 * This may be useful to poll to determine the set of transactions which must be registered
451 * with an Electrum server or for which an Electrum server needs to be polled to determine
452 * transaction confirmation state.
454 * This may update after any [`transactions_confirmed`] or [`block_connected`] call.
456 * Note that this is NOT the set of transactions which must be included in calls to
457 * [`transactions_confirmed`] if they are confirmed, but a small subset of it.
459 * [`transactions_confirmed`]: Self::transactions_confirmed
460 * [`transaction_unconfirmed`]: Self::transaction_unconfirmed
461 * [`block_connected`]: chain::Listen::block_connected
463 public byte[][] get_relevant_txids() {
464 byte[][] ret = bindings.ChannelManager_get_relevant_txids(this.ptr);
469 * Marks a transaction as having been reorganized out of the blockchain.
471 * If a transaction is included in [`get_relevant_txids`], and is no longer in the main branch
472 * of the blockchain, this function should be called to indicate that the transaction should
473 * be considered reorganized out.
475 * Once this is called, the given transaction will no longer appear on [`get_relevant_txids`],
476 * though this may be called repeatedly for a given transaction without issue.
478 * Note that if the transaction is confirmed on the main chain in a different block (indicated
479 * via a call to [`transactions_confirmed`]), it may re-appear in [`get_relevant_txids`], thus
480 * be very wary of race-conditions wherein the final state of a transaction indicated via
481 * these APIs is not the same as its state on the blockchain.
483 * [`transactions_confirmed`]: Self::transactions_confirmed
484 * [`get_relevant_txids`]: Self::get_relevant_txids
486 public void transaction_unconfirmed(byte[] txid) {
487 bindings.ChannelManager_transaction_unconfirmed(this.ptr, txid);
491 * Blocks until ChannelManager needs to be persisted or a timeout is reached. It returns a bool
492 * indicating whether persistence is necessary. Only one listener on
493 * `await_persistable_update` or `await_persistable_update_timeout` is guaranteed to be woken
495 * Note that the feature `allow_wallclock_use` must be enabled to use this function.
497 public boolean await_persistable_update_timeout(long max_wait) {
498 boolean ret = bindings.ChannelManager_await_persistable_update_timeout(this.ptr, max_wait);
503 * Blocks until ChannelManager needs to be persisted. Only one listener on
504 * `await_persistable_update` or `await_persistable_update_timeout` is guaranteed to be woken
507 public void await_persistable_update() {
508 bindings.ChannelManager_await_persistable_update(this.ptr);
512 * Constructs a new ChannelMessageHandler which calls the relevant methods on this_arg.
513 * This copies the `inner` pointer in this_arg and thus the returned ChannelMessageHandler must be freed before this_arg is
515 public ChannelMessageHandler as_ChannelMessageHandler() {
516 long ret = bindings.ChannelManager_as_ChannelMessageHandler(this.ptr);
517 ChannelMessageHandler ret_hu_conv = new ChannelMessageHandler(null, ret);
518 ret_hu_conv.ptrs_to.add(this);
523 * Serialize the ChannelManager object into a byte array which can be read by ChannelManager_read
525 public byte[] write() {
526 byte[] ret = bindings.ChannelManager_write(this.ptr);