Skip to content

Commit afb6c7c

Browse files
committed
update ffi for BasicMPP
1 parent baf86a1 commit afb6c7c

File tree

5 files changed

+46
-11
lines changed

5 files changed

+46
-11
lines changed

bindings/src/adaptors/mod.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -442,7 +442,7 @@ impl RoutingMessageHandler for FFIRoutingMsgHandler {
442442
unimplemented!()
443443
}
444444

445-
fn get_next_channel_announcements(&self, starting_point: u64, batch_amount: u8) -> Vec<(ChannelAnnouncement, ChannelUpdate, ChannelUpdate)> {
445+
fn get_next_channel_announcements(&self, starting_point: u64, batch_amount: u8) -> Vec<(ChannelAnnouncement, Option<ChannelUpdate>, Option<ChannelUpdate>)> {
446446
unimplemented!()
447447
}
448448

bindings/src/adaptors/primitives.rs

Lines changed: 17 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ use bitcoin::blockdata::transaction::{Transaction};
55
use bitcoin_hashes::sha256d::Hash as Sha256dHash;
66
use crate::FFIResult;
77
use lightning::chain::chaininterface::ChainError;
8-
use lightning::ln::channelmanager::PaymentHash;
8+
use lightning::ln::channelmanager::{PaymentHash, PaymentSecret};
99
use lightning::ln::router::{RouteHop, Route};
1010
use lightning::util::ser::{Readable, Writeable};
1111
use bitcoin_hashes::core::fmt::{Formatter, Error};
@@ -123,6 +123,17 @@ impl<'a> From<Sha256dHash> for FFISha256dHash<'a> {
123123
}
124124
}
125125

126+
array_struct!(FFISecret, u8);
127+
128+
impl<'a> TryFrom<FFISecret<'a>> for PaymentSecret {
129+
type Error = FFIResult;
130+
131+
fn try_from(ffi_secret: FFISecret) -> Result<PaymentSecret, Self::Error> {
132+
let s = unsafe_block!("" => std::slice::from_raw_parts(ffi_secret.ptr, ffi_secret.len));
133+
let s:[u8; 32] = s.try_into().map_err(|_| FFIResult::invalid_data_length())?;
134+
Ok(PaymentSecret(s))
135+
}
136+
}
126137

