1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
#[cfg(test)]
mod consensusdb_test;
mod schema;
use crate::{
consensusdb::schema::{
block::BlockSchema,
quorum_certificate::QCSchema,
single_entry::{SingleEntryKey, SingleEntrySchema},
},
error::DbError,
};
use anyhow::Result;
use consensus_types::{block::Block, quorum_cert::QuorumCert};
use diem_crypto::HashValue;
use diem_logger::prelude::*;
use schema::{BLOCK_CF_NAME, QC_CF_NAME, SINGLE_ENTRY_CF_NAME};
use schemadb::{Options, ReadOptions, SchemaBatch, DB, DEFAULT_CF_NAME};
use std::{collections::HashMap, iter::Iterator, path::Path, time::Instant};
pub struct ConsensusDB {
db: DB,
}
impl ConsensusDB {
pub fn new<P: AsRef<Path> + Clone>(db_root_path: P) -> Self {
let column_families = vec![
DEFAULT_CF_NAME,
BLOCK_CF_NAME,
QC_CF_NAME,
SINGLE_ENTRY_CF_NAME,
];
let path = db_root_path.as_ref().join("consensusdb");
let instant = Instant::now();
let mut opts = Options::default();
opts.create_if_missing(true);
opts.create_missing_column_families(true);
let db = DB::open(path.clone(), "consensus", column_families, &opts)
.expect("ConsensusDB open failed; unable to continue");
info!(
"Opened ConsensusDB at {:?} in {} ms",
path,
instant.elapsed().as_millis()
);
Self { db }
}
pub fn get_data(
&self,
) -> Result<(
Option<Vec<u8>>,
Option<Vec<u8>>,
Option<Vec<u8>>,
Vec<Block>,
Vec<QuorumCert>,
)> {
let last_vote = self.get_last_vote()?;
let highest_timeout_certificate = self.get_highest_timeout_certificate()?;
let highest_2chain_timeout_certificate = self.get_highest_2chain_timeout_certificate()?;
let consensus_blocks = self
.get_blocks()?
.into_iter()
.map(|(_block_hash, block_content)| block_content)
.collect::<Vec<_>>();
let consensus_qcs = self
.get_quorum_certificates()?
.into_iter()
.map(|(_block_hash, qc)| qc)
.collect::<Vec<_>>();
Ok((
last_vote,
highest_timeout_certificate,
highest_2chain_timeout_certificate,
consensus_blocks,
consensus_qcs,
))
}
pub fn save_highest_timeout_certificate(
&self,
highest_timeout_certificate: Vec<u8>,
) -> Result<(), DbError> {
let mut batch = SchemaBatch::new();
batch.put::<SingleEntrySchema>(
&SingleEntryKey::HighestTimeoutCertificate,
&highest_timeout_certificate,
)?;
self.commit(batch)?;
Ok(())
}
pub fn save_highest_2chain_timeout_certificate(&self, tc: Vec<u8>) -> Result<(), DbError> {
let mut batch = SchemaBatch::new();
batch.put::<SingleEntrySchema>(&SingleEntryKey::Highest2ChainTimeoutCert, &tc)?;
self.commit(batch)?;
Ok(())
}
pub fn save_vote(&self, last_vote: Vec<u8>) -> Result<(), DbError> {
let mut batch = SchemaBatch::new();
batch.put::<SingleEntrySchema>(&SingleEntryKey::LastVoteMsg, &last_vote)?;
self.commit(batch)
}
pub fn save_blocks_and_quorum_certificates(
&self,
block_data: Vec<Block>,
qc_data: Vec<QuorumCert>,
) -> Result<(), DbError> {
if block_data.is_empty() && qc_data.is_empty() {
return Err(anyhow::anyhow!("Consensus block and qc data is empty!").into());
}
let mut batch = SchemaBatch::new();
block_data
.iter()
.try_for_each(|block| batch.put::<BlockSchema>(&block.id(), block))?;
qc_data
.iter()
.try_for_each(|qc| batch.put::<QCSchema>(&qc.certified_block().id(), qc))?;
self.commit(batch)
}
pub fn delete_blocks_and_quorum_certificates(
&self,
block_ids: Vec<HashValue>,
) -> Result<(), DbError> {
if block_ids.is_empty() {
return Err(anyhow::anyhow!("Consensus block ids is empty!").into());
}
let mut batch = SchemaBatch::new();
block_ids.iter().try_for_each(|hash| {
batch.delete::<BlockSchema>(hash)?;
batch.delete::<QCSchema>(hash)
})?;
self.commit(batch)
}
fn commit(&self, batch: SchemaBatch) -> Result<(), DbError> {
self.db.write_schemas(batch)?;
Ok(())
}
fn get_highest_timeout_certificate(&self) -> Result<Option<Vec<u8>>, DbError> {
Ok(self
.db
.get::<SingleEntrySchema>(&SingleEntryKey::HighestTimeoutCertificate)?)
}
fn get_highest_2chain_timeout_certificate(&self) -> Result<Option<Vec<u8>>, DbError> {
Ok(self
.db
.get::<SingleEntrySchema>(&SingleEntryKey::Highest2ChainTimeoutCert)?)
}
pub fn delete_highest_timeout_certificate(&self) -> Result<(), DbError> {
let mut batch = SchemaBatch::new();
batch.delete::<SingleEntrySchema>(&SingleEntryKey::HighestTimeoutCertificate)?;
self.commit(batch)
}
pub fn delete_highest_2chain_timeout_certificate(&self) -> Result<(), DbError> {
let mut batch = SchemaBatch::new();
batch.delete::<SingleEntrySchema>(&SingleEntryKey::Highest2ChainTimeoutCert)?;
self.commit(batch)
}
fn get_last_vote(&self) -> Result<Option<Vec<u8>>, DbError> {
Ok(self
.db
.get::<SingleEntrySchema>(&SingleEntryKey::LastVoteMsg)?)
}
pub fn delete_last_vote_msg(&self) -> Result<(), DbError> {
let mut batch = SchemaBatch::new();
batch.delete::<SingleEntrySchema>(&SingleEntryKey::LastVoteMsg)?;
self.commit(batch)?;
Ok(())
}
fn get_blocks(&self) -> Result<HashMap<HashValue, Block>, DbError> {
let mut iter = self.db.iter::<BlockSchema>(ReadOptions::default())?;
iter.seek_to_first();
Ok(iter.collect::<Result<HashMap<HashValue, Block>>>()?)
}
fn get_quorum_certificates(&self) -> Result<HashMap<HashValue, QuorumCert>, DbError> {
let mut iter = self.db.iter::<QCSchema>(ReadOptions::default())?;
iter.seek_to_first();
Ok(iter.collect::<Result<HashMap<HashValue, QuorumCert>>>()?)
}
}