Merge pull request #684 from bmancini55/gossip_queries
[rust-lightning] / lightning-c-bindings / src / chain / chaininterface.rs
1 //! Traits and utility impls which allow other parts of rust-lightning to interact with the
2 //! blockchain.
3 //!
4 //! Includes traits for monitoring and receiving notifications of new blocks and block
5 //! disconnections, transaction broadcasting, and feerate information requests.
6
7 use std::ffi::c_void;
8 use bitcoin::hashes::Hash;
9 use crate::c_types::*;
10
11 /// Used to give chain error details upstream
12 #[must_use]
13 #[derive(Clone)]
14 #[repr(C)]
15 pub enum ChainError {
16         /// Client doesn't support UTXO lookup (but the chain hash matches our genesis block hash)
17         NotSupported,
18         /// Chain isn't the one watched
19         NotWatched,
20         /// Tx doesn't exist or is unconfirmed
21         UnknownTx,
22 }
23 use lightning::chain::chaininterface::ChainError as nativeChainError;
24 impl ChainError {
25         #[allow(unused)]
26         pub(crate) fn to_native(&self) -> nativeChainError {
27                 match self {
28                         ChainError::NotSupported => nativeChainError::NotSupported,
29                         ChainError::NotWatched => nativeChainError::NotWatched,
30                         ChainError::UnknownTx => nativeChainError::UnknownTx,
31                 }
32         }
33         #[allow(unused)]
34         pub(crate) fn into_native(self) -> nativeChainError {
35                 match self {
36                         ChainError::NotSupported => nativeChainError::NotSupported,
37                         ChainError::NotWatched => nativeChainError::NotWatched,
38                         ChainError::UnknownTx => nativeChainError::UnknownTx,
39                 }
40         }
41         #[allow(unused)]
42         pub(crate) fn from_native(native: &nativeChainError) -> Self {
43                 match native {
44                         nativeChainError::NotSupported => ChainError::NotSupported,
45                         nativeChainError::NotWatched => ChainError::NotWatched,
46                         nativeChainError::UnknownTx => ChainError::UnknownTx,
47                 }
48         }
49         #[allow(unused)]
50         pub(crate) fn native_into(native: nativeChainError) -> Self {
51                 match native {
52                         nativeChainError::NotSupported => ChainError::NotSupported,
53                         nativeChainError::NotWatched => ChainError::NotWatched,
54                         nativeChainError::UnknownTx => ChainError::UnknownTx,
55                 }
56         }
57 }
58 /// An interface to request notification of certain scripts as they appear the
59 /// chain.
60 ///
61 /// Note that all of the functions implemented here *must* be reentrant-safe (obviously - they're
62 /// called from inside the library in response to ChainListener events, P2P events, or timer
63 /// events).
64 #[repr(C)]
65 pub struct ChainWatchInterface {
66         pub this_arg: *mut c_void,
67         /// Provides a txid/random-scriptPubKey-in-the-tx which much be watched for.
68         pub install_watch_tx: extern "C" fn (this_arg: *const c_void, txid: *const [u8; 32], script_pub_key: crate::c_types::u8slice),
69         /// Provides an outpoint which must be watched for, providing any transactions which spend the
70         /// given outpoint.
71         pub install_watch_outpoint: extern "C" fn (this_arg: *const c_void, outpoint: crate::c_types::derived::C2Tuple_Txidu32Z, out_script: crate::c_types::u8slice),
72         /// Indicates that a listener needs to see all transactions.
73         pub watch_all_txn: extern "C" fn (this_arg: *const c_void),
74         /// Gets the script and value in satoshis for a given unspent transaction output given a
75         /// short_channel_id (aka unspent_tx_output_identier). For BTC/tBTC channels the top three
76         /// bytes are the block height, the next 3 the transaction index within the block, and the
77         /// final two the output within the transaction.
78         #[must_use]
79         pub get_chain_utxo: extern "C" fn (this_arg: *const c_void, genesis_hash: crate::c_types::ThirtyTwoBytes, unspent_tx_output_identifier: u64) -> crate::c_types::derived::CResult_C2Tuple_Scriptu64ZChainErrorZ,
80         /// Gets the list of transaction indices within a given block that the ChainWatchInterface is
81         /// watching for.
82         #[must_use]
83         pub filter_block: extern "C" fn (this_arg: *const c_void, block: crate::c_types::u8slice) -> crate::c_types::derived::CVec_usizeZ,
84         /// Returns a usize that changes when the ChainWatchInterface's watched data is modified.
85         /// Users of `filter_block` should pre-save a copy of `reentered`'s return value and use it to
86         /// determine whether they need to re-filter a given block.
87         #[must_use]
88         pub reentered: extern "C" fn (this_arg: *const c_void) -> usize,
89         pub free: Option<extern "C" fn(this_arg: *mut c_void)>,
90 }
91 unsafe impl Sync for ChainWatchInterface {}
92 unsafe impl Send for ChainWatchInterface {}
93
94 use lightning::chain::chaininterface::ChainWatchInterface as rustChainWatchInterface;
95 impl rustChainWatchInterface for ChainWatchInterface {
96         fn install_watch_tx(&self, txid: &bitcoin::hash_types::Txid, script_pub_key: &bitcoin::blockdata::script::Script) {
97                 (self.install_watch_tx)(self.this_arg, txid.as_inner(), crate::c_types::u8slice::from_slice(&script_pub_key[..]))
98         }
99         fn install_watch_outpoint(&self, outpoint: (bitcoin::hash_types::Txid, u32), out_script: &bitcoin::blockdata::script::Script) {
100                 let (mut orig_outpoint_0, mut orig_outpoint_1) = outpoint; let mut local_outpoint = (crate::c_types::ThirtyTwoBytes { data: orig_outpoint_0.into_inner() }, orig_outpoint_1).into();
101                 (self.install_watch_outpoint)(self.this_arg, local_outpoint, crate::c_types::u8slice::from_slice(&out_script[..]))
102         }
103         fn watch_all_txn(&self) {
104                 (self.watch_all_txn)(self.this_arg)
105         }
106         fn get_chain_utxo(&self, genesis_hash: bitcoin::hash_types::BlockHash, unspent_tx_output_identifier: u64) -> Result<(bitcoin::blockdata::script::Script, u64), lightning::chain::chaininterface::ChainError> {
107                 let mut ret = (self.get_chain_utxo)(self.this_arg, crate::c_types::ThirtyTwoBytes { data: genesis_hash.into_inner() }, unspent_tx_output_identifier);
108                 let mut local_ret = match ret.result_ok { true => Ok( { let (mut orig_ret_0_0, mut orig_ret_0_1) = (*unsafe { Box::from_raw(ret.contents.result.take_ptr()) }).to_rust(); let mut local_ret_0 = (::bitcoin::blockdata::script::Script::from(orig_ret_0_0.into_rust()), orig_ret_0_1); local_ret_0 }), false => Err( { (*unsafe { Box::from_raw(ret.contents.err.take_ptr()) }).into_native() })};
109                 local_ret
110         }
111         fn filter_block(&self, block: &bitcoin::blockdata::block::Block) -> Vec<usize> {
112                 let mut local_block = ::bitcoin::consensus::encode::serialize(block);
113                 let mut ret = (self.filter_block)(self.this_arg, crate::c_types::u8slice::from_slice(&local_block));
114                 let mut local_ret = Vec::new(); for mut item in ret.into_rust().drain(..) { local_ret.push( { item }); };
115                 local_ret
116         }
117         fn reentered(&self) -> usize {
118                 let mut ret = (self.reentered)(self.this_arg);
119                 ret
120         }
121 }
122
123 // We're essentially a pointer already, or at least a set of pointers, so allow us to be used
124 // directly as a Deref trait in higher-level structs:
125 impl std::ops::Deref for ChainWatchInterface {
126         type Target = Self;
127         fn deref(&self) -> &Self {
128                 self
129         }
130 }
131 /// Calls the free function if one is set
132 #[no_mangle]
133 pub extern "C" fn ChainWatchInterface_free(this_ptr: ChainWatchInterface) { }
134 impl Drop for ChainWatchInterface {
135         fn drop(&mut self) {
136                 if let Some(f) = self.free {
137                         f(self.this_arg);
138                 }
139         }
140 }
141 /// An interface to send a transaction to the Bitcoin network.
142 #[repr(C)]
143 pub struct BroadcasterInterface {
144         pub this_arg: *mut c_void,
145         /// Sends a transaction out to (hopefully) be mined.
146         pub broadcast_transaction: extern "C" fn (this_arg: *const c_void, tx: crate::c_types::Transaction),
147         pub free: Option<extern "C" fn(this_arg: *mut c_void)>,
148 }
149 unsafe impl Sync for BroadcasterInterface {}
150 unsafe impl Send for BroadcasterInterface {}
151
152 use lightning::chain::chaininterface::BroadcasterInterface as rustBroadcasterInterface;
153 impl rustBroadcasterInterface for BroadcasterInterface {
154         fn broadcast_transaction(&self, tx: &bitcoin::blockdata::transaction::Transaction) {
155                 let mut local_tx = ::bitcoin::consensus::encode::serialize(tx);
156                 (self.broadcast_transaction)(self.this_arg, crate::c_types::Transaction::from_slice(&local_tx))
157         }
158 }
159
160 // We're essentially a pointer already, or at least a set of pointers, so allow us to be used
161 // directly as a Deref trait in higher-level structs:
162 impl std::ops::Deref for BroadcasterInterface {
163         type Target = Self;
164         fn deref(&self) -> &Self {
165                 self
166         }
167 }
168 /// Calls the free function if one is set
169 #[no_mangle]
170 pub extern "C" fn BroadcasterInterface_free(this_ptr: BroadcasterInterface) { }
171 impl Drop for BroadcasterInterface {
172         fn drop(&mut self) {
173                 if let Some(f) = self.free {
174                         f(self.this_arg);
175                 }
176         }
177 }
178 /// A trait indicating a desire to listen for events from the chain
179 #[repr(C)]
180 pub struct ChainListener {
181         pub this_arg: *mut c_void,
182         /// Notifies a listener that a block was connected.
183         ///
184         /// The txn_matched array should be set to references to transactions which matched the
185         /// relevant installed watch outpoints/txn, or the full set of transactions in the block.
186         ///
187         /// Note that if txn_matched includes only matched transactions, and a new
188         /// transaction/outpoint is watched during a block_connected call, the block *must* be
189         /// re-scanned with the new transaction/outpoints and block_connected should be called
190         /// again with the same header and (at least) the new transactions.
191         ///
192         /// Note that if non-new transaction/outpoints are be registered during a call, a second call
193         /// *must not* happen.
194         ///
195         /// This also means those counting confirmations using block_connected callbacks should watch
196         /// for duplicate headers and not count them towards confirmations!
197         pub block_connected: extern "C" fn (this_arg: *const c_void, header: *const [u8; 80], height: u32, txn_matched: crate::c_types::derived::CVec_TransactionZ, indexes_of_txn_matched: crate::c_types::usizeslice),
198         /// Notifies a listener that a block was disconnected.
199         /// Unlike block_connected, this *must* never be called twice for the same disconnect event.
200         /// Height must be the one of the block which was disconnected (not new height of the best chain)
201         pub block_disconnected: extern "C" fn (this_arg: *const c_void, header: *const [u8; 80], disconnected_height: u32),
202         pub free: Option<extern "C" fn(this_arg: *mut c_void)>,
203 }
204 unsafe impl Sync for ChainListener {}
205 unsafe impl Send for ChainListener {}
206
207 use lightning::chain::chaininterface::ChainListener as rustChainListener;
208 impl rustChainListener for ChainListener {
209         fn block_connected(&self, header: &bitcoin::blockdata::block::BlockHeader, height: u32, txn_matched: &[&bitcoin::blockdata::transaction::Transaction], indexes_of_txn_matched: &[usize]) {
210                 let mut local_header = { let mut s = [0u8; 80]; s[..].copy_from_slice(&::bitcoin::consensus::encode::serialize(header)); s };
211                 let mut local_txn_matched = Vec::new(); for item in txn_matched.iter() { local_txn_matched.push( { let mut local_txn_matched_0 = ::bitcoin::consensus::encode::serialize(&**item); local_txn_matched_0.into() }); };
212                 let mut local_indexes_of_txn_matched = crate::c_types::usizeslice::from_slice(indexes_of_txn_matched);
213                 (self.block_connected)(self.this_arg, &local_header, height, local_txn_matched.into(), local_indexes_of_txn_matched)
214         }
215         fn block_disconnected(&self, header: &bitcoin::blockdata::block::BlockHeader, disconnected_height: u32) {
216                 let mut local_header = { let mut s = [0u8; 80]; s[..].copy_from_slice(&::bitcoin::consensus::encode::serialize(header)); s };
217                 (self.block_disconnected)(self.this_arg, &local_header, disconnected_height)
218         }
219 }
220
221 // We're essentially a pointer already, or at least a set of pointers, so allow us to be used
222 // directly as a Deref trait in higher-level structs:
223 impl std::ops::Deref for ChainListener {
224         type Target = Self;
225         fn deref(&self) -> &Self {
226                 self
227         }
228 }
229 /// Calls the free function if one is set
230 #[no_mangle]
231 pub extern "C" fn ChainListener_free(this_ptr: ChainListener) { }
232 impl Drop for ChainListener {
233         fn drop(&mut self) {
234                 if let Some(f) = self.free {
235                         f(self.this_arg);
236                 }
237         }
238 }
239 /// An enum that represents the speed at which we want a transaction to confirm used for feerate
240 /// estimation.
241 #[must_use]
242 #[derive(Clone)]
243 #[repr(C)]
244 pub enum ConfirmationTarget {
245         /// We are happy with this transaction confirming slowly when feerate drops some.
246         Background,
247         /// We'd like this transaction to confirm without major delay, but 12-18 blocks is fine.
248         Normal,
249         /// We'd like this transaction to confirm in the next few blocks.
250         HighPriority,
251 }
252 use lightning::chain::chaininterface::ConfirmationTarget as nativeConfirmationTarget;
253 impl ConfirmationTarget {
254         #[allow(unused)]
255         pub(crate) fn to_native(&self) -> nativeConfirmationTarget {
256                 match self {
257                         ConfirmationTarget::Background => nativeConfirmationTarget::Background,
258                         ConfirmationTarget::Normal => nativeConfirmationTarget::Normal,
259                         ConfirmationTarget::HighPriority => nativeConfirmationTarget::HighPriority,
260                 }
261         }
262         #[allow(unused)]
263         pub(crate) fn into_native(self) -> nativeConfirmationTarget {
264                 match self {
265                         ConfirmationTarget::Background => nativeConfirmationTarget::Background,
266                         ConfirmationTarget::Normal => nativeConfirmationTarget::Normal,
267                         ConfirmationTarget::HighPriority => nativeConfirmationTarget::HighPriority,
268                 }
269         }
270         #[allow(unused)]
271         pub(crate) fn from_native(native: &nativeConfirmationTarget) -> Self {
272                 match native {
273                         nativeConfirmationTarget::Background => ConfirmationTarget::Background,
274                         nativeConfirmationTarget::Normal => ConfirmationTarget::Normal,
275                         nativeConfirmationTarget::HighPriority => ConfirmationTarget::HighPriority,
276                 }
277         }
278         #[allow(unused)]
279         pub(crate) fn native_into(native: nativeConfirmationTarget) -> Self {
280                 match native {
281                         nativeConfirmationTarget::Background => ConfirmationTarget::Background,
282                         nativeConfirmationTarget::Normal => ConfirmationTarget::Normal,
283                         nativeConfirmationTarget::HighPriority => ConfirmationTarget::HighPriority,
284                 }
285         }
286 }
287 /// A trait which should be implemented to provide feerate information on a number of time
288 /// horizons.
289 ///
290 /// Note that all of the functions implemented here *must* be reentrant-safe (obviously - they're
291 /// called from inside the library in response to ChainListener events, P2P events, or timer
292 /// events).
293 #[repr(C)]
294 pub struct FeeEstimator {
295         pub this_arg: *mut c_void,
296         /// Gets estimated satoshis of fee required per 1000 Weight-Units.
297         ///
298         /// Must be no smaller than 253 (ie 1 satoshi-per-byte rounded up to ensure later round-downs
299         /// don't put us below 1 satoshi-per-byte).
300         ///
301         /// This translates to:
302         ///  * satoshis-per-byte * 250
303         ///  * ceil(satoshis-per-kbyte / 4)
304         #[must_use]
305         pub get_est_sat_per_1000_weight: extern "C" fn (this_arg: *const c_void, confirmation_target: crate::chain::chaininterface::ConfirmationTarget) -> u32,
306         pub free: Option<extern "C" fn(this_arg: *mut c_void)>,
307 }
308 unsafe impl Sync for FeeEstimator {}
309 unsafe impl Send for FeeEstimator {}
310
311 use lightning::chain::chaininterface::FeeEstimator as rustFeeEstimator;
312 impl rustFeeEstimator for FeeEstimator {
313         fn get_est_sat_per_1000_weight(&self, confirmation_target: lightning::chain::chaininterface::ConfirmationTarget) -> u32 {
314                 let mut ret = (self.get_est_sat_per_1000_weight)(self.this_arg, crate::chain::chaininterface::ConfirmationTarget::native_into(confirmation_target));
315                 ret
316         }
317 }
318
319 // We're essentially a pointer already, or at least a set of pointers, so allow us to be used
320 // directly as a Deref trait in higher-level structs:
321 impl std::ops::Deref for FeeEstimator {
322         type Target = Self;
323         fn deref(&self) -> &Self {
324                 self
325         }
326 }
327 /// Calls the free function if one is set
328 #[no_mangle]
329 pub extern "C" fn FeeEstimator_free(this_ptr: FeeEstimator) { }
330 impl Drop for FeeEstimator {
331         fn drop(&mut self) {
332                 if let Some(f) = self.free {
333                         f(self.this_arg);
334                 }
335         }
336 }
337
338 #[no_mangle]
339 pub static MIN_RELAY_FEE_SAT_PER_1000_WEIGHT: u64 = lightning::chain::chaininterface::MIN_RELAY_FEE_SAT_PER_1000_WEIGHT;
340
341 use lightning::chain::chaininterface::ChainWatchedUtil as nativeChainWatchedUtilImport;
342 type nativeChainWatchedUtil = nativeChainWatchedUtilImport;
343
344 /// Utility for tracking registered txn/outpoints and checking for matches
345 #[must_use]
346 #[repr(C)]
347 pub struct ChainWatchedUtil {
348         /// Nearly everyhwere, inner must be non-null, however in places where
349         /// the Rust equivalent takes an Option, it may be set to null to indicate None.
350         pub inner: *mut nativeChainWatchedUtil,
351         pub is_owned: bool,
352 }
353
354 impl Drop for ChainWatchedUtil {
355         fn drop(&mut self) {
356                 if self.is_owned && !self.inner.is_null() {
357                         let _ = unsafe { Box::from_raw(self.inner) };
358                 }
359         }
360 }
361 #[no_mangle]
362 pub extern "C" fn ChainWatchedUtil_free(this_ptr: ChainWatchedUtil) { }
363 #[allow(unused)]
364 /// Used only if an object of this type is returned as a trait impl by a method
365 extern "C" fn ChainWatchedUtil_free_void(this_ptr: *mut c_void) {
366         unsafe { let _ = Box::from_raw(this_ptr as *mut nativeChainWatchedUtil); }
367 }
368 #[allow(unused)]
369 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
370 impl ChainWatchedUtil {
371         pub(crate) fn take_ptr(mut self) -> *mut nativeChainWatchedUtil {
372                 assert!(self.is_owned);
373                 let ret = self.inner;
374                 self.inner = std::ptr::null_mut();
375                 ret
376         }
377 }
378 /// Constructs an empty (watches nothing) ChainWatchedUtil
379 #[must_use]
380 #[no_mangle]
381 pub extern "C" fn ChainWatchedUtil_new() -> ChainWatchedUtil {
382         let mut ret = lightning::chain::chaininterface::ChainWatchedUtil::new();
383         ChainWatchedUtil { inner: Box::into_raw(Box::new(ret)), is_owned: true }
384 }
385
386 /// Registers a tx for monitoring, returning true if it was a new tx and false if we'd already
387 /// been watching for it.
388 #[must_use]
389 #[no_mangle]
390 pub extern "C" fn ChainWatchedUtil_register_tx(this_arg: &mut ChainWatchedUtil, txid: *const [u8; 32], script_pub_key: crate::c_types::u8slice) -> bool {
391         let mut ret = unsafe { &mut (*(this_arg.inner as *mut nativeChainWatchedUtil)) }.register_tx(&::bitcoin::hash_types::Txid::from_slice(&unsafe { &*txid }[..]).unwrap(), &::bitcoin::blockdata::script::Script::from(Vec::from(script_pub_key.to_slice())));
392         ret
393 }
394
395 /// Registers an outpoint for monitoring, returning true if it was a new outpoint and false if
396 /// we'd already been watching for it
397 #[must_use]
398 #[no_mangle]
399 pub extern "C" fn ChainWatchedUtil_register_outpoint(this_arg: &mut ChainWatchedUtil, mut outpoint: crate::c_types::derived::C2Tuple_Txidu32Z, _script_pub_key: crate::c_types::u8slice) -> bool {
400         let (mut orig_outpoint_0, mut orig_outpoint_1) = outpoint.to_rust(); let mut local_outpoint = (::bitcoin::hash_types::Txid::from_slice(&orig_outpoint_0.data[..]).unwrap(), orig_outpoint_1);
401         let mut ret = unsafe { &mut (*(this_arg.inner as *mut nativeChainWatchedUtil)) }.register_outpoint(local_outpoint, &::bitcoin::blockdata::script::Script::from(Vec::from(_script_pub_key.to_slice())));
402         ret
403 }
404
405 /// Sets us to match all transactions, returning true if this is a new setting and false if
406 /// we'd already been set to match everything.
407 #[must_use]
408 #[no_mangle]
409 pub extern "C" fn ChainWatchedUtil_watch_all(this_arg: &mut ChainWatchedUtil) -> bool {
410         let mut ret = unsafe { &mut (*(this_arg.inner as *mut nativeChainWatchedUtil)) }.watch_all();
411         ret
412 }
413
414 /// Checks if a given transaction matches the current filter.
415 #[must_use]
416 #[no_mangle]
417 pub extern "C" fn ChainWatchedUtil_does_match_tx(this_arg: &ChainWatchedUtil, tx: crate::c_types::Transaction) -> bool {
418         let mut ret = unsafe { &*this_arg.inner }.does_match_tx(&tx.into_bitcoin());
419         ret
420 }
421
422
423 use lightning::chain::chaininterface::BlockNotifier as nativeBlockNotifierImport;
424 type nativeBlockNotifier = nativeBlockNotifierImport<'static, crate::chain::chaininterface::ChainListener, crate::chain::chaininterface::ChainWatchInterface>;
425
426 /// Utility for notifying listeners about new blocks, and handling block rescans if new watch
427 /// data is registered.
428 ///
429 /// Rather than using a plain BlockNotifier, it is preferable to use either a BlockNotifierArc
430 /// or a BlockNotifierRef for conciseness. See their documentation for more details, but essentially
431 /// you should default to using a BlockNotifierRef, and use a BlockNotifierArc instead when you
432 /// require ChainListeners with static lifetimes, such as when you're using lightning-net-tokio.
433 #[must_use]
434 #[repr(C)]
435 pub struct BlockNotifier {
436         /// Nearly everyhwere, inner must be non-null, however in places where
437         /// the Rust equivalent takes an Option, it may be set to null to indicate None.
438         pub inner: *mut nativeBlockNotifier,
439         pub is_owned: bool,
440 }
441
442 impl Drop for BlockNotifier {
443         fn drop(&mut self) {
444                 if self.is_owned && !self.inner.is_null() {
445                         let _ = unsafe { Box::from_raw(self.inner) };
446                 }
447         }
448 }
449 #[no_mangle]
450 pub extern "C" fn BlockNotifier_free(this_ptr: BlockNotifier) { }
451 #[allow(unused)]
452 /// Used only if an object of this type is returned as a trait impl by a method
453 extern "C" fn BlockNotifier_free_void(this_ptr: *mut c_void) {
454         unsafe { let _ = Box::from_raw(this_ptr as *mut nativeBlockNotifier); }
455 }
456 #[allow(unused)]
457 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
458 impl BlockNotifier {
459         pub(crate) fn take_ptr(mut self) -> *mut nativeBlockNotifier {
460                 assert!(self.is_owned);
461                 let ret = self.inner;
462                 self.inner = std::ptr::null_mut();
463                 ret
464         }
465 }
466 /// Constructs a new BlockNotifier without any listeners.
467 #[must_use]
468 #[no_mangle]
469 pub extern "C" fn BlockNotifier_new(mut chain_monitor: crate::chain::chaininterface::ChainWatchInterface) -> crate::chain::chaininterface::BlockNotifier {
470         let mut ret = lightning::chain::chaininterface::BlockNotifier::new(chain_monitor);
471         crate::chain::chaininterface::BlockNotifier { inner: Box::into_raw(Box::new(ret)), is_owned: true }
472 }
473
474 /// Register the given listener to receive events.
475 #[no_mangle]
476 pub extern "C" fn BlockNotifier_register_listener(this_arg: &BlockNotifier, mut listener: crate::chain::chaininterface::ChainListener) {
477         unsafe { &*this_arg.inner }.register_listener(listener)
478 }
479
480 /// Notify listeners that a block was connected given a full, unfiltered block.
481 ///
482 /// Handles re-scanning the block and calling block_connected again if listeners register new
483 /// watch data during the callbacks for you (see ChainListener::block_connected for more info).
484 #[no_mangle]
485 pub extern "C" fn BlockNotifier_block_connected(this_arg: &BlockNotifier, block: crate::c_types::u8slice, mut height: u32) {
486         unsafe { &*this_arg.inner }.block_connected(&::bitcoin::consensus::encode::deserialize(block.to_slice()).unwrap(), height)
487 }
488
489 /// Notify listeners that a block was connected, given pre-filtered list of transactions in the
490 /// block which matched the filter (probably using does_match_tx).
491 ///
492 /// Returns true if notified listeners registered additional watch data (implying that the
493 /// block must be re-scanned and this function called again prior to further block_connected
494 /// calls, see ChainListener::block_connected for more info).
495 #[must_use]
496 #[no_mangle]
497 pub extern "C" fn BlockNotifier_block_connected_checked(this_arg: &BlockNotifier, header: *const [u8; 80], mut height: u32, mut txn_matched: crate::c_types::derived::CVec_TransactionZ, mut indexes_of_txn_matched: crate::c_types::usizeslice) -> bool {
498         let mut local_txn_matched = Vec::new(); for mut item in txn_matched.into_rust().drain(..) { local_txn_matched.push( { ::bitcoin::consensus::encode::deserialize(&item.into_rust()[..]).unwrap() }); };
499         let mut ret = unsafe { &*this_arg.inner }.block_connected_checked(&::bitcoin::consensus::encode::deserialize(unsafe { &*header }).unwrap(), height, &local_txn_matched.iter().collect::<Vec<_>>()[..], indexes_of_txn_matched.to_slice());
500         ret
501 }
502
503 /// Notify listeners that a block was disconnected.
504 #[no_mangle]
505 pub extern "C" fn BlockNotifier_block_disconnected(this_arg: &BlockNotifier, header: *const [u8; 80], mut disconnected_height: u32) {
506         unsafe { &*this_arg.inner }.block_disconnected(&::bitcoin::consensus::encode::deserialize(unsafe { &*header }).unwrap(), disconnected_height)
507 }
508
509
510 use lightning::chain::chaininterface::ChainWatchInterfaceUtil as nativeChainWatchInterfaceUtilImport;
511 type nativeChainWatchInterfaceUtil = nativeChainWatchInterfaceUtilImport;
512
513 /// Utility to capture some common parts of ChainWatchInterface implementors.
514 ///
515 /// Keeping a local copy of this in a ChainWatchInterface implementor is likely useful.
516 #[must_use]
517 #[repr(C)]
518 pub struct ChainWatchInterfaceUtil {
519         /// Nearly everyhwere, inner must be non-null, however in places where
520         /// the Rust equivalent takes an Option, it may be set to null to indicate None.
521         pub inner: *mut nativeChainWatchInterfaceUtil,
522         pub is_owned: bool,
523 }
524
525 impl Drop for ChainWatchInterfaceUtil {
526         fn drop(&mut self) {
527                 if self.is_owned && !self.inner.is_null() {
528                         let _ = unsafe { Box::from_raw(self.inner) };
529                 }
530         }
531 }
532 #[no_mangle]
533 pub extern "C" fn ChainWatchInterfaceUtil_free(this_ptr: ChainWatchInterfaceUtil) { }
534 #[allow(unused)]
535 /// Used only if an object of this type is returned as a trait impl by a method
536 extern "C" fn ChainWatchInterfaceUtil_free_void(this_ptr: *mut c_void) {
537         unsafe { let _ = Box::from_raw(this_ptr as *mut nativeChainWatchInterfaceUtil); }
538 }
539 #[allow(unused)]
540 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
541 impl ChainWatchInterfaceUtil {
542         pub(crate) fn take_ptr(mut self) -> *mut nativeChainWatchInterfaceUtil {
543                 assert!(self.is_owned);
544                 let ret = self.inner;
545                 self.inner = std::ptr::null_mut();
546                 ret
547         }
548 }
549 #[no_mangle]
550 pub extern "C" fn ChainWatchInterfaceUtil_as_ChainWatchInterface(this_arg: *const ChainWatchInterfaceUtil) -> crate::chain::chaininterface::ChainWatchInterface {
551         crate::chain::chaininterface::ChainWatchInterface {
552                 this_arg: unsafe { (*this_arg).inner as *mut c_void },
553                 free: None,
554                 install_watch_tx: ChainWatchInterfaceUtil_ChainWatchInterface_install_watch_tx,
555                 install_watch_outpoint: ChainWatchInterfaceUtil_ChainWatchInterface_install_watch_outpoint,
556                 watch_all_txn: ChainWatchInterfaceUtil_ChainWatchInterface_watch_all_txn,
557                 get_chain_utxo: ChainWatchInterfaceUtil_ChainWatchInterface_get_chain_utxo,
558                 filter_block: ChainWatchInterfaceUtil_ChainWatchInterface_filter_block,
559                 reentered: ChainWatchInterfaceUtil_ChainWatchInterface_reentered,
560         }
561 }
562 use lightning::chain::chaininterface::ChainWatchInterface as ChainWatchInterfaceTraitImport;
563 extern "C" fn ChainWatchInterfaceUtil_ChainWatchInterface_install_watch_tx(this_arg: *const c_void, txid: *const [u8; 32], script_pub_key: crate::c_types::u8slice) {
564         unsafe { &mut *(this_arg as *mut nativeChainWatchInterfaceUtil) }.install_watch_tx(&::bitcoin::hash_types::Txid::from_slice(&unsafe { &*txid }[..]).unwrap(), &::bitcoin::blockdata::script::Script::from(Vec::from(script_pub_key.to_slice())))
565 }
566 extern "C" fn ChainWatchInterfaceUtil_ChainWatchInterface_install_watch_outpoint(this_arg: *const c_void, mut outpoint: crate::c_types::derived::C2Tuple_Txidu32Z, out_script: crate::c_types::u8slice) {
567         let (mut orig_outpoint_0, mut orig_outpoint_1) = outpoint.to_rust(); let mut local_outpoint = (::bitcoin::hash_types::Txid::from_slice(&orig_outpoint_0.data[..]).unwrap(), orig_outpoint_1);
568         unsafe { &mut *(this_arg as *mut nativeChainWatchInterfaceUtil) }.install_watch_outpoint(local_outpoint, &::bitcoin::blockdata::script::Script::from(Vec::from(out_script.to_slice())))
569 }
570 extern "C" fn ChainWatchInterfaceUtil_ChainWatchInterface_watch_all_txn(this_arg: *const c_void) {
571         unsafe { &mut *(this_arg as *mut nativeChainWatchInterfaceUtil) }.watch_all_txn()
572 }
573 #[must_use]
574 extern "C" fn ChainWatchInterfaceUtil_ChainWatchInterface_get_chain_utxo(this_arg: *const c_void, mut genesis_hash: crate::c_types::ThirtyTwoBytes, mut _unspent_tx_output_identifier: u64) -> crate::c_types::derived::CResult_C2Tuple_Scriptu64ZChainErrorZ {
575         let mut ret = unsafe { &mut *(this_arg as *mut nativeChainWatchInterfaceUtil) }.get_chain_utxo(::bitcoin::hash_types::BlockHash::from_slice(&genesis_hash.data[..]).unwrap(), _unspent_tx_output_identifier);
576         let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { let (mut orig_ret_0_0, mut orig_ret_0_1) = o; let mut local_ret_0 = (orig_ret_0_0.into_bytes().into(), orig_ret_0_1).into(); local_ret_0 }), Err(mut e) => crate::c_types::CResultTempl::err( { crate::chain::chaininterface::ChainError::native_into(e) }) };
577         local_ret
578 }
579 #[must_use]
580 extern "C" fn ChainWatchInterfaceUtil_ChainWatchInterface_filter_block(this_arg: *const c_void, block: crate::c_types::u8slice) -> crate::c_types::derived::CVec_usizeZ {
581         let mut ret = unsafe { &mut *(this_arg as *mut nativeChainWatchInterfaceUtil) }.filter_block(&::bitcoin::consensus::encode::deserialize(block.to_slice()).unwrap());
582         let mut local_ret = Vec::new(); for item in ret.drain(..) { local_ret.push( { item }); };
583         local_ret.into()
584 }
585 #[must_use]
586 extern "C" fn ChainWatchInterfaceUtil_ChainWatchInterface_reentered(this_arg: *const c_void) -> usize {
587         let mut ret = unsafe { &mut *(this_arg as *mut nativeChainWatchInterfaceUtil) }.reentered();
588         ret
589 }
590
591 /// Creates a new ChainWatchInterfaceUtil for the given network
592 #[must_use]
593 #[no_mangle]
594 pub extern "C" fn ChainWatchInterfaceUtil_new(mut network: crate::bitcoin::network::Network) -> crate::chain::chaininterface::ChainWatchInterfaceUtil {
595         let mut ret = lightning::chain::chaininterface::ChainWatchInterfaceUtil::new(network.into_bitcoin());
596         crate::chain::chaininterface::ChainWatchInterfaceUtil { inner: Box::into_raw(Box::new(ret)), is_owned: true }
597 }
598
599 /// Checks if a given transaction matches the current filter.
600 #[must_use]
601 #[no_mangle]
602 pub extern "C" fn ChainWatchInterfaceUtil_does_match_tx(this_arg: &ChainWatchInterfaceUtil, tx: crate::c_types::Transaction) -> bool {
603         let mut ret = unsafe { &*this_arg.inner }.does_match_tx(&tx.into_bitcoin());
604         ret
605 }
606