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 static const std::map<BlockFilterType, std::string> g_filter_types = {
20  {BlockFilterType::BASIC, "basic"},
21 };
22 
23 uint64_t GCSFilter::HashToRange(const Element& element) const
24 {
26  .Write(element)
27  .Finalize();
28  return FastRange64(hash, m_F);
29 }
30 
31 std::vector<uint64_t> GCSFilter::BuildHashedSet(const ElementSet& elements) const
32 {
33  std::vector<uint64_t> hashed_elements;
34  hashed_elements.reserve(elements.size());
35  for (const Element& element : elements) {
36  hashed_elements.push_back(HashToRange(element));
37  }
38  std::sort(hashed_elements.begin(), hashed_elements.end());
39  return hashed_elements;
40 }
41 
43  : m_params(params), m_N(0), m_F(0), m_encoded{0}
44 {}
45 
46 GCSFilter::GCSFilter(const Params& params, std::vector<unsigned char> encoded_filter, bool skip_decode_check)
47  : m_params(params), m_encoded(std::move(encoded_filter))
48 {
49  SpanReader stream{m_encoded};
50 
51  uint64_t N = ReadCompactSize(stream);
52  m_N = static_cast<uint32_t>(N);
53  if (m_N != N) {
54  throw std::ios_base::failure("N must be <2^32");
55  }
56  m_F = static_cast<uint64_t>(m_N) * static_cast<uint64_t>(m_params.m_M);
57 
58  if (skip_decode_check) return;
59 
60  // Verify that the encoded filter contains exactly N elements. If it has too much or too little
61  // data, a std::ios_base::failure exception will be raised.
62  BitStreamReader bitreader{stream};
63  for (uint64_t i = 0; i < m_N; ++i) {
64  GolombRiceDecode(bitreader, m_params.m_P);
65  }
66  if (!stream.empty()) {
67  throw std::ios_base::failure("encoded_filter contains excess data");
68  }
69 }
70 
71 GCSFilter::GCSFilter(const Params& params, const ElementSet& elements)
72  : m_params(params)
73 {
74  size_t N = elements.size();
75  m_N = static_cast<uint32_t>(N);
76  if (m_N != N) {
77  throw std::invalid_argument("N must be <2^32");
78  }
79  m_F = static_cast<uint64_t>(m_N) * static_cast<uint64_t>(m_params.m_M);
80 
81  VectorWriter stream{m_encoded, 0};
82 
83  WriteCompactSize(stream, m_N);
84 
85  if (elements.empty()) {
86  return;
87  }
88 
89  BitStreamWriter bitwriter{stream};
90 
91  uint64_t last_value = 0;
92  for (uint64_t value : BuildHashedSet(elements)) {
93  uint64_t delta = value - last_value;
94  GolombRiceEncode(bitwriter, m_params.m_P, delta);
95  last_value = value;
96  }
97 
98  bitwriter.Flush();
99 }
100 
101 bool GCSFilter::MatchInternal(const uint64_t* element_hashes, size_t size) const
102 {
103  SpanReader stream{m_encoded};
104 
105  // Seek forward by size of N
106  uint64_t N = ReadCompactSize(stream);
107  assert(N == m_N);
108 
109  BitStreamReader bitreader{stream};
110 
111  uint64_t value = 0;
112  size_t hashes_index = 0;
113  for (uint32_t i = 0; i < m_N; ++i) {
114  uint64_t delta = GolombRiceDecode(bitreader, m_params.m_P);
115  value += delta;
116 
117  while (true) {
118  if (hashes_index == size) {
119  return false;
120  } else if (element_hashes[hashes_index] == value) {
121  return true;
122  } else if (element_hashes[hashes_index] > value) {
123  break;
124  }
125 
126  hashes_index++;
127  }
128  }
129 
130  return false;
131 }
132 
133 bool GCSFilter::Match(const Element& element) const
134 {
135  uint64_t query = HashToRange(element);
136  return MatchInternal(&query, 1);
137 }
138 
139 bool GCSFilter::MatchAny(const ElementSet& elements) const
140 {
141  const std::vector<uint64_t> queries = BuildHashedSet(elements);
142  return MatchInternal(queries.data(), queries.size());
143 }
144 
145 const std::string& BlockFilterTypeName(BlockFilterType filter_type)
146 {
147  static std::string unknown_retval;
148  auto it = g_filter_types.find(filter_type);
149  return it != g_filter_types.end() ? it->second : unknown_retval;
150 }
151 
152 bool BlockFilterTypeByName(const std::string& name, BlockFilterType& filter_type) {
153  for (const auto& entry : g_filter_types) {
154  if (entry.second == name) {
155  filter_type = entry.first;
156  return true;
157  }
158  }
159  return false;
160 }
161 
162 const std::set<BlockFilterType>& AllBlockFilterTypes()
163 {
164  static std::set<BlockFilterType> types;
165 
166  static std::once_flag flag;
167  std::call_once(flag, []() {
168  for (const auto& entry : g_filter_types) {
169  types.insert(entry.first);
170  }
171  });
172 
173  return types;
174 }
175 
176 const std::string& ListBlockFilterTypes()
177 {
178  static std::string type_list{Join(g_filter_types, ", ", [](const auto& entry) { return entry.second; })};
179 
180  return type_list;
181 }
182 
184  const CBlockUndo& block_undo)
185 {
186  GCSFilter::ElementSet elements;
187 
188  for (const CTransactionRef& tx : block.vtx) {
189  for (const CTxOut& txout : tx->vout) {
190  const CScript& script = txout.scriptPubKey;
191  if (script.empty() || script[0] == OP_RETURN) continue;
192  elements.emplace(script.begin(), script.end());
193  }
194  }
195 
196  for (const CTxUndo& tx_undo : block_undo.vtxundo) {
197  for (const Coin& prevout : tx_undo.vprevout) {
198  const CScript& script = prevout.out.scriptPubKey;
199  if (script.empty()) continue;
200  elements.emplace(script.begin(), script.end());
201  }
202  }
203 
204  return elements;
205 }
206 
207 BlockFilter::BlockFilter(BlockFilterType filter_type, const uint256& block_hash,
208  std::vector<unsigned char> filter, bool skip_decode_check)
209  : m_filter_type(filter_type), m_block_hash(block_hash)
210 {
211  GCSFilter::Params params;
212  if (!BuildParams(params)) {
213  throw std::invalid_argument("unknown filter_type");
214  }
215  m_filter = GCSFilter(params, std::move(filter), skip_decode_check);
216 }
217 
218 BlockFilter::BlockFilter(BlockFilterType filter_type, const CBlock& block, const CBlockUndo& block_undo)
219  : m_filter_type(filter_type), m_block_hash(block.GetHash())
220 {
221  GCSFilter::Params params;
222  if (!BuildParams(params)) {
223  throw std::invalid_argument("unknown filter_type");
224  }
225  m_filter = GCSFilter(params, BasicFilterElements(block, block_undo));
226 }
227 
229 {
230  switch (m_filter_type) {
232  params.m_siphash_k0 = m_block_hash.GetUint64(0);
233  params.m_siphash_k1 = m_block_hash.GetUint64(1);
234  params.m_P = BASIC_FILTER_P;
235  params.m_M = BASIC_FILTER_M;
236  return true;
238  return false;
239  }
240 
241  return false;
242 }
243 
245 {
246  return Hash(GetEncodedFilter());
247 }
248 
249 uint256 BlockFilter::ComputeHeader(const uint256& prev_header) const
250 {
251  return Hash(GetHash(), prev_header);
252 }
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:19
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:23
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:42
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:31
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
bool empty() const
Definition: prevector.h:300
iterator begin()
Definition: prevector.h:304
iterator end()
Definition: prevector.h:306
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
std::shared_ptr< const CTransaction > CTransactionRef
Definition: transaction.h:423
const char * name
Definition: rest.cpp:50
@ OP_RETURN
Definition: script.h:110
void WriteCompactSize(SizeComputer &os, uint64_t nSize)
Definition: serialize.h:1110
uint64_t ReadCompactSize(Stream &is, bool range_check=true)
Decode a CompactSize-encoded variable-length integer.
Definition: serialize.h:352
auto Join(const C &container, const S &separator, UnaryOp unary_op)
Join all container items.
Definition: string.h:69
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())