Skip to content

Commit

Permalink
Update MessageHandler parameters
Browse files Browse the repository at this point in the history
  • Loading branch information
Conor Okus committed Jan 3, 2024
1 parent 45cc7af commit 884848b
Show file tree
Hide file tree
Showing 4 changed files with 68 additions and 136 deletions.
8 changes: 5 additions & 3 deletions docs/tutorials/building-a-node-with-ldk/handling-events.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,14 @@ use lightning::util::events::{Event};
// In the event handler passed to BackgroundProcessor::start
match event {
Event::PaymentSent { payment_preimage } => {
// Handle successful payment
// Handle successful payment
}
Event::PaymentFailed { payment_hash, rejected_by_dest } => {
// Handle failed payment
// Handle failed payment
}
Event::FundingGenerationReady { .. } => {
// Generate the funding transaction for the channel
}
Event::FundingGenerationReady { .. } =>
}
```

Expand Down
8 changes: 4 additions & 4 deletions docs/tutorials/building-a-node-with-ldk/introduction.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,10 @@ For an integrated example of an LDK node in Rust, see the [Sample Node](https://
The following tutorials will show you how to build the simplest lightning node using LDK, that fufills the following tasks:

1. **Connecting to Peers**
2. **Open Channels**
3. **Send Payments**
4. **Receive Payments**
5. **Close Channels**
2. **Opening Channels**
3. **Sending Payments**
4. **Receiving Payments**
5. **Closing Channels**

### Foundational Components

Expand Down
136 changes: 31 additions & 105 deletions docs/tutorials/building-a-node-with-ldk/sending-payments.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ string in accordance with BOLT 11. After parsing the invoice, you'll need to
find a route from your node to the recipient and then make the payment using
`ChannelManager`.

<CodeSwitcher :languages="{rust:'Rust', java:'Java', kotlin:'Kotlin', swift:'Swift'}">
<CodeSwitcher :languages="{rust:'Rust', kotlin:'Kotlin', swift:'Swift'}">
<template v-slot:rust>

```rust
Expand Down Expand Up @@ -39,113 +39,40 @@ channel_manager.send_payment(&route, payment_hash, &payment_secret)
```

</template>
<template v-slot:java>

```java
String invoice_str = // get an invoice from the payee
Result_InvoiceNoneZ parsed_invoice = Invoice.from_str(invoice_str);

if (parsed_invoice instanceof Result_InvoiceNoneZ.Result_InvoiceNoneZ_OK) {
Invoice invoice = ((Result_InvoiceNoneZ.Result_InvoiceNoneZ_OK) parsed_invoice).res;
long amt_msat = 0;
if (invoice.amount_pico_btc() instanceof Option_u64Z.Some) {
amt_msat = ((Option_u64Z.Some)invoice.amount_pico_btc()).some / 10;
}
if (amt_msat == 0) {
// <Handle a zero-value invoice>
}

Route route;
try (LockedNetworkGraph netgraph = router.read_locked_graph()) {
NetworkGraph graph = netgraph.graph();
Result_RouteLightningErrorZ route_res = UtilMethods.get_route(
channel_manager.get_our_node_id(),
graph, invoice.recover_payee_pub_key(), invoice.features(),
channel_manager.list_usable_channels(), invoice.route_hints(),
amt_msat, invoice.min_final_cltv_expiry(), logger);
assert route_res instanceof Result_RouteLightningErrorZ.Result_RouteLightningErrorZ_OK;
route = ((Result_RouteLightningErrorZ.Result_RouteLightningErrorZ_OK) route_res).res;
}

Result_NonePaymentSendFailureZ payment_res = channel_manager.send_payment(
route, invoice.payment_hash(), invoice.payment_secret());
assert payment_res instanceof Result_NonePaymentSendFailureZ.Result_NonePaymentSendFailureZ_OK;
}
```

</template>
<template v-slot:kotlin>
<template v-slot:kotlin>

```java
// Get an invoice from the recipient/payee
val parsedInvoice = Invoice.from_str(recipientInvoice)
if (!parsedInvoice.is_ok) {
// Unable to parse invoice
}
val parsedInvoice = Bolt11Invoice.from_str(recipientInvoice)
val invoiceVal = (parsedInvoice as Result_Bolt11InvoiceSignOrCreationErrorZ.Result_Bolt11InvoiceSignOrCreationErrorZ_OK).res

