Update auto-generated bindings to LDK 0.0.121
[ldk-c-bindings] / lightning-c-bindings / src / lightning_rapid_gossip_sync.rs
1 // This file is Copyright its original authors, visible in version control
2 // history and in the source files from which this was generated.
3 //
4 // This file is licensed under the license available in the LICENSE or LICENSE.md
5 // file in the root of this repository or, if no such file exists, the same
6 // license as that which applies to the original source files from which this
7 // source was automatically generated.
8
9 //! This crate exposes client functionality to rapidly sync gossip data, aimed primarily at mobile
10 //! devices.
11 //!
12 //! The rapid gossip sync server will provide a compressed response containing differential gossip
13 //! data. The gossip data is formatted compactly, omitting signatures and opportunistically
14 //! incremental where previous channel updates are known. This mechanism is enabled when the
15 //! timestamp of the last known channel update is communicated. A reference server implementation
16 //! can be found [on Github](https://github.com/lightningdevkit/rapid-gossip-sync-server).
17 //!
18 //! The primary benefit of this syncing mechanism is that it allows a low-powered client to offload
19 //! the validation of gossip signatures to a semi-trusted server. This enables the client to
20 //! privately calculate routes for payments, and to do so much faster than requiring a full
21 //! peer-to-peer gossip sync to complete.
22 //!
23 //! The server calculates its response on the basis of a client-provided `latest_seen` timestamp,
24 //! i.e., the server will return all rapid gossip sync data it has seen after the given timestamp.
25 //!
26 //! # Getting Started
27 //! Firstly, the data needs to be retrieved from the server. For example, you could use the server
28 //! at <https://rapidsync.lightningdevkit.org> with the following request format:
29 //!
30 //! ```shell
31 //! curl -o rapid_sync.lngossip https://rapidsync.lightningdevkit.org/snapshot/<last_sync_timestamp>
32 //! ```
33 //! Note that the first ever rapid sync should use `0` for `last_sync_timestamp`.
34 //!
35 //! After the gossip data snapshot has been downloaded, one of the client's graph processing
36 //! functions needs to be called. In this example, we process the update by reading its contents
37 //! from disk, which we do by calling [`RapidGossipSync::update_network_graph`]:
38 //!
39 //! ```
40 //! use bitcoin::blockdata::constants::genesis_block;
41 //! use bitcoin::Network;
42 //! use lightning::routing::gossip::NetworkGraph;
43 //! use lightning_rapid_gossip_sync::RapidGossipSync;
44 //!
45 //! # use lightning::util::logger::{Logger, Record};
46 //! # struct FakeLogger {}
47 //! # impl Logger for FakeLogger {
48 //! #     fn log(&self, record: Record) { }
49 //! # }
50 //! # let logger = FakeLogger {};
51 //!
52 //! let network_graph = NetworkGraph::new(Network::Bitcoin, &logger);
53 //! let rapid_sync = RapidGossipSync::new(&network_graph, &logger);
54 //! let snapshot_contents: &[u8] = &[0; 0];
55 //! // In no-std you need to provide the current time in unix epoch seconds
56 //! // otherwise you can use update_network_graph
57 //! let current_time_unix = 0;
58 //! let new_last_sync_timestamp_result = rapid_sync.update_network_graph_no_std(snapshot_contents, Some(current_time_unix));
59 //! ```
60
61 use alloc::str::FromStr;
62 use alloc::string::String;
63 use core::ffi::c_void;
64 use core::convert::Infallible;
65 use bitcoin::hashes::Hash;
66 use crate::c_types::*;
67 #[cfg(feature="no-std")]
68 use alloc::{vec::Vec, boxed::Box};
69
70 mod processing {
71
72 use alloc::str::FromStr;
73 use alloc::string::String;
74 use core::ffi::c_void;
75 use core::convert::Infallible;
76 use bitcoin::hashes::Hash;
77 use crate::c_types::*;
78 #[cfg(feature="no-std")]
79 use alloc::{vec::Vec, boxed::Box};
80
81 }
82 /// All-encompassing standard error type that processing can return
83 #[derive(Clone)]
84 #[must_use]
85 #[repr(C)]
86 pub enum GraphSyncError {
87         /// Error trying to read the update data, typically due to an erroneous data length indication
88         /// that is greater than the actual amount of data provided
89         DecodeError(
90                 crate::lightning::ln::msgs::DecodeError),
91         /// Error applying the patch to the network graph, usually the result of updates that are too
92         /// old or missing prerequisite data to the application of updates out of order
93         LightningError(
94                 crate::lightning::ln::msgs::LightningError),
95 }
96 use lightning_rapid_gossip_sync::GraphSyncError as GraphSyncErrorImport;
97 pub(crate) type nativeGraphSyncError = GraphSyncErrorImport;
98
99 impl GraphSyncError {
100         #[allow(unused)]
101         pub(crate) fn to_native(&self) -> nativeGraphSyncError {
102                 match self {
103                         GraphSyncError::DecodeError (ref a, ) => {
104                                 let mut a_nonref = Clone::clone(a);
105                                 nativeGraphSyncError::DecodeError (
106                                         a_nonref.into_native(),
107                                 )
108                         },
109                         GraphSyncError::LightningError (ref a, ) => {
110                                 let mut a_nonref = Clone::clone(a);
111                                 nativeGraphSyncError::LightningError (
112                                         *unsafe { Box::from_raw(a_nonref.take_inner()) },
113                                 )
114                         },
115                 }
116         }
117         #[allow(unused)]
118         pub(crate) fn into_native(self) -> nativeGraphSyncError {
119                 match self {
120                         GraphSyncError::DecodeError (mut a, ) => {
121                                 nativeGraphSyncError::DecodeError (
122                                         a.into_native(),
123                                 )
124                         },
125                         GraphSyncError::LightningError (mut a, ) => {
126                                 nativeGraphSyncError::LightningError (
127                                         *unsafe { Box::from_raw(a.take_inner()) },
128                                 )
129                         },
130                 }
131         }
132         #[allow(unused)]
133         pub(crate) fn from_native(native: &GraphSyncErrorImport) -> Self {
134                 let native = unsafe { &*(native as *const _ as *const c_void as *const nativeGraphSyncError) };
135                 match native {
136                         nativeGraphSyncError::DecodeError (ref a, ) => {
137                                 let mut a_nonref = Clone::clone(a);
138                                 GraphSyncError::DecodeError (
139                                         crate::lightning::ln::msgs::DecodeError::native_into(a_nonref),
140                                 )
141                         },
142                         nativeGraphSyncError::LightningError (ref a, ) => {
143                                 let mut a_nonref = Clone::clone(a);
144                                 GraphSyncError::LightningError (
145                                         crate::lightning::ln::msgs::LightningError { inner: ObjOps::heap_alloc(a_nonref), is_owned: true },
146                                 )
147                         },
148                 }
149         }
150         #[allow(unused)]
151         pub(crate) fn native_into(native: nativeGraphSyncError) -> Self {
152                 match native {
153                         nativeGraphSyncError::DecodeError (mut a, ) => {
154                                 GraphSyncError::DecodeError (
155                                         crate::lightning::ln::msgs::DecodeError::native_into(a),
156                                 )
157                         },
158                         nativeGraphSyncError::LightningError (mut a, ) => {
159                                 GraphSyncError::LightningError (
160                                         crate::lightning::ln::msgs::LightningError { inner: ObjOps::heap_alloc(a), is_owned: true },
161                                 )
162                         },
163                 }
164         }
165 }
166 /// Frees any resources used by the GraphSyncError
167 #[no_mangle]
168 pub extern "C" fn GraphSyncError_free(this_ptr: GraphSyncError) { }
169 /// Creates a copy of the GraphSyncError
170 #[no_mangle]
171 pub extern "C" fn GraphSyncError_clone(orig: &GraphSyncError) -> GraphSyncError {
172         orig.clone()
173 }
174 #[allow(unused)]
175 /// Used only if an object of this type is returned as a trait impl by a method
176 pub(crate) extern "C" fn GraphSyncError_clone_void(this_ptr: *const c_void) -> *mut c_void {
177         Box::into_raw(Box::new(unsafe { (*(this_ptr as *const GraphSyncError)).clone() })) as *mut c_void
178 }
179 #[allow(unused)]
180 /// Used only if an object of this type is returned as a trait impl by a method
181 pub(crate) extern "C" fn GraphSyncError_free_void(this_ptr: *mut c_void) {
182         let _ = unsafe { Box::from_raw(this_ptr as *mut GraphSyncError) };
183 }
184 #[no_mangle]
185 /// Utility method to constructs a new DecodeError-variant GraphSyncError
186 pub extern "C" fn GraphSyncError_decode_error(a: crate::lightning::ln::msgs::DecodeError) -> GraphSyncError {
187         GraphSyncError::DecodeError(a, )
188 }
189 #[no_mangle]
190 /// Utility method to constructs a new LightningError-variant GraphSyncError
191 pub extern "C" fn GraphSyncError_lightning_error(a: crate::lightning::ln::msgs::LightningError) -> GraphSyncError {
192         GraphSyncError::LightningError(a, )
193 }
194 /// Get a string which allows debug introspection of a GraphSyncError object
195 pub extern "C" fn GraphSyncError_debug_str_void(o: *const c_void) -> Str {
196         alloc::format!("{:?}", unsafe { o as *const crate::lightning_rapid_gossip_sync::GraphSyncError }).into()}
197
198 use lightning_rapid_gossip_sync::RapidGossipSync as nativeRapidGossipSyncImport;
199 pub(crate) type nativeRapidGossipSync = nativeRapidGossipSyncImport<&'static lightning::routing::gossip::NetworkGraph<crate::lightning::util::logger::Logger>, crate::lightning::util::logger::Logger>;
200
201 /// The main Rapid Gossip Sync object.
202 ///
203 /// See [crate-level documentation] for usage.
204 ///
205 /// [crate-level documentation]: crate
206 #[must_use]
207 #[repr(C)]
208 pub struct RapidGossipSync {
209         /// A pointer to the opaque Rust object.
210
211         /// Nearly everywhere, inner must be non-null, however in places where
212         /// the Rust equivalent takes an Option, it may be set to null to indicate None.
213         pub inner: *mut nativeRapidGossipSync,
214         /// Indicates that this is the only struct which contains the same pointer.
215
216         /// Rust functions which take ownership of an object provided via an argument require
217         /// this to be true and invalidate the object pointed to by inner.
218         pub is_owned: bool,
219 }
220
221 impl Drop for RapidGossipSync {
222         fn drop(&mut self) {
223                 if self.is_owned && !<*mut nativeRapidGossipSync>::is_null(self.inner) {
224                         let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
225                 }
226         }
227 }
228 /// Frees any resources used by the RapidGossipSync, if is_owned is set and inner is non-NULL.
229 #[no_mangle]
230 pub extern "C" fn RapidGossipSync_free(this_obj: RapidGossipSync) { }
231 #[allow(unused)]
232 /// Used only if an object of this type is returned as a trait impl by a method
233 pub(crate) extern "C" fn RapidGossipSync_free_void(this_ptr: *mut c_void) {
234         let _ = unsafe { Box::from_raw(this_ptr as *mut nativeRapidGossipSync) };
235 }
236 #[allow(unused)]
237 impl RapidGossipSync {
238         pub(crate) fn get_native_ref(&self) -> &'static nativeRapidGossipSync {
239                 unsafe { &*ObjOps::untweak_ptr(self.inner) }
240         }
241         pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeRapidGossipSync {
242                 unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
243         }
244         /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
245         pub(crate) fn take_inner(mut self) -> *mut nativeRapidGossipSync {
246                 assert!(self.is_owned);
247                 let ret = ObjOps::untweak_ptr(self.inner);
248                 self.inner = core::ptr::null_mut();
249                 ret
250         }
251 }
252 /// Instantiate a new [`RapidGossipSync`] instance.
253 #[must_use]
254 #[no_mangle]
255 pub extern "C" fn RapidGossipSync_new(network_graph: &crate::lightning::routing::gossip::NetworkGraph, mut logger: crate::lightning::util::logger::Logger) -> crate::lightning_rapid_gossip_sync::RapidGossipSync {
256         let mut ret = lightning_rapid_gossip_sync::RapidGossipSync::new(network_graph.get_native_ref(), logger);
257         crate::lightning_rapid_gossip_sync::RapidGossipSync { inner: ObjOps::heap_alloc(ret), is_owned: true }
258 }
259
260 /// Sync gossip data from a file.
261 /// Returns the last sync timestamp to be used the next time rapid sync data is queried.
262 ///
263 /// `network_graph`: The network graph to apply the updates to
264 ///
265 /// `sync_path`: Path to the file where the gossip update data is located
266 ///
267 #[must_use]
268 #[no_mangle]
269 pub extern "C" fn RapidGossipSync_sync_network_graph_with_file_path(this_arg: &crate::lightning_rapid_gossip_sync::RapidGossipSync, mut sync_path: crate::c_types::Str) -> crate::c_types::derived::CResult_u32GraphSyncErrorZ {
270         let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.sync_network_graph_with_file_path(sync_path.into_str());
271         let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { o }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning_rapid_gossip_sync::GraphSyncError::native_into(e) }).into() };
272         local_ret
273 }
274
275 /// Update network graph from binary data.
276 /// Returns the last sync timestamp to be used the next time rapid sync data is queried.
277 ///
278 /// `update_data`: `&[u8]` binary stream that comprises the update data
279 #[must_use]
280 #[no_mangle]
281 pub extern "C" fn RapidGossipSync_update_network_graph(this_arg: &crate::lightning_rapid_gossip_sync::RapidGossipSync, mut update_data: crate::c_types::u8slice) -> crate::c_types::derived::CResult_u32GraphSyncErrorZ {
282         let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.update_network_graph(update_data.to_slice());
283         let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { o }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning_rapid_gossip_sync::GraphSyncError::native_into(e) }).into() };
284         local_ret
285 }
286
287 /// Update network graph from binary data.
288 /// Returns the last sync timestamp to be used the next time rapid sync data is queried.
289 ///
290 /// `update_data`: `&[u8]` binary stream that comprises the update data
291 /// `current_time_unix`: `Option<u64>` optional current timestamp to verify data age
292 #[must_use]
293 #[no_mangle]
294 pub extern "C" fn RapidGossipSync_update_network_graph_no_std(this_arg: &crate::lightning_rapid_gossip_sync::RapidGossipSync, mut update_data: crate::c_types::u8slice, mut current_time_unix: crate::c_types::derived::COption_u64Z) -> crate::c_types::derived::CResult_u32GraphSyncErrorZ {
295         let mut local_current_time_unix = if current_time_unix.is_some() { Some( { current_time_unix.take() }) } else { None };
296         let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.update_network_graph_no_std(update_data.to_slice(), local_current_time_unix);
297         let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { o }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning_rapid_gossip_sync::GraphSyncError::native_into(e) }).into() };
298         local_ret
299 }
300
301 /// Returns whether a rapid gossip sync has completed at least once.
302 #[must_use]
303 #[no_mangle]
304 pub extern "C" fn RapidGossipSync_is_initial_sync_complete(this_arg: &crate::lightning_rapid_gossip_sync::RapidGossipSync) -> bool {
305         let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.is_initial_sync_complete();
306         ret
307 }
308