1 // This file is Copyright its original authors, visible in version control
2 // history and in the source files from which this was generated.
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.
9 //! This crate exposes client functionality to rapidly sync gossip data, aimed primarily at mobile
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).
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.
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.
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:
31 //! curl -o rapid_sync.lngossip https://rapidsync.lightningdevkit.org/snapshot/<last_sync_timestamp>
33 //! Note that the first ever rapid sync should use `0` for `last_sync_timestamp`.
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`]:
40 //! use bitcoin::blockdata::constants::genesis_block;
41 //! use bitcoin::Network;
42 //! use lightning::routing::gossip::NetworkGraph;
43 //! use lightning_rapid_gossip_sync::RapidGossipSync;
45 //! # use lightning::util::logger::{Logger, Record};
46 //! # struct FakeLogger {}
47 //! # impl Logger for FakeLogger {
48 //! # fn log(&self, record: Record) { }
50 //! # let logger = FakeLogger {};
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));
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};
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};
82 /// All-encompassing standard error type that processing can return
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
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
94 crate::lightning::ln::msgs::LightningError),
96 use lightning_rapid_gossip_sync::GraphSyncError as GraphSyncErrorImport;
97 pub(crate) type nativeGraphSyncError = GraphSyncErrorImport;
101 pub(crate) fn to_native(&self) -> nativeGraphSyncError {
103 GraphSyncError::DecodeError (ref a, ) => {
104 let mut a_nonref = Clone::clone(a);
105 nativeGraphSyncError::DecodeError (
106 a_nonref.into_native(),
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()) },
118 pub(crate) fn into_native(self) -> nativeGraphSyncError {
120 GraphSyncError::DecodeError (mut a, ) => {
121 nativeGraphSyncError::DecodeError (
125 GraphSyncError::LightningError (mut a, ) => {
126 nativeGraphSyncError::LightningError (
127 *unsafe { Box::from_raw(a.take_inner()) },
133 pub(crate) fn from_native(native: &GraphSyncErrorImport) -> Self {
134 let native = unsafe { &*(native as *const _ as *const c_void as *const nativeGraphSyncError) };
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),
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 },
151 pub(crate) fn native_into(native: nativeGraphSyncError) -> Self {
153 nativeGraphSyncError::DecodeError (mut a, ) => {
154 GraphSyncError::DecodeError (
155 crate::lightning::ln::msgs::DecodeError::native_into(a),
158 nativeGraphSyncError::LightningError (mut a, ) => {
159 GraphSyncError::LightningError (
160 crate::lightning::ln::msgs::LightningError { inner: ObjOps::heap_alloc(a), is_owned: true },
166 /// Frees any resources used by the GraphSyncError
168 pub extern "C" fn GraphSyncError_free(this_ptr: GraphSyncError) { }
169 /// Creates a copy of the GraphSyncError
171 pub extern "C" fn GraphSyncError_clone(orig: &GraphSyncError) -> GraphSyncError {
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
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) };
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, )
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, )
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()}
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, >;
201 /// The main Rapid Gossip Sync object.
203 /// See [crate-level documentation] for usage.
205 /// [crate-level documentation]: crate
208 pub struct RapidGossipSync {
209 /// A pointer to the opaque Rust object.
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.
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.
221 impl Drop for RapidGossipSync {
223 if self.is_owned && !<*mut nativeRapidGossipSync>::is_null(self.inner) {
224 let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
228 /// Frees any resources used by the RapidGossipSync, if is_owned is set and inner is non-NULL.
230 pub extern "C" fn RapidGossipSync_free(this_obj: RapidGossipSync) { }
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) };
237 impl RapidGossipSync {
238 pub(crate) fn get_native_ref(&self) -> &'static nativeRapidGossipSync {
239 unsafe { &*ObjOps::untweak_ptr(self.inner) }
241 pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeRapidGossipSync {
242 unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
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();
252 /// Instantiate a new [`RapidGossipSync`] instance.
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 }
260 /// Sync gossip data from a file.
261 /// Returns the last sync timestamp to be used the next time rapid sync data is queried.
263 /// `network_graph`: The network graph to apply the updates to
265 /// `sync_path`: Path to the file where the gossip update data is located
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() };
275 /// Update network graph from binary data.
276 /// Returns the last sync timestamp to be used the next time rapid sync data is queried.
278 /// `update_data`: `&[u8]` binary stream that comprises the update data
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() };
287 /// Update network graph from binary data.
288 /// Returns the last sync timestamp to be used the next time rapid sync data is queried.
290 /// `update_data`: `&[u8]` binary stream that comprises the update data
291 /// `current_time_unix`: `Option<u64>` optional current timestamp to verify data age
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() };
301 /// Returns whether a rapid gossip sync has completed at least once.
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();