b4c2d51c082297506649db873b80bd6b8f4dbebd
[ldk-c-bindings] / lightning-c-bindings / src / lightning_rapid_gossip_sync / mod.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 core::ffi::c_void;
63 use core::convert::Infallible;
64 use bitcoin::hashes::Hash;
65 use crate::c_types::*;
66 #[cfg(feature="no-std")]
67 use alloc::{vec::Vec, boxed::Box};
68
69 pub mod error;
70 mod processing {
71
72 use alloc::str::FromStr;
73 use core::ffi::c_void;
74 use core::convert::Infallible;
75 use bitcoin::hashes::Hash;
76 use crate::c_types::*;
77 #[cfg(feature="no-std")]
78 use alloc::{vec::Vec, boxed::Box};
79
80 }
81
82 use lightning_rapid_gossip_sync::RapidGossipSync as nativeRapidGossipSyncImport;
83 pub(crate) type nativeRapidGossipSync = nativeRapidGossipSyncImport<&'static lightning::routing::gossip::NetworkGraph<crate::lightning::util::logger::Logger>, crate::lightning::util::logger::Logger>;
84
85 /// The main Rapid Gossip Sync object.
86 ///
87 /// See [crate-level documentation] for usage.
88 ///
89 /// [crate-level documentation]: crate
90 #[must_use]
91 #[repr(C)]
92 pub struct RapidGossipSync {
93         /// A pointer to the opaque Rust object.
94
95         /// Nearly everywhere, inner must be non-null, however in places where
96         /// the Rust equivalent takes an Option, it may be set to null to indicate None.
97         pub inner: *mut nativeRapidGossipSync,
98         /// Indicates that this is the only struct which contains the same pointer.
99
100         /// Rust functions which take ownership of an object provided via an argument require
101         /// this to be true and invalidate the object pointed to by inner.
102         pub is_owned: bool,
103 }
104
105 impl Drop for RapidGossipSync {
106         fn drop(&mut self) {
107                 if self.is_owned && !<*mut nativeRapidGossipSync>::is_null(self.inner) {
108                         let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
109                 }
110         }
111 }
112 /// Frees any resources used by the RapidGossipSync, if is_owned is set and inner is non-NULL.
113 #[no_mangle]
114 pub extern "C" fn RapidGossipSync_free(this_obj: RapidGossipSync) { }
115 #[allow(unused)]
116 /// Used only if an object of this type is returned as a trait impl by a method
117 pub(crate) extern "C" fn RapidGossipSync_free_void(this_ptr: *mut c_void) {
118         let _ = unsafe { Box::from_raw(this_ptr as *mut nativeRapidGossipSync) };
119 }
120 #[allow(unused)]
121 impl RapidGossipSync {
122         pub(crate) fn get_native_ref(&self) -> &'static nativeRapidGossipSync {
123                 unsafe { &*ObjOps::untweak_ptr(self.inner) }
124         }
125         pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeRapidGossipSync {
126                 unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
127         }
128         /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
129         pub(crate) fn take_inner(mut self) -> *mut nativeRapidGossipSync {
130                 assert!(self.is_owned);
131                 let ret = ObjOps::untweak_ptr(self.inner);
132                 self.inner = core::ptr::null_mut();
133                 ret
134         }
135 }
136 /// Instantiate a new [`RapidGossipSync`] instance.
137 #[must_use]
138 #[no_mangle]
139 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 {
140         let mut ret = lightning_rapid_gossip_sync::RapidGossipSync::new(network_graph.get_native_ref(), logger);
141         crate::lightning_rapid_gossip_sync::RapidGossipSync { inner: ObjOps::heap_alloc(ret), is_owned: true }
142 }
143
144 /// Sync gossip data from a file.
145 /// Returns the last sync timestamp to be used the next time rapid sync data is queried.
146 ///
147 /// `network_graph`: The network graph to apply the updates to
148 ///
149 /// `sync_path`: Path to the file where the gossip update data is located
150 ///
151 #[must_use]
152 #[no_mangle]
153 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 {
154         let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.sync_network_graph_with_file_path(sync_path.into_str());
155         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::error::GraphSyncError::native_into(e) }).into() };
156         local_ret
157 }
158
159 /// Update network graph from binary data.
160 /// Returns the last sync timestamp to be used the next time rapid sync data is queried.
161 ///
162 /// `update_data`: `&[u8]` binary stream that comprises the update data
163 #[must_use]
164 #[no_mangle]
165 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 {
166         let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.update_network_graph(update_data.to_slice());
167         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::error::GraphSyncError::native_into(e) }).into() };
168         local_ret
169 }
170
171 /// Update network graph from binary data.
172 /// Returns the last sync timestamp to be used the next time rapid sync data is queried.
173 ///
174 /// `update_data`: `&[u8]` binary stream that comprises the update data
175 /// `current_time_unix`: `Option<u64>` optional current timestamp to verify data age
176 #[must_use]
177 #[no_mangle]
178 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 {
179         let mut local_current_time_unix = if current_time_unix.is_some() { Some( { current_time_unix.take() }) } else { None };
180         let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.update_network_graph_no_std(update_data.to_slice(), local_current_time_unix);
181         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::error::GraphSyncError::native_into(e) }).into() };
182         local_ret
183 }
184
185 /// Returns whether a rapid gossip sync has completed at least once.
186 #[must_use]
187 #[no_mangle]
188 pub extern "C" fn RapidGossipSync_is_initial_sync_complete(this_arg: &crate::lightning_rapid_gossip_sync::RapidGossipSync) -> bool {
189         let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.is_initial_sync_complete();
190         ret
191 }
192