bitcoint4/network/
message_bloom.rs

1// SPDX-License-Identifier: CC0-1.0
2
3//! Bitcoin Connection Bloom filtering network messages.
4//!
5//! This module describes BIP37 Connection Bloom filtering network messages.
6//!
7
8use std::io;
9
10use crate::consensus::{encode, Decodable, Encodable, ReadExt};
11use crate::internal_macros::impl_consensus_encoding;
12
13/// `filterload` message sets the current bloom filter
14#[derive(Clone, PartialEq, Eq, Debug)]
15pub struct FilterLoad {
16    /// The filter itself
17    pub filter: Vec<u8>,
18    /// The number of hash functions to use
19    pub hash_funcs: u32,
20    /// A random value
21    pub tweak: u32,
22    /// Controls how matched items are added to the filter
23    pub flags: BloomFlags,
24}
25
26impl_consensus_encoding!(FilterLoad, filter, hash_funcs, tweak, flags);
27
28/// Bloom filter update flags
29#[derive(Debug, Copy, Clone, Eq, PartialEq)]
30pub enum BloomFlags {
31    /// Never update the filter with outpoints.
32    None,
33    /// Always update the filter with outpoints.
34    All,
35    /// Only update the filter with outpoints if it is P2PK or P2MS
36    PubkeyOnly,
37}
38
39impl Encodable for BloomFlags {
40    fn consensus_encode<W: io::Write + ?Sized>(&self, w: &mut W) -> Result<usize, io::Error> {
41        w.write_all(&[match self {
42            BloomFlags::None => 0,
43            BloomFlags::All => 1,
44            BloomFlags::PubkeyOnly => 2,
45        }])?;
46        Ok(1)
47    }
48}
49
50impl Decodable for BloomFlags {
51    fn consensus_decode<R: io::Read + ?Sized>(r: &mut R) -> Result<Self, encode::Error> {
52        Ok(match r.read_u8()? {
53            0 => BloomFlags::None,
54            1 => BloomFlags::All,
55            2 => BloomFlags::PubkeyOnly,
56            _ => return Err(encode::Error::ParseFailed("unknown bloom flag")),
57        })
58    }
59}
60
61/// `filteradd` message updates the current filter with new data
62#[derive(Clone, PartialEq, Eq, Debug)]
63pub struct FilterAdd {
64    /// The data element to add to the current filter.
65    pub data: Vec<u8>,
66}
67
68impl_consensus_encoding!(FilterAdd, data);