127138
array_struct!(FFIScript, u8);
128139
impl<'a> FFIScript<'a> {
@@ -169,11 +180,11 @@ impl From<FFIChainError> for ChainError {
169180
array_struct!(FFIRoute, u8);
170181

171182
impl<'a> TryFrom<FFIRoute<'a>> for Route {
172-
type Error = lightning::ln::msgs::DecodeError;
183+
type Error = FFIResult;
173184

174185
fn try_from(value: FFIRoute<'a>) -> Result<Self, Self::Error> {
175186
let mut slice = value.as_ref();
176-
<Route as Readable>::read(&mut slice)
187+
<Route as Readable>::read(&mut slice).map_err(|_| FFIResult::deserialization_failure())
177188
}
178189
}
179190

@@ -184,16 +195,15 @@ array_struct!(FFIEvents, u8);
184195
/// General purpose byte array which has to cross ffi-boundary
185196
array_struct!(FFIBytes, u8);
186197

187-
impl<'a> TryFrom<Vec<Event>> for FFIEvents<'a> {
188-
type Error = lightning::ln::msgs::DecodeError;
198+
impl<'a> From<Vec<Event>> for FFIEvents<'a> {
189199

190-
fn try_from(value: Vec<Event>) -> Result<Self, Self::Error> {
200+
fn from(value: Vec<Event>) -> Self {
191201
let len = value.len();
192202
let mut result_vec: Vec<u8> = Vec::with_capacity(len * std::mem::size_of::<Event>());
193203
for e in value {
194204
result_vec.extend(e.encode());
195205
}
196206
let r = result_vec.into_boxed_slice();
197-
Ok(r.into())
207+
r.into()
198208
}
199209
}

bindings/src/channelmanager.rs

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -15,14 +15,15 @@ use crate::{
1515
error::FFIResult,
1616
handle::{Out, Ref, HandleShared},
1717
adaptors::*,
18-
adaptors::primitives::{FFISha256dHash, FFIRoute, FFIEvents},
18+
adaptors::primitives::{FFISha256dHash, FFIRoute, FFIEvents, FFISecret},
1919
channelmonitor::{FFIManyChannelMonitor},
2020
};
2121
use lightning::util::events::EventsProvider;
2222

2323
pub type FFIArcChannelManager = ChannelManager<InMemoryChannelKeys, Arc<FFIManyChannelMonitor>, Arc<FFIBroadCaster>, Arc<KeysManager>, Arc<FFIFeeEstimator>>;
2424
pub type FFIArcChannelManagerHandle<'a> = HandleShared<'a, FFIArcChannelManager>;
2525

26+
2627
pub(crate) fn construct_channel_manager(
2728
seed_ptr: Ref<u8>,
2829
seed_len: usize,
@@ -129,16 +130,20 @@ ffi! {
129130
unsafe_block!("We know chan_man is not null by wrapper macro. And we know `Out` is writable" => chan_man.init(HandleShared::alloc(chan_man_raw)));
130131
FFIResult::ok()
131132
}
132-
fn send_payment(handle: FFIArcChannelManagerHandle, route_ref: Ref<FFIRoute>, payment_hash_ref: Ref<FFISha256dHash>) -> FFIResult {
133+
134+
fn send_payment(handle: FFIArcChannelManagerHandle, route_ref: Ref<FFIRoute>, payment_hash_ref: Ref<FFISha256dHash>, payment_secret_ref: Ref<FFISecret>) -> FFIResult {
133135
let chan_man = unsafe_block!("We know handle points to valid channel_manager" => handle.as_ref());
134136
let route_ffi: &FFIRoute = unsafe_block!("We know it points to valid route data" => route_ref.as_ref());
135137
let payment_hash_ffi: &FFISha256dHash = unsafe_block!("We know it points to valid hash data" => payment_hash_ref.as_ref());
136138
let payment_hash: PaymentHash = payment_hash_ffi.clone().try_into()?;
139+
let payment_secret: &FFISecret = unsafe_block!("We know it points to valid payment_secret data or empty 32 bytes" => payment_secret_ref.as_ref());
140+
let maybe_secret = if payment_secret.as_ref().is_empty() { None } else { Some(payment_secret.deep_copy().try_into()?) };
137141
let route: Route = route_ffi.clone().try_into()?;
138-
chan_man.send_payment(route, payment_hash)?;
142+
chan_man.send_payment(&route, payment_hash, &maybe_secret)?;
139143
FFIResult::ok()
140144
}
141145

146+
142147
fn get_and_clear_pending_events(handle: FFIArcChannelManagerHandle, events: Out<FFIEvents>) -> FFIResult {
143148
let chan_man: &FFIArcChannelManager = unsafe_block!("We know handle points to valid channel_manager" => handle.as_ref());
144149
let e = chan_man.get_and_clear_pending_events().try_into()?;

bindings/src/error.rs

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,8 @@ pub enum Kind {
3434
Ok,
3535
EmptyPointerProvided,
3636
InvalidDataLength,
37+
/// Indicates we have passed byte array from wrapper which is not rust-lightning compatible.
38+
DeserializationFailure,
3739
/// Return this when buffer for allocating error message is too small.
3840
/// When this is the last error, the caller should try to increase the buffer size and call the function again.
3941
BufferTooSmall,
@@ -134,6 +136,14 @@ impl FFIResult {
134136
self.kind == Kind::EmptyPointerProvided
135137
}
136138

139+
pub(super) fn deserialization_failure() -> Self {
140+
FFIResult { kind: Kind::DeserializationFailure, id: next_err_id() }
141+
}
142+
143+
pub fn is_deserialization_failure(&self) -> bool {
144+
self.kind == Kind::DeserializationFailure
145+
}
146+
137147
pub(super) fn buffer_too_small() -> Self {
138148
FFIResult { kind: Kind::BufferTooSmall, id: next_err_id() }
139149
}
@@ -165,6 +175,7 @@ impl FFIResult {
165175
Kind::Ok => None,
166176
Kind::EmptyPointerProvided => Some("a required pointer argument was null"),
167177
Kind::InvalidDataLength => Some("provided data buffer has invalid length"),
178+
Kind::DeserializationFailure => Some("Failed to deserialize byte array passed to ffi"),
168179
Kind::InternalError => Some("An internal error occured"),
169180
Kind::BufferTooSmall => Some("buffer was too small"),
170181
}

lightning/src/ln/channelmanager.rs

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,7 @@ use std::sync::atomic::{AtomicUsize, Ordering};
5050
use std::time::Duration;
5151
use std::marker::{Sync, Send};
5252
use std::ops::Deref;
53+
use bitcoin_hashes::core::fmt::{Formatter, Error};
5354

5455
// We hold various information about HTLC relay in the HTLC objects in Channel itself:
5556
//
@@ -518,6 +519,14 @@ pub enum PaymentSendFailure {
518519
PartialFailure(Vec<Result<(), APIError>>),
519520
}
520521

522+
impl std::fmt::Display for PaymentSendFailure {
523+
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
524+
write!(f, "{:?}", self)
525+
}
526+
}
527+
528+
impl std::error::Error for PaymentSendFailure {}
529+
521530
macro_rules! handle_error {
522531
($self: ident, $internal: expr, $their_node_id: expr) => {
523532
match $internal {

0 commit comments

Comments
 (0)