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
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
//! Keymanager interface.
use std::sync::Arc;

use tiny_keccak::{Hasher, TupleHash};

use oasis_core_keymanager::client::{KeyManagerClient as CoreKeyManagerClient, RemoteClient};
pub use oasis_core_keymanager::{
    api::KeyManagerError,
    crypto::{KeyPair, KeyPairId, SignedPublicKey, StateKey},
    policy::TrustedPolicySigners,
};
use oasis_core_runtime::{
    common::namespace::Namespace,
    consensus::{beacon::EpochTime, verifier::Verifier},
    future::block_on,
    identity::Identity,
    protocol::Protocol,
    RpcDispatcher,
};

/// Key manager interface. This is a runtime context-resident convenience
/// wrapper to the keymanager configured for the runtime.
pub(crate) struct KeyManagerClient {
    inner: Arc<dyn CoreKeyManagerClient>,
}

impl KeyManagerClient {
    /// Create a new key manager client using the default remote client from oasis-core.
    pub(crate) fn new(
        runtime_id: Namespace,
        protocol: Arc<Protocol>,
        consensus_verifier: Arc<dyn Verifier>,
        identity: Arc<Identity>,
        rpc: &mut RpcDispatcher,
        key_cache_sizes: usize,
        signers: TrustedPolicySigners,
    ) -> Self {
        let remote_client = Arc::new(RemoteClient::new_runtime(
            runtime_id,
            protocol,
            consensus_verifier,
            identity,
            key_cache_sizes,
            signers,
            vec![],
        ));

        // Setup the quote policy update handler.
        let handler_remote_client = remote_client.clone();
        rpc.set_keymanager_quote_policy_update_handler(Some(Box::new(move |policy| {
            handler_remote_client.set_quote_policy(policy);
        })));

        // Setup the status update handler.
        let handler_remote_client = remote_client.clone();
        rpc.set_keymanager_status_update_handler(Some(Box::new(move |status| {
            handler_remote_client
                .set_status(status)
                .expect("failed to update km client status");
        })));

        KeyManagerClient {
            inner: remote_client,
        }
    }

    /// Create a client proxy which will forward calls to the inner client using the given context.
    /// Only public key queries will be allowed.
    pub(crate) fn with_context(self: &Arc<Self>) -> Box<dyn KeyManager> {
        Box::new(KeyManagerClientWithContext::new(self.clone(), false)) as Box<dyn KeyManager>
    }

    /// Create a client proxy which will forward calls to the inner client using the given context.
    /// Public and private key queries will be allowed.
    pub(crate) fn with_private_context(self: &Arc<Self>) -> Box<dyn KeyManager> {
        Box::new(KeyManagerClientWithContext::new(self.clone(), true)) as Box<dyn KeyManager>
    }

    /// Clear local key cache.
    ///
    /// See the oasis-core documentation for details.
    pub(crate) fn clear_cache(&self) {
        self.inner.clear_cache()
    }

    /// Get or create named key pair.
    ///
    /// See the oasis-core documentation for details.
    pub(crate) async fn get_or_create_keys(
        &self,
        key_pair_id: KeyPairId,
    ) -> Result<KeyPair, KeyManagerError> {
        retryable(|| self.inner.get_or_create_keys(key_pair_id, 0)).await
    }

    /// Get public key for a key pair id.
    ///
    /// See the oasis-core documentation for details.
    pub(crate) async fn get_public_key(
        &self,
        key_pair_id: KeyPairId,
    ) -> Result<SignedPublicKey, KeyManagerError> {
        retryable(|| self.inner.get_public_key(key_pair_id, 0)).await
    }

    /// Get or create named ephemeral key pair for given epoch.
    ///
    /// See the oasis-core documentation for details.
    pub(crate) async fn get_or_create_ephemeral_keys(
        &self,
        key_pair_id: KeyPairId,
        epoch: EpochTime,
    ) -> Result<KeyPair, KeyManagerError> {
        retryable(|| self.inner.get_or_create_ephemeral_keys(key_pair_id, epoch)).await
    }

    /// Get ephemeral public key for an epoch and a key pair id.
    ///
    /// See the oasis-core documentation for details.
    pub(crate) async fn get_public_ephemeral_key(
        &self,
        key_pair_id: KeyPairId,
        epoch: EpochTime,
    ) -> Result<SignedPublicKey, KeyManagerError> {
        retryable(|| self.inner.get_public_ephemeral_key(key_pair_id, epoch)).await
    }
}

/// Decorator for remote method calls that can be safely retried.
async fn retryable<A>(action: A) -> Result<A::Item, A::Error>
where
    A: tokio_retry::Action,
{
    let retry_strategy = tokio_retry::strategy::ExponentialBackoff::from_millis(4)
        .max_delay(std::time::Duration::from_millis(250))
        .map(tokio_retry::strategy::jitter)
        .take(5);

    tokio_retry::Retry::spawn(retry_strategy, action).await
}

/// Key manager interface.
pub trait KeyManager {
    /// Clear local key cache.
    ///
    /// See the oasis-core documentation for details.
    fn clear_cache(&self);

    /// Get or create named key pair.
    ///
    /// See the oasis-core documentation for details. This variant of the method
    /// synchronously blocks for the result.
    fn get_or_create_keys(&self, key_pair_id: KeyPairId) -> Result<KeyPair, KeyManagerError>;

