1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
// Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0

use crate::{CryptoStorage, Error, GetResponse, KVStorage, PublicKeyResponse};
use diem_crypto::{
    ed25519::{Ed25519PrivateKey, Ed25519PublicKey, Ed25519Signature},
    hash::CryptoHash,
};
use serde::{de::DeserializeOwned, Serialize};

pub const NAMESPACE_SEPARATOR: &str = "/";

/// This provides a light wrapper around KV storages to support a namespace. That namespace is
/// effectively prefixing all keys with then namespace value and "/" so a namespace of foo and a
/// key of bar becomes "foo/bar". Without a namespace, the key would just be "bar".
pub struct Namespaced<S> {
    namespace: String,
    inner: S,
}

impl<S> Namespaced<S> {
    pub fn new<N: Into<String>>(namespace: N, inner: S) -> Self {
        Self {
            namespace: namespace.into(),
            inner,
        }
    }

    pub fn inner(&self) -> &S {
        &self.inner
    }

    pub fn inner_mut(&mut self) -> &mut S {
        &mut self.inner
    }

    pub fn into_inner(self) -> S {
        self.inner
    }

    pub fn namespace(&self) -> &str {
        &self.namespace
    }

    fn namespaced(&self, name: &str) -> String {
        format!("{}{}{}", self.namespace, NAMESPACE_SEPARATOR, name)
    }
}

impl<'a, S> Namespaced<&'a S>
where
    S: KVStorage,
{
    /// This is a small hack in order to allow for calling KVStorage::get from a Namespaced created
    /// from an `&S` and not an `S`
    pub fn get<T: DeserializeOwned>(&self, key: &str) -> Result<GetResponse<T>, Error> {
        self.inner.get(&self.namespaced(key))
    }
}

impl<S: KVStorage> KVStorage for Namespaced<S> {
    fn available(&self) -> Result<(), Error> {
        self.inner.available()
    }

    fn get<T: DeserializeOwned>(&self, key: &str) -> Result<GetResponse<T>, Error> {
        self.inner.get(&self.namespaced(key))
    }

    fn set<T: Serialize>(&mut self, key: &str, value: T) -> Result<(), Error> {
        self.inner.set(&self.namespaced(key), value)
    }

    /// Note: This is not a namespace function
    #[cfg(any(test, feature = "testing"))]
    fn reset_and_clear(&mut self) -> Result<(), Error> {
        self.inner.reset_and_clear()
    }
}

impl<S: CryptoStorage> CryptoStorage for Namespaced<S> {
    fn create_key(&mut self, name: &str) -> Result<Ed25519PublicKey, Error> {
        self.inner.create_key(&self.namespaced(name))
    }

    fn export_private_key(&self, name: &str) -> Result<Ed25519PrivateKey, Error> {
        self.inner.export_private_key(&self.namespaced(name))
    }

    fn import_private_key(&mut self, name: &str, key: Ed25519PrivateKey) -> Result<(), Error> {
        self.inner.import_private_key(&self.namespaced(name), key)
    }

    fn export_private_key_for_version(
        &self,
        name: &str,
        version: Ed25519PublicKey,
    ) -> Result<Ed25519PrivateKey, Error> {
        self.inner
            .export_private_key_for_version(&self.namespaced(name), version)
    }

    fn get_public_key(&self, name: &str) -> Result<PublicKeyResponse, Error> {
        self.inner.get_public_key(&self.namespaced(name))
    }

    fn get_public_key_previous_version(&self, name: &str) -> Result<Ed25519PublicKey, Error> {
        self.inner
            .get_public_key_previous_version(&self.namespaced(name))
    }

    fn rotate_key(&mut self, name: &str) -> Result<Ed25519PublicKey, Error> {
        self.inner.rotate_key(&self.namespaced(name))
    }

    fn sign<T: CryptoHash + Serialize>(
        &self,
        name: &str,
        message: &T,
    ) -> Result<Ed25519Signature, Error> {
        self.inner.sign(&self.namespaced(name), message)
    }

    fn sign_using_version<T: CryptoHash + Serialize>(
        &self,
        name: &str,
        version: Ed25519PublicKey,
        message: &T,
    ) -> Result<Ed25519Signature, Error> {
        self.inner
            .sign_using_version(&self.namespaced(name), version, message)
    }
}

#[cfg(test)]
mod test {
    use super::*;
    use crate::OnDiskStorage;
    use diem_temppath::TempPath;

    #[test]
    fn test_different_namespaces() {
        let ns0 = "ns0";
        let ns1 = "ns1";
        let key = "key";

        let path_buf = TempPath::new().path().to_path_buf();

        let mut default = OnDiskStorage::new(path_buf.clone());
        let mut nss0 = Namespaced::new(ns0, OnDiskStorage::new(path_buf.clone()));
        let mut nss1 = Namespaced::new(ns1, OnDiskStorage::new(path_buf));

        default.set(key, 0).unwrap();
        nss0.set(key, 1).unwrap();
        nss1.set(key, 2).unwrap();

        assert_eq!(default.get::<u64>(key).unwrap().value, 0);
        assert_eq!(nss0.get::<u64>(key).unwrap().value, 1);
        assert_eq!(nss1.get::<u64>(key).unwrap().value, 2);
    }

    #[test]
    fn test_shared_namespace() {
        let ns = "ns";
        let key = "key";

        let path_buf = TempPath::new().path().to_path_buf();

        let default = OnDiskStorage::new(path_buf.clone());
        let mut nss = Namespaced::new(ns, OnDiskStorage::new(path_buf.clone()));
        let another_nss = Namespaced::new(ns, OnDiskStorage::new(path_buf));

        nss.set(key, 1).unwrap();
        default.get::<u64>(key).unwrap_err();
        assert_eq!(nss.get::<u64>(key).unwrap().value, 1);
        assert_eq!(another_nss.get::<u64>(key).unwrap().value, 1);
    }
}