summaryrefslogtreecommitdiffstats
path: root/src
diff options
context:
space:
mode:
authoralpaylan2021-04-14 18:40:26 +0300
committeralpaylan2021-04-14 18:40:26 +0300
commita5d5ab88d3f73d0b6f5fa847df6dace90810313d (patch)
treeeefa5cdd954179336a47a6897d3be5137542d48b /src
parent85b29df4208b83c1949032db56c8d76e8c76b705 (diff)
downloadgradecoin-a5d5ab88d3f73d0b6f5fa847df6dace90810313d.tar.gz
gradecoin-a5d5ab88d3f73d0b6f5fa847df6dace90810313d.tar.bz2
gradecoin-a5d5ab88d3f73d0b6f5fa847df6dace90810313d.zip
recover database from file.
Diffstat (limited to 'src')
-rw-r--r--src/schema.rs47
1 files changed, 45 insertions, 2 deletions
diff --git a/src/schema.rs b/src/schema.rs
index 65150c1..9e157c7 100644
--- a/src/schema.rs
+++ b/src/schema.rs
@@ -15,16 +15,59 @@ use std::collections::{HashMap, HashSet};
15use std::fmt; 15use std::fmt;
16use std::fs; 16use std::fs;
17use std::sync::Arc; 17use std::sync::Arc;
18 18use std::io;
19use std::vec::Vec;
20use std::string::String;
21use std::path::PathBuf;
19// use crate::validators; 22// use crate::validators;
20 23
21pub type PublicKeySignature = String; 24pub type PublicKeySignature = String;
22 25
26
27fn last_block_exists() -> (bool, String) {
28 let blocks = read_block_name().unwrap();
29 for block in blocks {
30 let block = block.to_str().unwrap();
31 if block.contains("last.block") {
32 return (true, block.to_string());
33 }
34 }
35 (false, "".to_string())
36}
37
38fn read_block_name() -> io::Result<Vec<PathBuf>> {
39 let mut entries = fs::read_dir("./blocks")?
40 .map(|res| res.map(|e| e.path()))
41 .collect::<Result<Vec<_>, io::Error>>()?;
42
43 // The order in which `read_dir` returns entries is not guaranteed. If reproducible
44 // ordering is required the entries should be explicitly sorted.
45
46 entries.sort();
47
48 // The entries have now been sorted by their path.
49
50 Ok(entries)
51}
52
53fn create_db_with_last_block(path: String) -> Db {
54 let file = fs::read(path).unwrap();
55 let json = std::str::from_utf8(&file).unwrap();
56 let block: Block = serde_json::from_str(json).unwrap();
57 let db = Db::new();
58 *db.blockchain.write() = block;
59 return db;
60}
23/// Creates a new database 61/// Creates a new database
24pub fn create_database() -> Db { 62pub fn create_database() -> Db {
25 fs::create_dir_all("blocks").unwrap(); 63 fs::create_dir_all("blocks").unwrap();
26 fs::create_dir_all("users").unwrap(); 64 fs::create_dir_all("users").unwrap();
27 Db::new() 65 let (res, path) = last_block_exists();
66 if res {
67 return create_db_with_last_block(path);
68 } else {
69 return Db::new();
70 }
28} 71}
29 72
30/// A JWT Payload/Claims representation 73/// A JWT Payload/Claims representation