    /// Get public key for a key pair id.
    ///
    /// See the oasis-core documentation for details. This variant of the method
    /// synchronously blocks for the result.
    fn get_public_key(&self, key_pair_id: KeyPairId) -> Result<SignedPublicKey, KeyManagerError>;

    /// Get or create named ephemeral key pair for given epoch.
    ///
    /// See the oasis-core documentation for details. This variant of the method
    /// synchronously blocks for the result.
    fn get_or_create_ephemeral_keys(
        &self,
        key_pair_id: KeyPairId,
        epoch: EpochTime,
    ) -> Result<KeyPair, KeyManagerError>;

    /// Get ephemeral public key for an epoch and a key pair id.
    ///
    /// See the oasis-core documentation for details. This variant of the method
    /// synchronously blocks for the result.
    fn get_public_ephemeral_key(
        &self,
        key_pair_id: KeyPairId,
        epoch: EpochTime,
    ) -> Result<SignedPublicKey, KeyManagerError>;

    fn box_clone(&self) -> Box<dyn KeyManager>;
}

impl Clone for Box<dyn KeyManager> {
    fn clone(&self) -> Box<dyn KeyManager> {
        self.box_clone()
    }
}

/// Convenience wrapper around an existing KeyManagerClient instance which uses
/// a default io context for all calls.
#[derive(Clone)]
pub struct KeyManagerClientWithContext {
    parent: Arc<KeyManagerClient>,
    allow_private: bool,
}

impl KeyManagerClientWithContext {
    fn new(parent: Arc<KeyManagerClient>, allow_private: bool) -> KeyManagerClientWithContext {
        KeyManagerClientWithContext {
            parent,
            allow_private,
        }
    }

    /// Get or create named key pair.
    ///
    /// See the oasis-core documentation for details.
    async fn get_or_create_keys_async(
        &self,
        key_pair_id: KeyPairId,
    ) -> Result<KeyPair, KeyManagerError> {
        if !self.allow_private {
            return Err(KeyManagerError::Other(anyhow::anyhow!(
                "not allowed by local runtime policy"
            )));
        }

        self.parent.get_or_create_keys(key_pair_id).await
    }

    /// Get public key for a key pair id.
    ///
    /// See the oasis-core documentation for details.
    async fn get_public_key_async(
        &self,
        key_pair_id: KeyPairId,
    ) -> Result<SignedPublicKey, KeyManagerError> {
        self.parent.get_public_key(key_pair_id).await
    }

    /// Get ephemeral public key for an epoch and a key pair id.
    ///
    /// See the oasis-core documentation for details.
    async fn get_or_create_ephemeral_keys_async(
        &self,
        key_pair_id: KeyPairId,
        epoch: EpochTime,
    ) -> Result<KeyPair, KeyManagerError> {
        if !self.allow_private {
            return Err(KeyManagerError::Other(anyhow::anyhow!(
                "not allowed by local runtime policy"
            )));
        }

        self.parent
            .get_or_create_ephemeral_keys(key_pair_id, epoch)
            .await
    }

    /// Get ephemeral public key for an epoch and a key pair id.
    ///
    /// See the oasis-core documentation for details.
    async fn get_public_ephemeral_key_async(
        &self,
        key_pair_id: KeyPairId,
        epoch: EpochTime,
    ) -> Result<SignedPublicKey, KeyManagerError> {
        self.parent
            .get_public_ephemeral_key(key_pair_id, epoch)
            .await
    }
}

impl KeyManager for KeyManagerClientWithContext {
    fn clear_cache(&self) {
        self.parent.clear_cache();
    }

    fn get_or_create_keys(&self, key_pair_id: KeyPairId) -> Result<KeyPair, KeyManagerError> {
        block_on(self.get_or_create_keys_async(key_pair_id))
    }

    fn get_public_key(&self, key_pair_id: KeyPairId) -> Result<SignedPublicKey, KeyManagerError> {
        block_on(self.get_public_key_async(key_pair_id))
    }

    fn get_or_create_ephemeral_keys(
        &self,
        key_pair_id: KeyPairId,
        epoch: EpochTime,
    ) -> Result<KeyPair, KeyManagerError> {
        block_on(self.get_or_create_ephemeral_keys_async(key_pair_id, epoch))
    }

    fn get_public_ephemeral_key(
        &self,
        key_pair_id: KeyPairId,
        epoch: EpochTime,
    ) -> Result<SignedPublicKey, KeyManagerError> {
        block_on(self.get_public_ephemeral_key_async(key_pair_id, epoch))
    }

    fn box_clone(&self) -> Box<dyn KeyManager> {
        Box::new(self.clone())
    }
}

/// Key pair ID domain separation context.
pub const KEY_PAIR_ID_CONTEXT: &[u8] = b"oasis-runtime-sdk/keymanager: key pair id";

/// Derive a `KeyPairId` for use with the key manager functions.
pub fn get_key_pair_id<'a, C>(context: C) -> KeyPairId
where
    C: IntoIterator<Item = &'a [u8]> + 'a,
{
    let mut h = TupleHash::v256(KEY_PAIR_ID_CONTEXT);
    for item in context.into_iter() {
        h.update(item);
    }
    let mut key_pair_id = [0u8; 32];
    h.finalize(&mut key_pair_id);

    KeyPairId(key_pair_id)
}