bip157 0.5.0

A Bitcoin light-client according to the BIP-157/BIP-158 specifications
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
//! This crate is a conservative, private, and vetted Bitcoin client built in accordance
//! with the [BIP157](https://github.com/bitcoin/bips/blob/master/bip-0157.mediawiki) and [BIP158](https://github.com/bitcoin/bips/blob/master/bip-0158.mediawiki)
//! standards. _Conservative_, as in this crate makes very little assumptions about the underlying memory requirements of the
//! device running the software. _Private_, as in the Bitcoin nodes that serve this client data do not know what transactions the
//! client is querying for, only the entire Bitcoin block. _Vetted_, as in the dependencies of the core library are meant to remain limited,
//! rigorously tested, and absolutely necessary.
//!
//! # Example usage
//!
//! ```no_run
//! use bip157::{Builder, Event, Client, Network, BlockHash};
//!
//! #[tokio::main]
//! async fn main() {
//!     // Add third-party logging
//!     let subscriber = tracing_subscriber::FmtSubscriber::new();
//!     tracing::subscriber::set_global_default(subscriber).unwrap();
//!     // Create a new node builder
//!     let builder = Builder::new(Network::Signet);
//!     // Add node preferences and build the node/client
//!     let (node, client) = builder
//!         // The number of connections we would like to maintain
//!         .required_peers(2)
//!         .build();
//!     // Run the node and wait for the sync message;
//!     tokio::task::spawn(async move { node.run().await });
//!     // Split the client into components that send messages and listen to messages
//!     let Client { requester, info_rx: _, warn_rx: _, mut event_rx } = client;
//!     loop {
//!         if let Some(event) = event_rx.recv().await {
//!             match event {
//!                 Event::FiltersSynced(_) => {
//!                     tracing::info!("Sync complete!");
//!                     break;
//!                 },
//!                 _ => (),
//!             }
//!         }
//!     }
//!     requester.shutdown();
//! }
//! ```

#![warn(missing_docs)]
pub mod chain;

use crate::network::{ConnectionType, PeerTimeoutConfig};

mod network;

mod broadcaster;
/// Convenient way to build a compact filters node.
pub mod builder;
/// Structures to communicate with a node.
pub mod client;
/// Errors associated with a node.
pub mod error;
/// Messages the node may send a client.
pub mod messages;
/// The structure that communicates with the Bitcoin P2P network and collects data.
pub mod node;

use bitcoin::OutPoint;
use chain::Filter;

use std::net::{IpAddr, Ipv4Addr, SocketAddr};
use std::path::PathBuf;

// Re-exports
#[doc(inline)]
pub use chain::checkpoints::HeaderCheckpoint;

#[doc(inline)]
pub use tokio::sync::mpsc::Receiver;
use tokio::sync::mpsc::Sender;

#[doc(inline)]
pub use tokio::sync::mpsc::UnboundedReceiver;
use tokio::sync::mpsc::UnboundedSender;

#[doc(inline)]
pub use {
    crate::builder::Builder,
    crate::chain::ChainState,
    crate::client::{Client, Requester},
    crate::error::{ClientError, NodeError},
    crate::messages::{Event, Info, Progress, RejectPayload, SyncUpdate, Warning},
    crate::node::Node,
};

#[doc(inline)]
pub use bitcoin::{
    bip158::BlockFilter, block::Header, p2p::address::AddrV2, p2p::message_network::RejectReason,
    p2p::ServiceFlags, Address, Block, BlockHash, FeeRate, Network, ScriptBuf, Transaction, Wtxid,
};

pub extern crate tokio;

/// A Bitcoin [`Block`] with associated height.
#[derive(Debug, Clone)]
pub struct IndexedBlock {
    /// The height or index in the chain.
    pub height: u32,
    /// The Bitcoin block with some matching script.
    pub block: Block,
}

impl IndexedBlock {
    pub(crate) fn new(height: u32, block: Block) -> Self {
        Self { height, block }
    }
}

/// The type of filter to make a request for.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord)]
#[non_exhaustive]
pub enum FilterType {
    #[default]
    /// A golomb coded compact sketch based on siphash. Contains all spendable script types.
    Basic,
}

#[derive(Debug, Clone, Copy, Default)]
enum BlockType {
    #[default]
    Legacy,
    Witness,
}

impl From<FilterType> for u8 {
    fn from(value: FilterType) -> Self {
        match value {
            FilterType::Basic => 0x00,
        }
    }
}

