Skip to main content

ac_keystore/
keystore_ext.rs

1/*
2	Copyright 2019 Supercomputing Systems AG
3	Licensed under the Apache License, Version 2.0 (the "License");
4	you may not use this file except in compliance with the License.
5	You may obtain a copy of the License at
6
7		http://www.apache.org/licenses/LICENSE-2.0
8
9	Unless required by applicable law or agreed to in writing, software
10	distributed under the License is distributed on an "AS IS" BASIS,
11	WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12	See the License for the specific language governing permissions and
13	limitations under the License.
14*/
15
16use crate::LocalKeystore;
17use sc_keystore::Result;
18use sp_application_crypto::{AppPair, AppPublic};
19
20/// This is an extension from the substrate-api-client repo. Keep it as a separate trait to
21/// make that clear.
22pub trait KeystoreExt {
23	fn generate<Pair: AppPair>(&self) -> Result<Pair>;
24	fn public_keys<Public: AppPublic>(&self) -> Result<Vec<Public>>;
25}
26
27impl KeystoreExt for LocalKeystore {
28	fn generate<Pair: AppPair>(&self) -> Result<Pair> {
29		self.0.write().generate_by_type::<Pair::Generic>(Pair::ID).map(Into::into)
30	}
31
32	fn public_keys<Public: AppPublic>(&self) -> Result<Vec<Public>> {
33		self.0
34			.read()
35			.raw_public_keys(Public::ID)
36			.map(|v| v.into_iter().filter_map(|k| Public::from_slice(k.as_slice()).ok()).collect())
37	}
38}
39
40#[cfg(test)]
41mod tests {
42	use crate::{KeystoreExt, LocalKeystore};
43	use sp_application_crypto::sr25519::AppPair;
44	use sp_core::Pair;
45
46	#[test]
47	fn test_execute_generate_doesnt_fail() {
48		let store = LocalKeystore::in_memory();
49		let generated_key = store.generate::<AppPair>();
50
51		// check that something was generated
52		assert_ne!("", format!("{:?}", generated_key.unwrap().to_raw_vec()));
53	}
54}