/
recovery.rs
172 lines (163 loc) · 6.52 KB
/
recovery.rs
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
// Copyright 2020. The Tari Project
//
// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
// following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following
// disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
// following disclaimer in the documentation and/or other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote
// products derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
use std::{
env::temp_dir,
fs,
io::{self, Write},
sync::Arc,
};
use anyhow::anyhow;
use log::*;
use tari_common::{
configuration::Network,
exit_codes::{ExitCode, ExitError},
};
use tari_core::{
chain_storage::{
async_db::AsyncBlockchainDb,
create_lmdb_database,
create_recovery_lmdb_database,
BlockchainBackend,
BlockchainDatabase,
BlockchainDatabaseConfig,
Validators,
},
consensus::ConsensusManager,
proof_of_work::randomx_factory::RandomXFactory,
transactions::CryptoFactories,
validation::{
block_validators::{BodyOnlyValidator, OrphanBlockValidator},
header_validator::HeaderValidator,
mocks::MockValidator,
DifficultyCalculator,
},
};
use crate::config::{BaseNodeConfig, DatabaseType};
pub const LOG_TARGET: &str = "base_node::app";
pub fn initiate_recover_db(config: &BaseNodeConfig) -> Result<(), ExitError> {
// create recovery db
match &config.db_type {
DatabaseType::Lmdb => {
create_recovery_lmdb_database(config.lmdb_path.as_path()).map_err(|err| {
error!(target: LOG_TARGET, "{}", err);
ExitError::new(ExitCode::UnknownError, err)
})?;
},
};
Ok(())
}
pub async fn run_recovery(node_config: &BaseNodeConfig) -> Result<(), anyhow::Error> {
println!("Starting recovery mode");
let rules = ConsensusManager::builder(node_config.network).build();
let (temp_db, main_db, temp_path) = match &node_config.db_type {
DatabaseType::Lmdb => {
let backend = create_lmdb_database(&node_config.lmdb_path, node_config.lmdb.clone(), rules.clone())
.map_err(|e| {
error!(target: LOG_TARGET, "Error opening db: {}", e);
anyhow!("Could not open DB: {}", e)
})?;
let temp_path = temp_dir().join("temp_recovery");
let temp = create_lmdb_database(&temp_path, node_config.lmdb.clone(), rules.clone()).map_err(|e| {
error!(target: LOG_TARGET, "Error opening recovery db: {}", e);
anyhow!("Could not open recovery DB: {}", e)
})?;
(temp, backend, temp_path)
},
};
let factories = CryptoFactories::default();
let randomx_factory = RandomXFactory::new(node_config.max_randomx_vms);
let validators = Validators::new(
BodyOnlyValidator::new(rules.clone()),
HeaderValidator::new(rules.clone()),
OrphanBlockValidator::new(
rules.clone(),
node_config.bypass_range_proof_verification,
factories.clone(),
),
);
let mut config = node_config.storage;
config.cleanup_orphans_at_startup = true;
let db = BlockchainDatabase::new(
main_db,
rules.clone(),
validators,
node_config.storage,
DifficultyCalculator::new(rules, randomx_factory),
)?;
do_recovery(db.into(), temp_db).await?;
info!(
target: LOG_TARGET,
"Node has completed recovery mode, it will try to cleanup the db"
);
fs::remove_dir_all(&temp_path).map_err(|e| {
error!(target: LOG_TARGET, "Error opening recovery db: {}", e);
anyhow!("Could not open recovery DB: {}", e)
})
}
// Function to handle the recovery attempt of the db
async fn do_recovery<D: BlockchainBackend + 'static>(
db: AsyncBlockchainDb<D>,
source_backend: D,
) -> Result<(), anyhow::Error> {
// We dont care about the values, here, so we just use mock validators, and a mainnet CM.
let rules = ConsensusManager::builder(Network::LocalNet).build();
let validators = Validators::new(
MockValidator::new(true),
MockValidator::new(true),
MockValidator::new(true),
);
let source_database = BlockchainDatabase::new(
source_backend,
rules.clone(),
validators,
BlockchainDatabaseConfig::default(),
DifficultyCalculator::new(rules, Default::default()),
)?;
let max_height = source_database
.get_chain_metadata()
.map_err(|e| anyhow!("Could not get max chain height: {}", e))?
.height_of_longest_chain();
// we start at height 1
let mut counter = 1;
print!("Starting recovery at height: ");
loop {
print!("{}", counter);
io::stdout().flush().unwrap();
trace!(target: LOG_TARGET, "Asking for block with height: {}", counter);
let block = source_database
.fetch_block(counter)
.map_err(|e| anyhow!("Could not get block from recovery db: {}", e))?
.try_into_block()?;
trace!(target: LOG_TARGET, "Adding block: {}", block);
db.add_block(Arc::new(block))
.await
.map_err(|e| anyhow!("Stopped recovery at height {}, reason: {}", counter, e))?;
if counter >= max_height {
info!(target: LOG_TARGET, "Done with recovery, chain height {}", counter);
break;
}
print!("\x1B[{}D\x1B[K", counter.to_string().len());
counter += 1;
}
Ok(())
}