/// A compact block filter with associated height.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct IndexedFilter {
    height: u32,
    filter: Filter,
}

impl IndexedFilter {
    fn new(height: u32, filter: Filter) -> Self {
        Self { height, filter }
    }

    /// The height in the chain.
    pub fn height(&self) -> u32 {
        self.height
    }

    /// Return the [`BlockHash`] associated with this filer
    pub fn block_hash(&self) -> BlockHash {
        self.filter.block_hash()
    }

    /// Does the filter contain a positive match for any of the provided scripts
    pub fn contains_any<'a>(&'a self, scripts: impl Iterator<Item = &'a ScriptBuf>) -> bool {
        self.filter.contains_any(scripts)
    }

    /// Consume the index and get underlying block filter.
    pub fn block_filter(self) -> BlockFilter {
        self.filter.into_filter()
    }

    /// Consume the filter and get the raw bytes
    pub fn into_contents(self) -> Vec<u8> {
        self.filter.contents()
    }
}

impl std::cmp::PartialOrd for IndexedFilter {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        Some(self.cmp(other))
    }
}

impl std::cmp::Ord for IndexedFilter {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        self.height.cmp(&other.height)
    }
}

#[derive(Debug, Clone)]
enum TrustedPeerInner {
    Addr(AddrV2),
    Hostname(String),
}

impl From<AddrV2> for TrustedPeerInner {
    fn from(addr: AddrV2) -> Self {
        Self::Addr(addr)
    }
}

/// A peer on the Bitcoin P2P network
///
/// # Building peers
///
/// ```rust
/// use std::net::{IpAddr, Ipv4Addr};
/// use bip157::{TrustedPeer, ServiceFlags, AddrV2};
///
/// let local_host = IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0));
/// let mut trusted = TrustedPeer::from_ip(local_host);
/// // Optionally set the known services of the peer later.
/// trusted.set_services(ServiceFlags::P2P_V2);
///
/// let local_host = Ipv4Addr::new(0, 0, 0, 0);
/// // Or construct a trusted peer directly.
/// let trusted = TrustedPeer::new(AddrV2::Ipv4(local_host), None, ServiceFlags::P2P_V2);
///
/// // Or implicitly with `into`
/// let local_host = IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0));
/// let trusted: TrustedPeer = (local_host, None).into();
///
/// // Or from a hostname — resolution happens at connection time.
/// let trusted = TrustedPeer::from_hostname("bitcoind.svc.local", 8333);
/// ```
#[derive(Debug, Clone)]
pub struct TrustedPeer {
    // The address or hostname of the remote node to connect to.
    address: TrustedPeerInner,
    // The port to establish a TCP connection. If none is provided, the typical Bitcoin Core port is used as the default.
    port: Option<u16>,
    // The services this peer is known to offer before starting the node.
    known_services: ServiceFlags,
}

impl TrustedPeer {
    /// Create a new trusted peer.
    pub fn new(address: impl Into<AddrV2>, port: Option<u16>, services: ServiceFlags) -> Self {
        Self {
            address: TrustedPeerInner::Addr(address.into()),
            port,
            known_services: services,
        }
    }

    /// Create a new trusted peer using the default port for the network.
    pub fn from_ip(ip_addr: impl Into<IpAddr>) -> Self {
        let address = match ip_addr.into() {
            IpAddr::V4(ip) => AddrV2::Ipv4(ip),
            IpAddr::V6(ip) => AddrV2::Ipv6(ip),
        };
        Self {
            address: TrustedPeerInner::Addr(address),
            port: None,
            known_services: ServiceFlags::NONE,
        }
    }

    /// Create a new peer from a known address and port.
    pub fn from_socket_addr(socket_addr: impl Into<SocketAddr>) -> Self {
        let socket_addr: SocketAddr = socket_addr.into();
        let address = match socket_addr {
            SocketAddr::V4(ip) => AddrV2::Ipv4(*ip.ip()),
            SocketAddr::V6(ip) => AddrV2::Ipv6(*ip.ip()),
        };
        Self {
            address: TrustedPeerInner::Addr(address),
            port: Some(socket_addr.port()),
            known_services: ServiceFlags::NONE,
        }
    }

