2016-11-03 09:19:35 -07:00
|
|
|
use std::sync::Arc;
|
2016-11-04 04:08:58 -07:00
|
|
|
use std::path::PathBuf;
|
2016-11-24 22:58:04 -08:00
|
|
|
use std::fs::create_dir_all;
|
2016-11-03 09:19:35 -07:00
|
|
|
use app_dirs::{app_dir, AppDataType};
|
|
|
|
use {db, APP_INFO};
|
2016-11-07 01:15:15 -08:00
|
|
|
use config::Config;
|
2016-11-03 09:19:35 -07:00
|
|
|
|
2016-11-21 00:52:27 -08:00
|
|
|
pub fn open_db(cfg: &Config) -> db::SharedStore {
|
2016-11-24 22:58:04 -08:00
|
|
|
let db_path = match cfg.data_dir {
|
|
|
|
Some(ref data_dir) => custom_path(&data_dir, "db"),
|
|
|
|
None => app_dir(AppDataType::UserData, &APP_INFO, "db").expect("Failed to get app dir"),
|
|
|
|
};
|
2016-11-21 00:52:27 -08:00
|
|
|
Arc::new(db::Storage::with_cache(db_path, cfg.db_cache).expect("Failed to open database"))
|
2016-11-03 09:19:35 -07:00
|
|
|
}
|
|
|
|
|
2016-11-24 22:58:04 -08:00
|
|
|
pub fn node_table_path(cfg: &Config) -> PathBuf {
|
|
|
|
let mut node_table = match cfg.data_dir {
|
|
|
|
Some(ref data_dir) => custom_path(&data_dir, "p2p"),
|
|
|
|
None => app_dir(AppDataType::UserData, &APP_INFO, "p2p").expect("Failed to get app dir"),
|
|
|
|
};
|
2016-11-04 04:08:58 -07:00
|
|
|
node_table.push("nodes.csv");
|
|
|
|
node_table
|
|
|
|
}
|
|
|
|
|
2016-11-17 10:37:45 -08:00
|
|
|
pub fn init_db(cfg: &Config, db: &db::SharedStore) -> Result<(), String> {
|
2016-11-03 09:19:35 -07:00
|
|
|
// insert genesis block if db is empty
|
2016-11-07 01:15:15 -08:00
|
|
|
let genesis_block = cfg.magic.genesis_block();
|
|
|
|
match db.block_hash(0) {
|
2016-11-07 02:20:27 -08:00
|
|
|
Some(ref db_genesis_block_hash) if db_genesis_block_hash != &genesis_block.hash() => Err("Trying to open database with incompatible genesis block".into()),
|
|
|
|
Some(_) => Ok(()),
|
|
|
|
None => {
|
|
|
|
db.insert_block(&genesis_block).expect("Failed to insert genesis block to the database");
|
|
|
|
Ok(())
|
|
|
|
}
|
2016-11-03 09:19:35 -07:00
|
|
|
}
|
|
|
|
}
|
2016-11-24 22:58:04 -08:00
|
|
|
|
|
|
|
fn custom_path(data_dir: &str, sub_dir: &str) -> PathBuf {
|
|
|
|
let mut path = PathBuf::from(data_dir);
|
|
|
|
path.push(sub_dir);
|
|
|
|
if let Err(e) = create_dir_all(&path) {
|
|
|
|
panic!("Failed to get app dir: {}", e);
|
|
|
|
}
|
|
|
|
path
|
|
|
|
}
|