sawtooth/journal/chain_id_manager.rs
1/*
2 * Copyright 2018 Intel Corporation
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 * ------------------------------------------------------------------------------
16 */
17use std::fs::File;
18use std::io;
19use std::io::prelude::*;
20use std::path::PathBuf;
21
22/// The ChainIdManager is in charge of of keeping track of the block-chain-id
23/// stored in the data_dir.
24#[derive(Clone, Debug)]
25pub struct ChainIdManager {
26 data_dir: String,
27}
28
29impl ChainIdManager {
30 pub fn new(data_dir: String) -> Self {
31 ChainIdManager { data_dir }
32 }
33
34 pub fn save_block_chain_id(&self, block_chain_id: &str) -> Result<(), io::Error> {
35 let mut path = PathBuf::new();
36 path.push(&self.data_dir);
37 path.push("block-chain-id");
38
39 let mut file = File::create(path)?;
40 file.write_all(block_chain_id.as_bytes())
41 }
42
43 pub fn get_block_chain_id(&self) -> Result<Option<String>, io::Error> {
44 let mut path = PathBuf::new();
45 path.push(&self.data_dir);
46 path.push("block-chain-id");
47
48 match File::open(path) {
49 Ok(mut file) => {
50 let mut contents = String::new();
51 file.read_to_string(&mut contents)?;
52 Ok(Some(contents))
53 }
54 Err(ref err) if err.kind() == io::ErrorKind::NotFound => Ok(None),
55 Err(err) => Err(err),
56 }
57 }
58}