    /// Create a new trusted peer from a DNS hostname.
    ///
    /// The hostname is stored as-is and resolved to an IP address at the
    /// time a connection is attempted, via [`tokio::net::lookup_host`]. If
    /// resolution fails or yields no addresses, the peer is skipped and
    /// the next configured peer is tried.
    pub fn from_hostname(hostname: impl Into<String>, port: u16) -> Self {
        Self {
            address: TrustedPeerInner::Hostname(hostname.into()),
            port: Some(port),
            known_services: ServiceFlags::NONE,
        }
    }

    /// A recommended port to connect to, if there is one.
    pub fn port(&self) -> Option<u16> {
        self.port
    }

    /// The services this peer is known to offer.
    pub fn services(&self) -> ServiceFlags {
        self.known_services
    }

    /// Set the known services for this trusted peer.
    pub fn set_services(&mut self, services: ServiceFlags) {
        self.known_services = services;
    }
}

impl From<(IpAddr, Option<u16>)> for TrustedPeer {
    fn from(value: (IpAddr, Option<u16>)) -> Self {
        let address = match value.0 {
            IpAddr::V4(ip) => AddrV2::Ipv4(ip),
            IpAddr::V6(ip) => AddrV2::Ipv6(ip),
        };
        TrustedPeer::new(address, value.1, ServiceFlags::NONE)
    }
}

impl From<IpAddr> for TrustedPeer {
    fn from(value: IpAddr) -> Self {
        TrustedPeer::from_ip(value)
    }
}

impl From<SocketAddr> for TrustedPeer {
    fn from(value: SocketAddr) -> Self {
        TrustedPeer::from_socket_addr(value)
    }
}

/// Route network traffic through a Socks5 proxy, typically used by a Tor daemon.
#[derive(Debug, Clone)]
pub struct Socks5Proxy(SocketAddr);

impl Socks5Proxy {
    /// Define a non-standard Socks5 proxy to connect to.
    pub fn new(socket_addr: impl Into<SocketAddr>) -> Self {
        Self(socket_addr.into())
    }

    /// Connect to the default local Socks5 proxy hosted at `127.0.0.1:9050`.
    pub const fn local() -> Self {
        Socks5Proxy(SocketAddr::new(
            IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)),
            9050,
        ))
    }
}

