Bitcoin Core  27.99.0
P2P Digital Currency
blockfilter.cpp
Go to the documentation of this file.
1 // Copyright (c) 2018-2022 The Bitcoin Core developers
2 // Distributed under the MIT software license, see the accompanying
3 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
4 
5 #include <mutex>
6 #include <set>
7 
8 #include <blockfilter.h>
9 #include <crypto/siphash.h>
10 #include <hash.h>
11 #include <primitives/block.h>
12 #include <primitives/transaction.h>
13 #include <script/script.h>
14 #include <streams.h>
15 #include <undo.h>
16 #include <util/golombrice.h>
17 #include <util/string.h>
18 
19 using util::Join;
20 
21 static const std::map<BlockFilterType, std::string> g_filter_types = {
22  {BlockFilterType::BASIC, "basic"},
23 };
24 
25 uint64_t GCSFilter::HashToRange(const Element& element) const
26 {
28  .Write(element)
29  .Finalize();
30  return FastRange64(hash, m_F);
31 }
32 
33 std::vector<uint64_t> GCSFilter::BuildHashedSet(const ElementSet& elements) const
34 {
35  std::vector<uint64_t> hashed_elements;
36  hashed_elements.reserve(elements.size());
37  for (const Element& element : elements) {
38  hashed_elements.push_back(HashToRange(element));
39  }
40  std::sort(hashed_elements.begin(), hashed_elements.end());
41  return hashed_elements;
42 }
43 
45  : m_params(params), m_N(0), m_F(0), m_encoded{0}
46 {}
47 
48 GCSFilter::GCSFilter(const Params& params, std::vector<unsigned char> encoded_filter, bool skip_decode_check)
49  : m_params(params), m_encoded(std::move(encoded_filter))
50 {
51  SpanReader stream{m_encoded};
52 
53  uint64_t N = ReadCompactSize(stream);
54  m_N = static_cast<uint32_t>(N);
55  if (m_N != N) {
56  throw std::ios_base::failure("N must be <2^32");
57  }
58  m_F = static_cast<uint64_t>(m_N) * static_cast<uint64_t>(m_params.m_M);
59 
60  if (skip_decode_check) return;
61 
62  // Verify that the encoded filter contains exactly N elements. If it has too much or too little
63  // data, a std::ios_base::failure exception will be raised.
64  BitStreamReader bitreader{stream};
65  for (uint64_t i = 0; i < m_N; ++i) {
66  GolombRiceDecode(bitreader, m_params.m_P);
67  }
68  if (!stream.empty()) {
69  throw std::ios_base::failure("encoded_filter contains excess data");
70  }
71 }
72 
73 GCSFilter::GCSFilter(const Params& params, const ElementSet& elements)
74  : m_params(params)
75 {
76  size_t N = elements.size();
77  m_N = static_cast<uint32_t>(N);
78  if (m_N != N) {
79  throw std::invalid_argument("N must be <2^32");
80  }
81  m_F = static_cast<uint64_t>(m_N) * static_cast<uint64_t>(m_params.m_M);
82 
83  VectorWriter stream{m_encoded, 0};
84 
85  WriteCompactSize(stream, m_N);
86 
87  if (elements.empty()) {
88  return;
89  }
90 
91  BitStreamWriter bitwriter{stream};
92 
93  uint64_t last_value = 0;
94  for (uint64_t value : BuildHashedSet(elements)) {
95  uint64_t delta = value - last_value;
96  GolombRiceEncode(bitwriter, m_params.m_P, delta);
97  last_value = value;
98  }
99 
100  bitwriter.Flush();
101 }
102 
103 bool GCSFilter::MatchInternal(const uint64_t* element_hashes, size_t size) const
104 {
105  SpanReader stream{m_encoded};
106 
107  // Seek forward by size of N
108  uint64_t N = ReadCompactSize(stream);
109  assert(N == m_N);
110 
111  BitStreamReader bitreader{stream};
112 
113  uint64_t value = 0;
114  size_t hashes_index = 0;
115  for (uint32_t i = 0; i < m_N; ++i) {
116  uint64_t delta = GolombRiceDecode(bitreader, m_params.m_P);
117  value += delta;
118 
119  while (true) {
120  if (hashes_index == size) {
121  return false;
122  } else if (element_hashes[hashes_index] == value) {
123  return true;
124  } else if (element_hashes[hashes_index] > value) {
125  break;
126  }
127 
128  hashes_index++;
129  }
130  }
131 
132  return false;
133 }
134 
135 bool GCSFilter::Match(const Element& element) const
136 {
137  uint64_t query = HashToRange(element);
138  return MatchInternal(&query, 1);
139 }
140 
141 bool GCSFilter::MatchAny(const ElementSet& elements) const
142 {
143  const std::vector<uint64_t> queries = BuildHashedSet(elements);
144  return MatchInternal(queries.data(), queries.size());
145 }
146 
147 const std::string& BlockFilterTypeName(BlockFilterType filter_type)
148 {
149  static std::string unknown_retval;
150  auto it = g_filter_types.find(filter_type);
151  return it != g_filter_types.end() ? it->second : unknown_retval;
152 }
153 
154 bool BlockFilterTypeByName(const std::string& name, BlockFilterType& filter_type) {
155  for (const auto& entry : g_filter_types) {
156  if (entry.second == name) {
157  filter_type = entry.first;
158  return true;
159  }
160  }
161  return false;
162 }
163 
164 const std::set<BlockFilterType>& AllBlockFilterTypes()
165 {
166  static std::set<BlockFilterType> types;
167 
168  static std::once_flag flag;
169  std::call_once(flag, []() {
170  for (const auto& entry : g_filter_types) {
171  types.insert(entry.first);
172  }
173  });
174 
175  return types;
176 }
177 
178 const std::string& ListBlockFilterTypes()
179 {
180  static std::string type_list{Join(g_filter_types, ", ", [](const auto& entry) { return entry.second; })};
181 
182  return type_list;
183 }
184 
186  const CBlockUndo& block_undo)
187 {
188  GCSFilter::ElementSet elements;
189 
190  for (const CTransactionRef& tx : block.vtx) {
191  for (const CTxOut& txout : tx->vout) {
192  const CScript& script = txout.scriptPubKey;
193  if (script.empty() || script[0] == OP_RETURN) continue;
194  elements.emplace(script.begin(), script.end());
195  }
196  }
197 
198  for (const CTxUndo& tx_undo : block_undo.vtxundo) {
199  for (const Coin& prevout : tx_undo.vprevout) {
200  const CScript& script = prevout.out.scriptPubKey;
201  if (script.empty()) continue;
202  elements.emplace(script.begin(), script.end());
203  }
204  }
205 
206  return elements;
207 }
208 
209 BlockFilter::BlockFilter(BlockFilterType filter_type, const uint256& block_hash,
210  std::vector<unsigned char> filter, bool skip_decode_check)
211  : m_filter_type(filter_type), m_block_hash(block_hash)
212 {
213  GCSFilter::Params params;
214  if (!BuildParams(params)) {
215  throw std::invalid_argument("unknown filter_type");
216  }
217  m_filter = GCSFilter(params, std::move(filter), skip_decode_check);
218 }
219 
220 BlockFilter::BlockFilter(BlockFilterType filter_type, const CBlock& block, const CBlockUndo& block_undo)
221  : m_filter_type(filter_type), m_block_hash(block.GetHash())
222 {
223  GCSFilter::Params params;
224  if (!BuildParams(params)) {
225  throw std::invalid_argument("unknown filter_type");
226  }
227  m_filter = GCSFilter(params, BasicFilterElements(block, block_undo));
228 }
229 
231 {
232  switch (m_filter_type) {
234  params.m_siphash_k0 = m_block_hash.GetUint64(0);
235  params.m_siphash_k1 = m_block_hash.GetUint64(1);
236  params.m_P = BASIC_FILTER_P;
237  params.m_M = BASIC_FILTER_M;
238  return true;
240  return false;
241  }
242 
243  return false;
244 }
245 
247 {
248  return Hash(GetEncodedFilter());
249 }
250 
251 uint256 BlockFilter::ComputeHeader(const uint256& prev_header) const
252 {
253  return Hash(GetHash(), prev_header);
254 }
const std::string & BlockFilterTypeName(BlockFilterType filter_type)
Get the human-readable name for a filter type.
static const std::map< BlockFilterType, std::string > g_filter_types
Definition: blockfilter.cpp:21
static GCSFilter::ElementSet BasicFilterElements(const CBlock &block, const CBlockUndo &block_undo)
const std::string & ListBlockFilterTypes()
Get a comma-separated list of known filter type names.
bool BlockFilterTypeByName(const std::string &name, BlockFilterType &filter_type)
Find a filter type by its human-readable name.
const std::set< BlockFilterType > & AllBlockFilterTypes()
Get a list of known filter types.
BlockFilterType
Definition: blockfilter.h:93
constexpr uint8_t BASIC_FILTER_P
Definition: blockfilter.h:89
constexpr uint32_t BASIC_FILTER_M
Definition: blockfilter.h:90
GCSFilter m_filter
Definition: blockfilter.h:119
bool BuildParams(GCSFilter::Params &params) const
uint256 ComputeHeader(const uint256 &prev_header) const
Compute the filter header given the previous one.
BlockFilterType m_filter_type
Definition: blockfilter.h:117
BlockFilter()=default
uint256 GetHash() const
Compute the filter hash.
uint256 m_block_hash
Definition: blockfilter.h:118
const std::vector< unsigned char > & GetEncodedFilter() const LIFETIMEBOUND
Definition: blockfilter.h:138
Definition: block.h:69
std::vector< CTransactionRef > vtx
Definition: block.h:72
Undo information for a CBlock.
Definition: undo.h:63
std::vector< CTxUndo > vtxundo
Definition: undo.h:65
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:414
SipHash-2-4.
Definition: siphash.h:15
uint64_t Finalize() const
Compute the 64-bit SipHash-2-4 of the data written so far.
Definition: siphash.cpp:77
CSipHasher & Write(uint64_t data)
Hash a 64-bit integer worth of data It is treated as if this was the little-endian interpretation of ...
Definition: siphash.cpp:28
An output of a transaction.
Definition: transaction.h:150
CScript scriptPubKey
Definition: transaction.h:153
Undo information for a CTransaction.
Definition: undo.h:53
std::vector< Coin > vprevout
Definition: undo.h:56
A UTXO entry.
Definition: coins.h:32
CTxOut out
unspent transaction output
Definition: coins.h:35
This implements a Golomb-coded set as defined in BIP 158.
Definition: blockfilter.h:29
std::vector< unsigned char > Element
Definition: blockfilter.h:31
uint64_t m_F
Range of element hashes, F = N * M.
Definition: blockfilter.h:49
bool MatchInternal(const uint64_t *sorted_element_hashes, size_t size) const
Helper method used to implement Match and MatchAny.
std::unordered_set< Element, ByteVectorHash > ElementSet
Definition: blockfilter.h:32
uint64_t HashToRange(const Element &element) const
Hash a data element to an integer in the range [0, N * M).
Definition: blockfilter.cpp:25
uint32_t m_N
Number of elements in the filter.
Definition: blockfilter.h:48
bool Match(const Element &element) const
Checks if the element may be in the set.
GCSFilter(const Params &params=Params())
Constructs an empty filter.
Definition: blockfilter.cpp:44
bool MatchAny(const ElementSet &elements) const
Checks if any of the given elements may be in the set.
std::vector< uint64_t > BuildHashedSet(const ElementSet &elements) const
Definition: blockfilter.cpp:33
Params m_params
Definition: blockfilter.h:47
std::vector< unsigned char > m_encoded
Definition: blockfilter.h:50
Minimal stream for reading from an existing byte array by Span.
Definition: streams.h:101
constexpr uint64_t GetUint64(int pos) const
Definition: uint256.h:76
256-bit opaque blob.
Definition: uint256.h:106
static uint64_t FastRange64(uint64_t x, uint64_t n)
Fast range reduction with 64-bit input and 64-bit range.
Definition: fastrange.h:25
uint64_t GolombRiceDecode(BitStreamReader< IStream > &bitreader, uint8_t P)
Definition: golombrice.h:32
void GolombRiceEncode(BitStreamWriter< OStream > &bitwriter, uint8_t P, uint64_t x)
Definition: golombrice.h:15
uint256 Hash(const T &in1)
Compute the 256-bit hash of an object.
Definition: hash.h:75
auto Join(const C &container, const S &separator, UnaryOp unary_op)
Join all container items.
Definition: string.h:107
std::shared_ptr< const CTransaction > CTransactionRef
Definition: transaction.h:423
const char * name
Definition: rest.cpp:49
@ OP_RETURN
Definition: script.h:110
void WriteCompactSize(SizeComputer &os, uint64_t nSize)
Definition: serialize.h:1095
uint64_t ReadCompactSize(Stream &is, bool range_check=true)
Decode a CompactSize-encoded variable-length integer.
Definition: serialize.h:337
uint32_t m_M
Inverse false positive rate.
Definition: blockfilter.h:39
uint64_t m_siphash_k1
Definition: blockfilter.h:37
uint8_t m_P
Golomb-Rice coding parameter.
Definition: blockfilter.h:38
uint64_t m_siphash_k0
Definition: blockfilter.h:36
assert(!tx.IsCoinBase())