val invoice = (parsedInvoice as Result_InvoiceParseOrSemanticErrorZ.Result_InvoiceParseOrSemanticErrorZ_OK).res
val res = UtilMethods.pay_invoice(invoice, Retry.attempts(6), channelManager)

var amountSats: Long = 0
if (invoice.amount_milli_satoshis() is Option_u64Z.Some) {
amountSats = (invoice.amount_milli_satoshis() as Option_u64Z.Some).some * 1000
}

if (amountSats == 0L) {
// Handle a zero-value invoice
}

val res = channelManagerConstructor.payer.pay_invoice(invoice)



if (parsed_invoice instanceof Result_InvoiceNoneZ.Result_InvoiceNoneZ_OK) {
Invoice invoice = ((Result_InvoiceNoneZ.Result_InvoiceNoneZ_OK) parsed_invoice).res;
long amt_msat = 0;
if (invoice.amount_pico_btc() instanceof Option_u64Z.Some) {
amt_msat = ((Option_u64Z.Some)invoice.amount_pico_btc()).some / 10;
}
if (amt_msat == 0) {
// <Handle a zero-value invoice>
}

Route route;
try (LockedNetworkGraph netgraph = router.read_locked_graph()) {
NetworkGraph graph = netgraph.graph();
Result_RouteLightningErrorZ route_res = UtilMethods.get_route(
channel_manager.get_our_node_id(),
graph, invoice.recover_payee_pub_key(), invoice.features(),
channel_manager.list_usable_channels(), invoice.route_hints(),
amt_msat, invoice.min_final_cltv_expiry(), logger);
assert route_res instanceof Result_RouteLightningErrorZ.Result_RouteLightningErrorZ_OK;
route = ((Result_RouteLightningErrorZ.Result_RouteLightningErrorZ_OK) route_res).res;
}

Result_NonePaymentSendFailureZ payment_res = channel_manager.send_payment(
route, invoice.payment_hash(), invoice.payment_secret());
assert payment_res instanceof Result_NonePaymentSendFailureZ.Result_NonePaymentSendFailureZ_OK;
if (res.is_ok) {
// Payment success
}
```

</template>

<template v-slot:swift>

```Swift
let invoiceStr = // get an invoice from the payee
let parsedInvoice = Bolt11Invoice.fromStr(s: invoiceStr)

if let invoiceVal = parsedInvoice.getValue() {
let invoicePaymentResult = Bindings.payInvoice(
invoice: invoiceVal,
retryStrategy: Bindings.Retry.initWithTimeout(a: 15),
channelmanager: channelManager
)

if invoicePaymentResult.isOk() {
// Payment Sent
}
```Swift
let invoiceStr = // get an invoice from the payee
let parsedInvoice = Bolt11Invoice.fromStr(s: invoiceStr)

if let invoiceVal = parsedInvoice.getValue() {
let invoicePaymentResult = Bindings.payInvoice(
invoice: invoiceVal,
retryStrategy: Bindings.Retry.initWithTimeout(a: 15),
channelmanager: channelManager
)

if invoicePaymentResult.isOk() {
// Payment Sent
}
```
}
```

</template>

Expand All @@ -156,7 +83,7 @@ in a `PaymentSent` event with the preimage of the payment hash. Be sure to look
out for a `PaymentFailed` event, if the payment fails for some reason, and act
accordingly.

<CodeSwitcher :languages="{rust:'Rust', java:'Java', swift:'Swift'}">
<CodeSwitcher :languages="{rust:'Rust', kotlin:'Kotlin', swift:'Swift'}">
<template v-slot:rust>

```rust
Expand All @@ -173,17 +100,16 @@ match event {
```

</template>
<template v-slot:java>
<template v-slot:kotlin>

```java
// In the `handle_event` method of ChannelManagerPersister implementation
else if (e instanceof Event.PaymentSent) {
// Handle successful payment
Event.PaymentSent event = ((Event.PaymentSent) e);
// In the `handleEvent` method of ChannelManagerPersister implementation
if(event is Event.PaymentSent) {
// Handle successful payment
}
else if (e instanceof Event.PaymentFailed) {
// Handle failed payment
Event.PaymentFailed event = ((Event.PaymentFailed) e);

if(event is Event.PaymentFailed) {
// Handle failed payment
}
```

Expand All @@ -202,4 +128,4 @@ if let paymentSentEvent = event.getValueAsPaymentSent() {

</template>

</CodeSwitcher>
</CodeSwitcher>
Original file line number Diff line number Diff line change
@@ -1,35 +1,39 @@
# Setting up a PeerManager

The Peer Manager is responsible for managing a set of peer connections and all data associated with those peers.
The Peer Manager is responsible for managing a set of peer connections and data associated with those peers.


## Adding a PeerManager
## Adding a `PeerManager`

To add a PeerManager to your application, run:

<CodeSwitcher :languages="{rust:'Rust', kotlin:'Kotlin', swift:'Swift'}">
<template v-slot:rust>

```rust
use lightning::ln::peer_handler::{PeerManager};

let mut ephemeral_bytes = [0; 32];
rand::thread_rng().fill_bytes(&mut ephemeral_bytes);

let lightning_msg_handler = MessageHandler {
chan_handler: &channel_manager,
route_handler: &gossip_sync,
};

let ignoring_custom_msg_handler = IgnoringMessageHandler {};
let peer_manager = PeerManager::new(
lightning_msg_handler,
keys_manager.get_node_secret(),
&ephemeral_bytes,
&logger,
&ignoring_custom_msg_handler,
);
```
```rust
use lightning::ln::peer_handler::{PeerManager};

let mut ephemeral_bytes = [0; 32];
rand::thread_rng().fill_bytes(&mut ephemeral_bytes);

let lightning_msg_handler = MessageHandler {
chan_handler: channel_manager,
route_handler: gossip_sync,
onion_message_handler: onion_messenger,
custom_message_handler: IgnoringMessageHandler {}
};

let peer_manager = PeerManager::new(
lightning_msg_handler,
cur_time.as_secs().try_into().map_err(|e| {
log_error!(logger, "Failed to get current time: {}", e);
BuildError::InvalidSystemTime
})?,
&ephemeral_bytes,
&logger,
&keys_manager
);
```

</template>

<template v-slot:kotlin>
Expand Down Expand Up @@ -58,4 +62,4 @@ To add a PeerManager to your application, run:

**Dependencies:** `ChannelManager`, `RoutingMessageHandler`, `KeysManager`, random bytes, `Logger`

**References:** [Rust `PeerManager` docs](https://docs.rs/lightning/*/lightning/ln/peer_handler/struct.PeerManager.html), [Rust `RoutingMessageHandler` docs](https://docs.rs/lightning/*/lightning/ln/msgs/trait.RoutingMessageHandler.html), [Java `PeerManager` bindings](https://github.com/lightningdevkit/ldk-garbagecollected/blob/main/src/main/java/org/ldk/structs/PeerManager.java), [Java `RoutingMessageHandler` bindings](https://github.com/lightningdevkit/ldk-garbagecollected/blob/main/src/main/java/org/ldk/structs/RoutingMessageHandler.java)
**References:** [Rust `PeerManager` docs](https://docs.rs/lightning/*/lightning/ln/peer_handler/struct.PeerManager.html), [Rust `RoutingMessageHandler` docs](https://docs.rs/lightning/*/lightning/ln/msgs/trait.RoutingMessageHandler.html), [Java `PeerManager` bindings](https://github.com/lightningdevkit/ldk-garbagecollected/blob/main/src/main/java/org/ldk/structs/PeerManager.java), [Java `RoutingMessageHandler` bindings](https://github.com/lightningdevkit/ldk-garbagecollected/blob/main/src/main/java/org/ldk/structs/RoutingMessageHandler.java)

0 comments on commit 884848b

Please sign in to comment.