impl From<SocketAddr> for Socks5Proxy {
    fn from(value: SocketAddr) -> Self {
        Self(value)
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum NodeState {
    // We are behind on block headers according to our peers.
    Behind,
    // We may start downloading compact block filter headers.
    HeadersSynced,
    // We may start scanning compact block filters.
    FilterHeadersSynced,
    // We may start asking for blocks with matches.
    FiltersSynced,
}

#[derive(Debug)]
struct Config {
    required_peers: u8,
    white_list: Vec<TrustedPeer>,
    whitelist_only: bool,
    data_path: Option<PathBuf>,
    chain_state: Option<ChainState>,
    connection_type: ConnectionType,
    peer_timeout_config: PeerTimeoutConfig,
    filter_type: FilterType,
    block_type: BlockType,
}

impl Default for Config {
    fn default() -> Self {
        Self {
            required_peers: 1,
            white_list: Default::default(),
            whitelist_only: Default::default(),
            data_path: Default::default(),
            chain_state: Default::default(),
            connection_type: Default::default(),
            peer_timeout_config: PeerTimeoutConfig::default(),
            filter_type: FilterType::default(),
            block_type: BlockType::default(),
        }
    }
}
/// Query a Bitcoin DNS seeder.
///
/// This is **not** a generic DNS implementation. It is specifically tailored to query and parse DNS for Bitcoin seeders.
/// Iternally, three queries will be made with varying filters for the requested service flags.
/// Similar to [`lookup_host`](tokio::net::lookup_host), this has no guarantee to return any `IpAddr`.
///
/// # Example usage
///
/// ```no_run
/// use std::net::{IpAddr, Ipv4Addr};
///
/// use bip157::lookup_host;
///
/// #[tokio::main]
/// async fn main() {
///     let addrs = lookup_host("seed.bitcoin.sipa.be").await;
/// }
/// ```
pub async fn lookup_host<S: AsRef<str>>(hostname: S) -> Vec<IpAddr> {
    crate::network::dns::lookup_hostname(hostname.as_ref()).await
}

fn default_port_from_network(network: &Network) -> u16 {
    match network {
        Network::Bitcoin => 8333,
        Network::Testnet => 18333,
        Network::Testnet4 => 48333,
        Network::Signet => 38333,
        Network::Regtest => 18444,
    }
}

#[derive(Debug, Clone)]
struct Dialog {
    info_tx: Sender<Info>,
    warn_tx: UnboundedSender<Warning>,
    event_tx: UnboundedSender<Event>,
}

impl Dialog {
    fn new(
        info_tx: Sender<Info>,
        warn_tx: UnboundedSender<Warning>,
        event_tx: UnboundedSender<Event>,
    ) -> Self {
        Self {
            info_tx,
            warn_tx,
            event_tx,
        }
    }

    fn send_warning(&self, warning: Warning) {
        let _ = self.warn_tx.send(warning);
    }

    async fn send_info(&self, info: Info) {
        let _ = self.info_tx.send(info).await;
    }

    fn send_event(&self, message: Event) {
        let _ = self.event_tx.send(message);
    }
}

/// A package is a set of dependent transactions to submit to the mempool.
#[derive(Debug, Clone)]
pub struct Package {
    parent: Transaction,
    child: Option<Transaction>,
}

impl Package {
    /// Create a new package from a single transaction.
    pub fn new_single(transaction: Transaction) -> Self {
        Self {
            parent: transaction,
            child: None,
        }
    }

    /// Construct a new package using the one-parent-one-child topology, where the child spends an
    /// output from the parent. The primary use of such a topology is for a child to bump the
    /// fee-rate of the package.
    ///
    /// # Errors
    ///
    /// If the child does not spend at least one output created by the parent.
    pub fn new_one_parent_one_child(
        parent: Transaction,
        child: Transaction,
    ) -> Result<Self, error::PackageError> {
        Self::child_depends_on_parent(&parent, &child)?;
        Ok(Self {
            parent,
            child: Some(child),
        })
    }

    /// Construct a new package from a list of transactions. Currently, the only valid package
    /// lengths are 1 and 2. In the case of two transactions, the child is expected to be _last_ in
    /// the list.
    ///
    /// # Errors
    ///
    /// - If the length of the vector is not one or two
    /// - The transactions do not depend on each other.
    pub fn from_vec(mut transactions: Vec<Transaction>) -> Result<Self, error::PackageError> {
        match transactions.len() {
            1 => Ok(Package::new_single(transactions.remove(0))),
            2 => {
                let parent = transactions.remove(0);
                let child = transactions.remove(0);
                Ok(Package::new_one_parent_one_child(parent, child)?)
            }
            invalid => Err(error::PackageError::InvalidPackageLength(invalid)),
        }
    }

    fn child_depends_on_parent(
        parent: &Transaction,
        child: &Transaction,
    ) -> Result<(), error::PackageError> {
        let outpoints = {
            let txid = parent.compute_txid();
            let mut outpoints = Vec::with_capacity(parent.output.len());
            for vout in 0..parent.output.len() {
                outpoints.push(OutPoint {
                    txid,
                    vout: vout as u32,
                });
            }
            outpoints
        };
        if !child
            .input
            .iter()
            .any(|input| outpoints.contains(&input.previous_output))
        {
            return Err(error::PackageError::UnrelatedTransactions);
        }
        Ok(())
    }

    fn advertise_package(&self) -> Wtxid {
        match &self.child {
            Some(child) => child.compute_wtxid(),
            None => self.parent.compute_wtxid(),
        }
    }

    fn parent(&self) -> Transaction {
        self.parent.clone()
    }

    fn child(&self) -> Option<Transaction> {
        self.child.clone()
    }
}

impl From<Transaction> for Package {
    fn from(value: Transaction) -> Self {
        Package {
            parent: value,
            child: None,
        }
    }
}

macro_rules! impl_sourceless_error {
    ($e:ident) => {
        impl std::error::Error for $e {
            fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
                None
            }
        }
    };
}

pub(crate) use impl_sourceless_error;

macro_rules! debug {
    ($expr:expr) => {
        #[cfg(debug_assertions)]
        println!("{}", $expr)
    };
}

pub(crate) use debug;

#[cfg(test)]
macro_rules! impl_deserialize {
    ($t:ident, $for:ident) => {
        impl<'de> serde::Deserialize<'de> for $t {
            fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
            where
                D: serde::Deserializer<'de>,
            {
                let s = String::deserialize(deserializer)?;
                let bytes = hex::decode(&s).map_err(serde::de::Error::custom)?;
                let bitcoin_type: $for =
                    bitcoin::consensus::deserialize(&bytes).map_err(serde::de::Error::custom)?;
                Ok($t(bitcoin_type))
            }
        }
    };
}

#[cfg(test)]
pub(crate) use impl_deserialize;