diem_config/config/
secure_backend_config.rs

1// Copyright (c) The Diem Core Contributors
2// SPDX-License-Identifier: Apache-2.0
3
4// Copyright 2021 Conflux Foundation. All rights reserved.
5// Conflux is free software and distributed under GNU General Public License.
6// See http://www.gnu.org/licenses/
7
8use diem_secure_storage::{
9    InMemoryStorage, NamespacedStorage, OnDiskStorage, Storage,
10};
11use serde::{Deserialize, Serialize};
12use std::path::PathBuf;
13
14#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
15#[serde(rename_all = "snake_case", tag = "type")]
16pub enum SecureBackend {
17    InMemoryStorage,
18    OnDiskStorage(OnDiskStorageConfig),
19}
20
21#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
22#[serde(deny_unknown_fields)]
23pub struct OnDiskStorageConfig {
24    // Required path for on disk storage
25    pub path: PathBuf,
26    /// A namespace is an optional portion of the path to a key stored within
27    /// OnDiskStorage. For example, a key, S, without a namespace would be
28    /// available in S, with a namespace, N, it would be in N/S.
29    pub namespace: Option<String>,
30    #[serde(skip)]
31    data_dir: PathBuf,
32}
33
34impl Default for OnDiskStorageConfig {
35    fn default() -> Self {
36        Self {
37            namespace: None,
38            path: PathBuf::from("secure_storage.json"),
39            data_dir: PathBuf::from("/opt/diem/data"),
40        }
41    }
42}
43
44impl OnDiskStorageConfig {
45    pub fn path(&self) -> PathBuf {
46        if self.path.is_relative() {
47            self.data_dir.join(&self.path)
48        } else {
49            self.path.clone()
50        }
51    }
52
53    pub fn set_data_dir(&mut self, data_dir: PathBuf) {
54        self.data_dir = data_dir;
55    }
56}
57
58impl From<&SecureBackend> for Storage {
59    fn from(backend: &SecureBackend) -> Self {
60        match backend {
61            SecureBackend::InMemoryStorage => {
62                Storage::from(InMemoryStorage::new())
63            }
64            SecureBackend::OnDiskStorage(config) => {
65                let storage = Storage::from(OnDiskStorage::new(config.path()));
66                if let Some(namespace) = &config.namespace {
67                    Storage::from(NamespacedStorage::new(
68                        storage,
69                        namespace.clone(),
70                    ))
71                } else {
72                    storage
73                }
74            }
75        }
76    }
77}