Bitcoin Core  0.19.99
P2P Digital Currency
blockfilter.cpp
Go to the documentation of this file.
1 // Copyright (c) 2018 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 <sstream>
7 
8 #include <blockfilter.h>
9 #include <crypto/siphash.h>
10 #include <hash.h>
11 #include <primitives/transaction.h>
12 #include <script/script.h>
13 #include <streams.h>
14 
16 static constexpr int GCS_SER_TYPE = SER_NETWORK;
17 
19 static constexpr int GCS_SER_VERSION = 0;
20 
21 static const std::map<BlockFilterType, std::string> g_filter_types = {
22  {BlockFilterType::BASIC, "basic"},
23 };
24 
25 template <typename OStream>
26 static void GolombRiceEncode(BitStreamWriter<OStream>& bitwriter, uint8_t P, uint64_t x)
27 {
28  // Write quotient as unary-encoded: q 1's followed by one 0.
29  uint64_t q = x >> P;
30  while (q > 0) {
31  int nbits = q <= 64 ? static_cast<int>(q) : 64;
32  bitwriter.Write(~0ULL, nbits);
33  q -= nbits;
34  }
35  bitwriter.Write(0, 1);
36 
37  // Write the remainder in P bits. Since the remainder is just the bottom
38  // P bits of x, there is no need to mask first.
39  bitwriter.Write(x, P);
40 }
41 
42 template <typename IStream>
43 static uint64_t GolombRiceDecode(BitStreamReader<IStream>& bitreader, uint8_t P)
44 {
45  // Read unary-encoded quotient: q 1's followed by one 0.
46  uint64_t q = 0;
47  while (bitreader.Read(1) == 1) {
48  ++q;
49  }
50 
51  uint64_t r = bitreader.Read(P);
52 
53  return (q << P) + r;
54 }
55 
56 // Map a value x that is uniformly distributed in the range [0, 2^64) to a
57 // value uniformly distributed in [0, n) by returning the upper 64 bits of
58 // x * n.
59 //
60 // See: https://lemire.me/blog/2016/06/27/a-fast-alternative-to-the-modulo-reduction/
61 static uint64_t MapIntoRange(uint64_t x, uint64_t n)
62 {
63 #ifdef __SIZEOF_INT128__
64  return (static_cast<unsigned __int128>(x) * static_cast<unsigned __int128>(n)) >> 64;
65 #else
66  // To perform the calculation on 64-bit numbers without losing the
67  // result to overflow, split the numbers into the most significant and
68  // least significant 32 bits and perform multiplication piece-wise.
69  //
70  // See: https://stackoverflow.com/a/26855440
71  uint64_t x_hi = x >> 32;
72  uint64_t x_lo = x & 0xFFFFFFFF;
73  uint64_t n_hi = n >> 32;
74  uint64_t n_lo = n & 0xFFFFFFFF;
75 
76  uint64_t ac = x_hi * n_hi;
77  uint64_t ad = x_hi * n_lo;
78  uint64_t bc = x_lo * n_hi;
79  uint64_t bd = x_lo * n_lo;
80 
81  uint64_t mid34 = (bd >> 32) + (bc & 0xFFFFFFFF) + (ad & 0xFFFFFFFF);
82  uint64_t upper64 = ac + (bc >> 32) + (ad >> 32) + (mid34 >> 32);
83  return upper64;
84 #endif
85 }
86 
87 uint64_t GCSFilter::HashToRange(const Element& element) const
88 {
90  .Write(element.data(), element.size())
91  .Finalize();
92  return MapIntoRange(hash, m_F);
93 }
94 
95 std::vector<uint64_t> GCSFilter::BuildHashedSet(const ElementSet& elements) const
96 {
97  std::vector<uint64_t> hashed_elements;
98  hashed_elements.reserve(elements.size());
99  for (const Element& element : elements) {
100  hashed_elements.push_back(HashToRange(element));
101  }
102  std::sort(hashed_elements.begin(), hashed_elements.end());
103  return hashed_elements;
104 }
105 
107  : m_params(params), m_N(0), m_F(0), m_encoded{0}
108 {}
109 
110 GCSFilter::GCSFilter(const Params& params, std::vector<unsigned char> encoded_filter)
111  : m_params(params), m_encoded(std::move(encoded_filter))
112 {
114 
115  uint64_t N = ReadCompactSize(stream);
116  m_N = static_cast<uint32_t>(N);
117  if (m_N != N) {
118  throw std::ios_base::failure("N must be <2^32");
119  }
120  m_F = static_cast<uint64_t>(m_N) * static_cast<uint64_t>(m_params.m_M);
121 
122  // Verify that the encoded filter contains exactly N elements. If it has too much or too little
123  // data, a std::ios_base::failure exception will be raised.
124  BitStreamReader<VectorReader> bitreader(stream);
125  for (uint64_t i = 0; i < m_N; ++i) {
126  GolombRiceDecode(bitreader, m_params.m_P);
127  }
128  if (!stream.empty()) {
129  throw std::ios_base::failure("encoded_filter contains excess data");
130  }
131 }
132 
133 GCSFilter::GCSFilter(const Params& params, const ElementSet& elements)
134  : m_params(params)
135 {
136  size_t N = elements.size();
137  m_N = static_cast<uint32_t>(N);
138  if (m_N != N) {
139  throw std::invalid_argument("N must be <2^32");
140  }
141  m_F = static_cast<uint64_t>(m_N) * static_cast<uint64_t>(m_params.m_M);
142 
144 
145  WriteCompactSize(stream, m_N);
146 
147  if (elements.empty()) {
148  return;
149  }
150 
151  BitStreamWriter<CVectorWriter> bitwriter(stream);
152 
153  uint64_t last_value = 0;
154  for (uint64_t value : BuildHashedSet(elements)) {
155  uint64_t delta = value - last_value;
156  GolombRiceEncode(bitwriter, m_params.m_P, delta);
157  last_value = value;
158  }
159 
160  bitwriter.Flush();
161 }
162 
163 bool GCSFilter::MatchInternal(const uint64_t* element_hashes, size_t size) const
164 {
166 
167  // Seek forward by size of N
168  uint64_t N = ReadCompactSize(stream);
169  assert(N == m_N);
170 
171  BitStreamReader<VectorReader> bitreader(stream);
172 
173  uint64_t value = 0;
174  size_t hashes_index = 0;
175  for (uint32_t i = 0; i < m_N; ++i) {
176  uint64_t delta = GolombRiceDecode(bitreader, m_params.m_P);
177  value += delta;
178 
179  while (true) {
180  if (hashes_index == size) {
181  return false;
182  } else if (element_hashes[hashes_index] == value) {
183  return true;
184  } else if (element_hashes[hashes_index] > value) {
185  break;
186  }
187 
188  hashes_index++;
189  }
190  }
191 
192  return false;
193 }
194 
195 bool GCSFilter::Match(const Element& element) const
196 {
197  uint64_t query = HashToRange(element);
198  return MatchInternal(&query, 1);
199 }
200 
201 bool GCSFilter::MatchAny(const ElementSet& elements) const
202 {
203  const std::vector<uint64_t> queries = BuildHashedSet(elements);
204  return MatchInternal(queries.data(), queries.size());
205 }
206 
207 const std::string& BlockFilterTypeName(BlockFilterType filter_type)
208 {
209  static std::string unknown_retval = "";
210  auto it = g_filter_types.find(filter_type);
211  return it != g_filter_types.end() ? it->second : unknown_retval;
212 }
213 
214 bool BlockFilterTypeByName(const std::string& name, BlockFilterType& filter_type) {
215  for (const auto& entry : g_filter_types) {
216  if (entry.second == name) {
217  filter_type = entry.first;
218  return true;
219  }
220  }
221  return false;
222 }
223 
224 const std::vector<BlockFilterType>& AllBlockFilterTypes()
225 {
226  static std::vector<BlockFilterType> types;
227 
228  static std::once_flag flag;
229  std::call_once(flag, []() {
230  types.reserve(g_filter_types.size());
231  for (auto entry : g_filter_types) {
232  types.push_back(entry.first);
233  }
234  });
235 
236  return types;
237 }
238 
239 const std::string& ListBlockFilterTypes()
240 {
241  static std::string type_list;
242 
243  static std::once_flag flag;
244  std::call_once(flag, []() {
245  std::stringstream ret;
246  bool first = true;
247  for (auto entry : g_filter_types) {
248  if (!first) ret << ", ";
249  ret << entry.second;
250  first = false;
251  }
252  type_list = ret.str();
253  });
254 
255  return type_list;
256 }
257 
259  const CBlockUndo& block_undo)
260 {
261  GCSFilter::ElementSet elements;
262 
263  for (const CTransactionRef& tx : block.vtx) {
264  for (const CTxOut& txout : tx->vout) {
265  const CScript& script = txout.scriptPubKey;
266  if (script.empty() || script[0] == OP_RETURN) continue;
267  elements.emplace(script.begin(), script.end());
268  }
269  }
270 
271  for (const CTxUndo& tx_undo : block_undo.vtxundo) {
272  for (const Coin& prevout : tx_undo.vprevout) {
273  const CScript& script = prevout.out.scriptPubKey;
274  if (script.empty()) continue;
275  elements.emplace(script.begin(), script.end());
276  }
277  }
278 
279  return elements;
280 }
281 
282 BlockFilter::BlockFilter(BlockFilterType filter_type, const uint256& block_hash,
283  std::vector<unsigned char> filter)
284  : m_filter_type(filter_type), m_block_hash(block_hash)
285 {
286  GCSFilter::Params params;
287  if (!BuildParams(params)) {
288  throw std::invalid_argument("unknown filter_type");
289  }
290  m_filter = GCSFilter(params, std::move(filter));
291 }
292 
293 BlockFilter::BlockFilter(BlockFilterType filter_type, const CBlock& block, const CBlockUndo& block_undo)
294  : m_filter_type(filter_type), m_block_hash(block.GetHash())
295 {
296  GCSFilter::Params params;
297  if (!BuildParams(params)) {
298  throw std::invalid_argument("unknown filter_type");
299  }
300  m_filter = GCSFilter(params, BasicFilterElements(block, block_undo));
301 }
302 
304 {
305  switch (m_filter_type) {
307  params.m_siphash_k0 = m_block_hash.GetUint64(0);
308  params.m_siphash_k1 = m_block_hash.GetUint64(1);
309  params.m_P = BASIC_FILTER_P;
310  params.m_M = BASIC_FILTER_M;
311  return true;
313  return false;
314  }
315 
316  return false;
317 }
318 
320 {
321  const std::vector<unsigned char>& data = GetEncodedFilter();
322 
323  uint256 result;
324  CHash256().Write(data.data(), data.size()).Finalize(result.begin());
325  return result;
326 }
327 
328 uint256 BlockFilter::ComputeHeader(const uint256& prev_header) const
329 {
330  const uint256& filter_hash = GetHash();
331 
332  uint256 result;
333  CHash256()
334  .Write(filter_hash.begin(), filter_hash.size())
335  .Write(prev_header.begin(), prev_header.size())
336  .Finalize(result.begin());
337  return result;
338 }
std::shared_ptr< const CTransaction > CTransactionRef
Definition: transaction.h:408
std::vector< Coin > vprevout
Definition: undo.h:73
BlockFilter()=default
static void GolombRiceEncode(BitStreamWriter< OStream > &bitwriter, uint8_t P, uint64_t x)
Definition: blockfilter.cpp:26
constexpr uint32_t BASIC_FILTER_M
Definition: blockfilter.h:85
CScript scriptPubKey
Definition: transaction.h:137
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
A UTXO entry.
Definition: coins.h:30
Definition: block.h:72
uint64_t ReadCompactSize(Stream &is)
Definition: serialize.h:288
bool BlockFilterTypeByName(const std::string &name, BlockFilterType &filter_type)
Find a filter type by its human-readable name.
void WriteCompactSize(CSizeComputer &os, uint64_t nSize)
Definition: serialize.h:998
CHash256 & Write(const unsigned char *data, size_t len)
Definition: hash.h:34
CTxOut out
unspent transaction output
Definition: coins.h:34
constexpr uint8_t BASIC_FILTER_P
Definition: blockfilter.h:84
bool MatchAny(const ElementSet &elements) const
Checks if any of the given elements may be in the set.
A hasher class for Bitcoin&#39;s 256-bit hash (double SHA-256).
Definition: hash.h:22
std::vector< uint64_t > BuildHashedSet(const ElementSet &elements) const
Definition: blockfilter.cpp:95
void Write(uint64_t data, int nbits)
Write the nbits least significant bits of a 64-bit int to the output stream.
Definition: streams.h:562
GCSFilter m_filter
Definition: blockfilter.h:114
static const std::map< BlockFilterType, std::string > g_filter_types
Definition: blockfilter.cpp:21
unsigned char * begin()
Definition: uint256.h:54
uint256 GetHash() const
Compute the filter hash.
bool Match(const Element &element) const
Checks if the element may be in the set.
GCSFilter(const Params &params=Params())
Constructs an empty filter.
bool MatchInternal(const uint64_t *sorted_element_hashes, size_t size) const
Helper method used to implement Match and MatchAny.
const std::vector< BlockFilterType > & AllBlockFilterTypes()
Get a list of known filter types.
iterator end()
Definition: prevector.h:286
BlockFilterType
Definition: blockfilter.h:87
const std::vector< unsigned char > & GetEncodedFilter() const
Definition: blockfilter.h:133
const std::string & ListBlockFilterTypes()
Get a comma-separated list of known filter type names.
Minimal stream for reading from an existing vector by reference.
Definition: streams.h:130
const char * name
Definition: rest.cpp:38
uint64_t HashToRange(const Element &element) const
Hash a data element to an integer in the range [0, N * M).
Definition: blockfilter.cpp:87
An output of a transaction.
Definition: transaction.h:133
unsigned int size() const
Definition: uint256.h:74
uint64_t Read(int nbits)
Read the specified number of bits from the stream.
Definition: streams.h:514
static uint64_t GolombRiceDecode(BitStreamReader< IStream > &bitreader, uint8_t P)
Definition: blockfilter.cpp:43
static GCSFilter::ElementSet BasicFilterElements(const CBlock &block, const CBlockUndo &block_undo)
This implements a Golomb-coded set as defined in BIP 158.
Definition: blockfilter.h:23
void Flush()
Flush any unwritten bits to the output stream, padding with 0&#39;s to the next byte boundary.
Definition: streams.h:582
std::unordered_set< Element, ByteVectorHash > ElementSet
Definition: blockfilter.h:27
uint32_t m_M
Inverse false positive rate.
Definition: blockfilter.h:34
uint256 ComputeHeader(const uint256 &prev_header) const
Compute the filter header given the previous one.
uint64_t m_siphash_k0
Definition: blockfilter.h:31
uint8_t m_P
Golomb-Rice coding parameter.
Definition: blockfilter.h:33
256-bit opaque blob.
Definition: uint256.h:120
std::vector< CTransactionRef > vtx
Definition: block.h:76
static constexpr int GCS_SER_TYPE
SerType used to serialize parameters in GCS filter encoding.
Definition: blockfilter.cpp:16
Undo information for a CBlock.
Definition: undo.h:101
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:390
Undo information for a CTransaction.
Definition: undo.h:69
BlockFilterType m_filter_type
Definition: blockfilter.h:112
bool empty() const
Definition: prevector.h:280
SipHash-2-4.
Definition: siphash.h:13
uint256 m_block_hash
Definition: blockfilter.h:113
Params m_params
Definition: blockfilter.h:42
iterator begin()
Definition: prevector.h:284
std::vector< unsigned char > Element
Definition: blockfilter.h:26
bool empty() const
Definition: streams.h:178
static constexpr int GCS_SER_VERSION
Protocol version used to serialize parameters in GCS filter encoding.
Definition: blockfilter.cpp:19
uint64_t m_siphash_k1
Definition: blockfilter.h:32
uint32_t m_N
Number of elements in the filter.
Definition: blockfilter.h:43
auto it
Definition: validation.cpp:365
uint64_t GetUint64(int pos) const
Definition: uint256.h:79
std::vector< CTxUndo > vtxundo
Definition: undo.h:104
uint64_t m_F
Range of element hashes, F = N * M.
Definition: blockfilter.h:44
bool BuildParams(GCSFilter::Params &params) const
std::vector< unsigned char > m_encoded
Definition: blockfilter.h:45
static uint64_t MapIntoRange(uint64_t x, uint64_t n)
Definition: blockfilter.cpp:61
const std::string & BlockFilterTypeName(BlockFilterType filter_type)
Get the human-readable name for a filter type.