dusk_node/
database.rs

1// This Source Code Form is subject to the terms of the Mozilla Public
2// License, v. 2.0. If a copy of the MPL was not distributed with this
3// file, You can obtain one at http://mozilla.org/MPL/2.0/.
4//
5// Copyright (c) DUSK NETWORK. All rights reserved.
6
7use std::collections::HashSet;
8use std::path::Path;
9
10pub mod rocksdb;
11
12use anyhow::Result;
13use node_data::ledger::{
14    Block, Fault, Header, Label, SpendingId, SpentTransaction, Transaction,
15};
16use node_data::message::{payload, ConsensusHeader};
17use serde::{Deserialize, Serialize};
18
19pub struct LightBlock {
20    pub header: Header,
21    pub transactions_ids: Vec<[u8; 32]>,
22    pub faults_ids: Vec<[u8; 32]>,
23}
24
25pub trait DB: Send + Sync + 'static {
26    type P<'a>: Persist;
27
28    /// Creates or open a database located at this path.
29    ///
30    /// Panics if opening db or creating one fails.
31    fn create_or_open<T>(path: T, opts: DatabaseOptions) -> Self
32    where
33        T: AsRef<Path>;
34
35    /// Provides a managed execution of a read-only isolated transaction.
36    fn view<F, T>(&self, f: F) -> T
37    where
38        F: for<'a> FnOnce(&Self::P<'a>) -> T;
39
40    /// Provides a managed execution of a read-write atomic transaction.
41    ///
42    /// An atomic transaction is an indivisible and irreducible series of
43    /// database operations such that either all occur, or nothing occurs.
44    ///
45    /// Transaction commit will happen only if no error is returned by `fn`
46    /// and no panic is raised on `fn` execution.
47    fn update<F, T>(&self, f: F) -> Result<T>
48    where
49        F: for<'a> FnOnce(&mut Self::P<'a>) -> Result<T>;
50
51    fn update_dry_run<F, T>(&self, dry_run: bool, f: F) -> Result<T>
52    where
53        F: for<'a> FnOnce(&mut Self::P<'a>) -> Result<T>;
54
55    fn close(&mut self);
56}
57
58/// Implements both read-write and read-only transactions to DB.
59
60pub trait Ledger {
61    /// Read-write transactions
62    /// Returns disk footprint of the committed transaction
63    fn store_block(
64        &mut self,
65        header: &Header,
66        txs: &[SpentTransaction],
67        faults: &[Fault],
68        label: Label,
69    ) -> Result<usize>;
70
71    fn delete_block(&mut self, b: &Block) -> Result<()>;
72    fn block_header(&self, hash: &[u8]) -> Result<Option<Header>>;
73
74    fn light_block(&self, hash: &[u8]) -> Result<Option<LightBlock>>;
75
76    fn block(&self, hash: &[u8]) -> Result<Option<Block>>;
77    fn block_hash_by_height(&self, height: u64) -> Result<Option<[u8; 32]>>;
78    fn block_by_height(&self, height: u64) -> Result<Option<Block>>;
79
80    fn block_exists(&self, hash: &[u8]) -> Result<bool>;
81
82    fn ledger_tx(&self, tx_id: &[u8]) -> Result<Option<SpentTransaction>>;
83    fn ledger_txs(
84        &self,
85        tx_ids: Vec<&[u8; 32]>,
86    ) -> Result<Vec<SpentTransaction>>;
87
88    fn ledger_tx_exists(&self, tx_id: &[u8]) -> Result<bool>;
89
90    fn block_label_by_height(
91        &self,
92        height: u64,
93    ) -> Result<Option<([u8; 32], Label)>>;
94
95    fn store_block_label(
96        &mut self,
97        height: u64,
98        hash: &[u8; 32],
99        label: Label,
100    ) -> Result<()>;
101
102    fn faults_by_block(&self, start_height: u64) -> Result<Vec<Fault>>;
103    fn faults(&self, faults_ids: &[[u8; 32]]) -> Result<Vec<Fault>>;
104}
105
106pub trait ConsensusStorage {
107    /// Candidate Storage
108    fn store_candidate(&mut self, cm: Block) -> Result<()>;
109    fn candidate(&self, hash: &[u8]) -> Result<Option<Block>>;
110
111    /// Fetches a candidate block by lookup key (prev_block_hash, iteration).
112    fn candidate_by_iteration(
113        &self,
114        ch: &ConsensusHeader,
115    ) -> Result<Option<Block>>;
116
117    fn clear_candidates(&mut self) -> Result<()>;
118
119    fn delete_candidate<F>(&mut self, closure: F) -> Result<()>
120    where
121        F: FnOnce(u64) -> bool + std::marker::Copy;
122
123    fn count_candidates(&self) -> usize;
124
125    /// ValidationResult Storage
126    fn store_validation_result(
127        &mut self,
128        ch: &ConsensusHeader,
129        vr: &payload::ValidationResult,
130    ) -> Result<()>;
131
132    fn validation_result(
133        &self,
134        ch: &ConsensusHeader,
135    ) -> Result<Option<payload::ValidationResult>>;
136
137    fn clear_validation_results(&mut self) -> Result<()>;
138
139    fn delete_validation_results<F>(&mut self, closure: F) -> Result<()>
140    where
141        F: FnOnce([u8; 32]) -> bool + std::marker::Copy;
142
143    fn count_validation_results(&self) -> usize;
144}
145
146pub trait Mempool {
147    /// Adds a transaction to the mempool with a timestamp.
148    fn store_mempool_tx(
149        &mut self,
150        tx: &Transaction,
151        timestamp: u64,
152    ) -> Result<()>;
153
154    /// Gets a transaction from the mempool.
155    fn mempool_tx(&self, tx_id: [u8; 32]) -> Result<Option<Transaction>>;
156
157    /// Checks if a transaction exists in the mempool.
158    fn mempool_tx_exists(&self, tx_id: [u8; 32]) -> Result<bool>;
159
160    /// Deletes a transaction from the mempool.
161    ///
162    /// If `cascade` is true, all dependant transactions are deleted
163    ///
164    /// Return a vector with all the deleted tx_id
165    fn delete_mempool_tx(
166        &mut self,
167        tx_id: [u8; 32],
168        cascade: bool,
169    ) -> Result<Vec<[u8; 32]>>;
170
171    /// Get transactions hash from the mempool, searching by spendable ids
172    fn mempool_txs_by_spendable_ids(
173        &self,
174        n: &[SpendingId],
175    ) -> HashSet<[u8; 32]>;
176
177    /// Get an iterator over the mempool transactions sorted by gas price
178    fn mempool_txs_sorted_by_fee(
179        &self,
180    ) -> Result<Box<dyn Iterator<Item = Transaction> + '_>>;
181
182    /// Get an iterator over the mempool transactions hash by gas price
183    fn mempool_txs_ids_sorted_by_fee(
184        &self,
185    ) -> Result<Box<dyn Iterator<Item = (u64, [u8; 32])> + '_>>;
186
187    /// Get an iterator over the mempool transactions hash by gas price (asc)
188    fn mempool_txs_ids_sorted_by_low_fee(
189        &self,
190    ) -> Result<Box<dyn Iterator<Item = (u64, [u8; 32])> + '_>>;
191
192    /// Get all transactions hashes.
193    fn mempool_txs_ids(&self) -> Result<Vec<[u8; 32]>>;
194
195    /// Get all expired transactions.
196    fn mempool_expired_txs(&self, timestamp: u64) -> Result<Vec<[u8; 32]>>;
197
198    /// Number of persisted transactions
199    fn mempool_txs_count(&self) -> usize;
200}
201
202pub trait Metadata {
203    /// Assigns an value to a key in the Metadata CF
204    fn op_write<T: AsRef<[u8]>>(&mut self, key: &[u8], value: T) -> Result<()>;
205
206    /// Reads an value of a key from the Metadata CF
207    fn op_read(&self, key: &[u8]) -> Result<Option<Vec<u8>>>;
208}
209
210pub trait Persist:
211    Ledger + ConsensusStorage + Mempool + Metadata + core::fmt::Debug
212{
213    // Candidate block functions
214
215    fn clear_database(&mut self) -> Result<()>;
216    fn commit(self) -> Result<()>;
217    fn rollback(self) -> Result<()>;
218}
219
220pub fn into_array<const N: usize>(value: &[u8]) -> [u8; N] {
221    let mut res = [0u8; N];
222    res.copy_from_slice(&value[0..N]);
223    res
224}
225
226#[derive(Serialize, Deserialize, Clone, Debug)]
227pub struct DatabaseOptions {
228    /// Max write buffer size per Blocks-related CF. By default, there are two
229    /// write buffers (MemTables) per CF.
230    pub blocks_cf_max_write_buffer_size: usize,
231
232    /// Disables Block Cache for non-Mempool CFs
233    ///
234    /// Block Cache is useful in optimizing DB reads. For
235    /// non-block-explorer nodes, DB reads for block retrieval should
236    /// not be buffered in memory.
237    pub blocks_cf_disable_block_cache: bool,
238
239    /// Max write buffer size per Mempool CF.
240    pub mempool_cf_max_write_buffer_size: usize,
241
242    /// Enables a set of flags for collecting DB stats as log data.
243    pub enable_debug: bool,
244
245    /// Create the database if missing
246    pub create_if_missing: bool,
247}
248
249impl Default for DatabaseOptions {
250    fn default() -> Self {
251        Self {
252            blocks_cf_max_write_buffer_size: 1024 * 1024, // 1 MiB
253            mempool_cf_max_write_buffer_size: 10 * 1024 * 1024, // 10 MiB
254            blocks_cf_disable_block_cache: true,
255            enable_debug: false,
256            create_if_missing: true,
257        }
258    }
259}