cuprate_types/blockchain.rs
1//! Database [`BlockchainReadRequest`]s, [`BlockchainWriteRequest`]s, and [`BlockchainResponse`]s.
2//!
3//! Tests that assert particular requests lead to particular
4//! responses are also tested in Cuprate's blockchain database crate.
5//---------------------------------------------------------------------------------------------------- Import
6use std::{
7 collections::{HashMap, HashSet},
8 ops::Range,
9};
10
11use indexmap::{IndexMap, IndexSet};
12use monero_oxide::block::Block;
13
14use crate::{
15 output_cache::OutputCache,
16 rpc::{
17 ChainInfo, CoinbaseTxSum, OutputDistributionData, OutputHistogramEntry,
18 OutputHistogramInput,
19 },
20 types::{Chain, ExtendedBlockHeader, OutputOnChain, TxsInBlock, VerifiedBlockInformation},
21 AltBlockInformation, BlockCompleteEntry, ChainId, PreRctOutputDistributionInput,
22 TxInBlockchain,
23};
24
25//---------------------------------------------------------------------------------------------------- ReadRequest
26/// A read request to the blockchain database.
27///
28/// This pairs with [`BlockchainResponse`], where each variant here
29/// matches in name with a [`BlockchainResponse`] variant. For example,
30/// the proper response for a [`BlockchainReadRequest::BlockHash`]
31/// would be a [`BlockchainResponse::BlockHash`].
32///
33/// See `Response` for the expected responses per `Request`.
34#[derive(Debug, Clone, PartialEq, Eq)]
35pub enum BlockchainReadRequest {
36 /// Request [`BlockCompleteEntry`]s.
37 BlockCompleteEntries {
38 /// The block hashes.
39 block_hashes: Vec<[u8; 32]>,
40 /// If `true`, strip the prunable tx data.
41 prune: bool,
42 },
43
44 /// Request [`BlockCompleteEntry`]s.
45 ///
46 /// The input is the block heights.
47 BlockCompleteEntriesByHeight(Vec<usize>),
48
49 /// Request [`BlockCompleteEntry`]s (and output indices) for the
50 /// blocks above the split point between our chain and the given chain.
51 BlockCompleteEntriesAboveSplitPoint {
52 chain: Vec<[u8; 32]>,
53 /// If `Some`, skip the chain scan and start serving from this height directly.
54 start_height: Option<usize>,
55 /// If `true`, each block's miner-tx entry in the output indices is an
56 /// empty placeholder.
57 no_miner_tx: bool,
58 len: usize,
59 prune: bool,
60 },
61
62 /// Request a block's extended header.
63 ///
64 /// The input is the block's height.
65 BlockExtendedHeader(usize),
66
67 /// Request a block's hash.
68 ///
69 /// The input is the block's height and the chain it is on.
70 BlockHash(usize, Chain),
71
72 /// Request a range of block's hashes.
73 ///
74 /// The input is the range of block heights and the chain it is on.
75 BlockHashInRange(Range<usize>, Chain),
76
77 /// Request to check if we have a block and which [`Chain`] it is on.
78 ///
79 /// The input is the block's hash.
80 FindBlock([u8; 32]),
81
82 /// Removes the block hashes that are not in the _main_ chain.
83 ///
84 /// This should filter (remove) hashes in alt-blocks as well.
85 FilterUnknownHashes(HashSet<[u8; 32]>),
86
87 /// Request a range of block extended headers.
88 ///
89 /// The input is a range of block heights.
90 BlockExtendedHeaderInRange(Range<usize>, Chain),
91
92 /// Request the current chain height.
93 ///
94 /// Note that this is not the top-block height.
95 ChainHeight,
96
97 /// Request the total amount of generated coins (atomic units) at this height.
98 GeneratedCoins(usize),
99
100 /// Request the cumulative RCT output count for the main-chain blocks in this height range.
101 CumulativeRctOutsInRange(Range<usize>),
102
103 /// Request data for multiple outputs.
104 ///
105 /// The input is a `HashMap` where:
106 /// - Key = output amount
107 /// - Value = set of amount indices
108 ///
109 /// For pre-RCT outputs, the amount is non-zero,
110 /// and the amount indices represent the wanted
111 /// indices of duplicate amount outputs, i.e.:
112 ///
113 /// ```ignore
114 /// // list of outputs with amount 10
115 /// [0, 1, 2, 3, 4, 5]
116 /// // ^ ^
117 /// // we only want these two, so we would provide
118 /// // `amount: 10, amount_index: {1, 3}`
119 /// ```
120 ///
121 /// For RCT outputs, the amounts would be `0` and
122 /// the amount indices would represent the global
123 /// RCT output indices.
124 Outputs {
125 outputs: IndexMap<u64, IndexSet<u64>>,
126 get_txid: bool,
127 },
128
129 /// This is the same as [`BlockchainReadRequest::Outputs`] but with a [`Vec`] container.
130 ///
131 /// The input [`Vec`] values are `(amount, amount_index)`.
132 ///
133 /// The response will be in the same order as the request.
134 OutputsVec {
135 outputs: Vec<(u64, u64)>,
136 get_txid: bool,
137 },
138
139 /// Request the amount of outputs with a certain amount.
140 ///
141 /// The input is a list of output amounts.
142 NumberOutputsWithAmount(Vec<u64>),
143
144 /// Check the spend status of key images.
145 ///
146 /// Input is a set of key images.
147 KeyImagesSpent(HashSet<[u8; 32]>),
148
149 /// Same as [`BlockchainReadRequest::KeyImagesSpent`] but with a [`Vec`].
150 ///
151 /// The response will be in the same order as the request.
152 KeyImagesSpentVec(Vec<[u8; 32]>),
153
154 /// A request for the compact chain history.
155 CompactChainHistory,
156
157 /// A request for the next chain entry.
158 ///
159 /// Input is a list of block hashes and the amount of block hashes to return in the next chain entry.
160 ///
161 /// # Invariant
162 /// The [`Vec`] containing the block IDs must be sorted in reverse chronological block
163 /// order, or else the returned response is unspecified and meaningless,
164 /// as this request performs a binary search
165 NextChainEntry(Vec<[u8; 32]>, usize),
166
167 /// A request to find the first unknown block ID in a list of block IDs.
168 ///
169 /// # Invariant
170 /// The [`Vec`] containing the block IDs must be sorted in chronological block
171 /// order, or else the returned response is unspecified and meaningless,
172 /// as this request performs a binary search.
173 FindFirstUnknown(Vec<[u8; 32]>),
174
175 /// A request for transactions from a specific block.
176 TxsInBlock {
177 /// The block to get transactions from.
178 block_hash: [u8; 32],
179 /// The indexes of the transactions from the block.
180 /// This is not the global index of the txs, instead it is the local index as they appear in
181 /// the block.
182 tx_indexes: Vec<u64>,
183 },
184
185 /// A request for all alt blocks in the chain with the given [`ChainId`].
186 AltBlocksInChain(ChainId),
187
188 /// Get a [`Block`] by its height.
189 Block { height: usize },
190
191 /// Get a [`Block`] by its hash.
192 BlockByHash([u8; 32]),
193
194 /// Get the total amount of non-coinbase transactions in the chain.
195 TotalTxCount,
196
197 /// Get the current size of the database.
198 DatabaseSize,
199
200 /// Get an output histogram.
201 ///
202 /// TODO: document fields after impl.
203 OutputHistogram(OutputHistogramInput),
204
205 /// Get the distribution for a pre-RCT output amount.
206 ///
207 /// - TODO: document fields after impl.
208 /// - TODO: <https://github.com/monero-project/monero/blob/893916ad091a92e765ce3241b94e706ad012b62a/src/rpc/rpc_handler.cpp#L29>
209 PreRctOutputDistribution(PreRctOutputDistributionInput),
210
211 /// Get the coinbase amount and the fees amount for
212 /// `N` last blocks starting at particular height.
213 ///
214 /// TODO: document fields after impl.
215 CoinbaseTxSum { height: usize, count: u64 },
216
217 /// Get information on all alternative chains.
218 AltChains,
219
220 /// Get the amount of alternative chains that exist.
221 AltChainCount,
222
223 /// Get transaction blobs by their hashes.
224 ///
225 /// Returned transactions must preserve request order, omitting missing hashes.
226 Transactions { tx_hashes: Vec<[u8; 32]> },
227
228 /// Get the total amount of RCT outputs in the blockchain.
229 TotalRctOutputs,
230
231 /// Get the output indexes of a transaction.
232 TxOutputIndexes { tx_hash: [u8; 32] },
233}
234
235//---------------------------------------------------------------------------------------------------- WriteRequest
236/// A write request to the blockchain database.
237#[derive(Debug, Clone, PartialEq, Eq)]
238pub enum BlockchainWriteRequest {
239 /// Request that a block be written to the database.
240 ///
241 /// Input is an already verified block.
242 WriteBlock(VerifiedBlockInformation),
243
244 /// Request that a batch of blocks be written to the database.
245 ///
246 /// Input is an already verified batch of blocks, must not be empty.
247 BatchWriteBlocks(Vec<VerifiedBlockInformation>),
248
249 /// Write an alternative block to the database,
250 ///
251 /// Input is the alternative block.
252 WriteAltBlock(AltBlockInformation),
253
254 /// A request to pop some blocks from the top of the main chain
255 ///
256 /// Input is the amount of blocks to pop and a bool for if the popped blocks should be added as
257 /// alt blocks.
258 ///
259 /// This request flushes all alt-chains from the cache before adding the popped blocks to the
260 /// alt cache, if requested to do so.
261 PopBlocks(usize, bool),
262
263 /// A request to flush all alternative blocks.
264 FlushAltBlocks,
265}
266
267//---------------------------------------------------------------------------------------------------- Response
268/// A response from the database.
269///
270/// These are the data types returned when using sending a `Request`.
271///
272/// This pairs with [`BlockchainReadRequest`] and [`BlockchainWriteRequest`],
273/// see those two for more info.
274#[derive(Debug, Clone, PartialEq, Eq)]
275#[expect(clippy::large_enum_variant)]
276pub enum BlockchainResponse {
277 //------------------------------------------------------ Reads
278 /// Response to [`BlockchainReadRequest::BlockCompleteEntries`].
279 BlockCompleteEntries {
280 /// The [`BlockCompleteEntry`]s that we had.
281 blocks: Vec<BlockCompleteEntry>,
282 /// The hashes of blocks that were requested, but we don't have.
283 missing_hashes: Vec<[u8; 32]>,
284 /// Our blockchain height.
285 blockchain_height: usize,
286 },
287
288 /// Response to [`BlockchainReadRequest::BlockCompleteEntriesByHeight`].
289 BlockCompleteEntriesByHeight(Vec<BlockCompleteEntry>),
290
291 /// Response to [`BlockchainReadRequest::BlockCompleteEntriesAboveSplitPoint`].
292 BlockCompleteEntriesAboveSplitPoint {
293 /// The [`BlockCompleteEntry`]s that we had.
294 blocks: Vec<BlockCompleteEntry>,
295 /// The output indices of all transaction outputs across all blocks.
296 ///
297 /// `output_indices[block][tx][output]`, including the miner tx (miner tx will be empty if not requested).
298 output_indices: Vec<Vec<Vec<u64>>>,
299 /// Our blockchain height.
300 blockchain_height: usize,
301 /// The height the returned blocks start from.
302 start_height: usize,
303 /// Hash of the current top block.
304 top_hash: [u8; 32],
305 },
306
307 /// Response to [`BlockchainReadRequest::BlockExtendedHeader`].
308 ///
309 /// Inner value is the extended headed of the requested block.
310 BlockExtendedHeader(ExtendedBlockHeader),
311
312 /// Response to [`BlockchainReadRequest::BlockHash`].
313 ///
314 /// Inner value is the hash of the requested block.
315 BlockHash([u8; 32]),
316
317 /// Response to [`BlockchainReadRequest::BlockHashInRange`].
318 ///
319 /// Inner value is the hashes of the requested blocks, in order.
320 BlockHashInRange(Vec<[u8; 32]>),
321
322 /// Response to [`BlockchainReadRequest::FindBlock`].
323 ///
324 /// Inner value is the chain and height of the block if found.
325 FindBlock(Option<(Chain, usize)>),
326
327 /// Response to [`BlockchainReadRequest::FilterUnknownHashes`].
328 ///
329 /// Inner value is the list of hashes that were in the main chain.
330 FilterUnknownHashes(HashSet<[u8; 32]>),
331
332 /// Response to [`BlockchainReadRequest::BlockExtendedHeaderInRange`].
333 ///
334 /// Inner value is the list of extended header(s) of the requested block(s).
335 BlockExtendedHeaderInRange(Vec<ExtendedBlockHeader>),
336
337 /// Response to [`BlockchainReadRequest::ChainHeight`].
338 ///
339 /// Inner value is the chain height, and the top block's hash.
340 ChainHeight(usize, [u8; 32]),
341
342 /// Response to [`BlockchainReadRequest::GeneratedCoins`].
343 ///
344 /// Inner value is the total amount of generated coins up to and including the chosen height, in atomic units.
345 GeneratedCoins(u64),
346
347 /// Response to [`BlockchainReadRequest::CumulativeRctOutsInRange`].
348 ///
349 /// Inner value is `cumulative_rct_outs` for each block in the requested range.
350 CumulativeRctOutsInRange(Vec<u64>),
351
352 /// Response to [`BlockchainReadRequest::Outputs`].
353 ///
354 /// Inner value is an [`OutputCache`], missing outputs won't trigger an error, they just will not be
355 /// in the cache until the cache is updated with the block containing those outputs.
356 Outputs(OutputCache),
357
358 /// Response to [`BlockchainReadRequest::OutputsVec`].
359 OutputsVec(Vec<(u64, Vec<(u64, OutputOnChain)>)>),
360
361 /// Response to [`BlockchainReadRequest::NumberOutputsWithAmount`].
362 ///
363 /// Inner value is a `HashMap` of all the outputs requested where:
364 /// - Key = output amount
365 /// - Value = count of outputs with the same amount
366 NumberOutputsWithAmount(HashMap<u64, usize>),
367
368 /// Response to [`BlockchainReadRequest::KeyImagesSpent`].
369 ///
370 /// The inner value is `true` if _any_ of the key images
371 /// were spent (existed in the database already).
372 ///
373 /// The inner value is `false` if _none_ of the key images were spent.
374 KeyImagesSpent(bool),
375
376 /// Response to [`BlockchainReadRequest::KeyImagesSpentVec`].
377 ///
378 /// Inner value is a `Vec` the same length as the input.
379 ///
380 /// The index of each entry corresponds with the request.
381 /// `true` means that the key image was spent.
382 KeyImagesSpentVec(Vec<bool>),
383
384 /// Response to [`BlockchainReadRequest::CompactChainHistory`].
385 CompactChainHistory {
386 /// A list of blocks IDs in our chain, starting with the most recent block, all the way to the genesis block.
387 ///
388 /// These blocks should be in reverse chronological order, not every block is needed.
389 block_ids: Vec<[u8; 32]>,
390 /// The current cumulative difficulty of the chain.
391 cumulative_difficulty: u128,
392 },
393
394 /// Response to [`BlockchainReadRequest::NextChainEntry`].
395 ///
396 /// If all blocks were unknown `start_height` will be [`None`], the other fields will be meaningless.
397 NextChainEntry {
398 /// The start height of this entry, [`None`] if we could not find the split point.
399 start_height: Option<usize>,
400 /// The current chain height.
401 chain_height: usize,
402 /// The next block hashes in the entry.
403 block_ids: Vec<[u8; 32]>,
404 /// The block weights of the next blocks.
405 block_weights: Vec<usize>,
406 /// The current cumulative difficulty of our chain.
407 cumulative_difficulty: u128,
408 /// The block blob of the 2nd block in `block_ids`, if there is one.
409 first_block_blob: Option<Vec<u8>>,
410 },
411
412 /// Response to [`BlockchainReadRequest::FindFirstUnknown`].
413 ///
414 /// Contains the index of the first unknown block and its expected height.
415 ///
416 /// This will be [`None`] if all blocks were known.
417 FindFirstUnknown(Option<(usize, usize)>),
418
419 /// The response for [`BlockchainReadRequest::TxsInBlock`].
420 ///
421 /// Will return [`None`] if the request contained an index out of range.
422 TxsInBlock(Option<TxsInBlock>),
423
424 /// The response for [`BlockchainReadRequest::AltBlocksInChain`].
425 ///
426 /// Contains all the alt blocks in the alt-chain in chronological order.
427 AltBlocksInChain(Vec<AltBlockInformation>),
428
429 /// Response to:
430 /// - [`BlockchainReadRequest::Block`].
431 /// - [`BlockchainReadRequest::BlockByHash`].
432 Block(Block),
433
434 /// Response to [`BlockchainReadRequest::TotalTxCount`].
435 TotalTxCount(usize),
436
437 /// Response to [`BlockchainReadRequest::DatabaseSize`].
438 DatabaseSize {
439 /// The size of the database file in bytes.
440 database_size: u64,
441 /// The amount of free bytes there are
442 /// the disk where the database is located.
443 free_space: u64,
444 },
445
446 /// Response to [`BlockchainReadRequest::PreRctOutputDistribution`].
447 PreRctOutputDistribution(Vec<OutputDistributionData>),
448
449 /// Response to [`BlockchainReadRequest::OutputHistogram`].
450 OutputHistogram(Vec<OutputHistogramEntry>),
451
452 /// Response to [`BlockchainReadRequest::CoinbaseTxSum`].
453 CoinbaseTxSum(CoinbaseTxSum),
454
455 /// Response to [`BlockchainReadRequest::AltChains`].
456 AltChains(Vec<ChainInfo>),
457
458 /// Response to [`BlockchainReadRequest::AltChainCount`].
459 AltChainCount(usize),
460
461 /// Response to [`BlockchainReadRequest::Transactions`].
462 Transactions {
463 /// The transaction blobs found.
464 txs: Vec<TxInBlockchain>,
465 /// The hashes of any transactions that could not be found.
466 missed_txs: Vec<[u8; 32]>,
467 },
468
469 /// Response to [`BlockchainReadRequest::TotalRctOutputs`].
470 TotalRctOutputs(u64),
471
472 /// Response to [`BlockchainReadRequest::TxOutputIndexes`].
473 TxOutputIndexes(Vec<u64>),
474
475 //------------------------------------------------------ Writes
476 /// A generic Ok response to indicate a request was successfully handled.
477 ///
478 /// currently the response for:
479 /// - [`BlockchainWriteRequest::WriteBlock`]
480 /// - [`BlockchainWriteRequest::WriteAltBlock`]
481 /// - [`BlockchainWriteRequest::FlushAltBlocks`]
482 Ok,
483
484 /// Response to [`BlockchainWriteRequest::PopBlocks`].
485 ///
486 /// The inner value is the alt-chain ID for the old main chain blocks.
487 PopBlocks(Option<ChainId>),
488}
489
490//---------------------------------------------------------------------------------------------------- Tests
491#[cfg(test)]
492mod test {
493 // use super::*;
494}