diff options
Diffstat (limited to 'src/schema.rs')
| -rw-r--r-- | src/schema.rs | 47 |
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}; | |||
| 15 | use std::fmt; | 15 | use std::fmt; |
| 16 | use std::fs; | 16 | use std::fs; |
| 17 | use std::sync::Arc; | 17 | use std::sync::Arc; |
| 18 | 18 | use std::io; | |
| 19 | use std::vec::Vec; | ||
| 20 | use std::string::String; | ||
| 21 | use std::path::PathBuf; | ||
| 19 | // use crate::validators; | 22 | // use crate::validators; |
| 20 | 23 | ||
| 21 | pub type PublicKeySignature = String; | 24 | pub type PublicKeySignature = String; |
| 22 | 25 | ||
| 26 | |||
| 27 | fn 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 | |||
| 38 | fn 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 | |||
| 53 | fn 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 |
| 24 | pub fn create_database() -> Db { | 62 | pub 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 |
