gring/keyring.rs
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
// This file is part of Gear.
//
// Copyright (C) 2024 Gear Technologies Inc.
// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
//! Keyring implementation based on the polkadot-js keystore.
use crate::{ss58, Keystore};
use anyhow::{anyhow, Result};
use colored::Colorize;
use schnorrkel::Keypair;
use serde::{Deserialize, Serialize};
use std::{fs, path::PathBuf};
const CONFIG: &str = "keyring.json";
/// Gear keyring.
#[derive(Default, Serialize, Deserialize)]
pub struct Keyring {
/// Path to the store.
#[serde(skip)]
pub store: PathBuf,
/// A set of keystore instances.
#[serde(skip)]
ring: Vec<Keystore>,
/// The primary key.
pub primary: String,
}
impl Keyring {
/// Loads the keyring from the store.
///
/// NOTE: For the store path, see [`STORE`].
pub fn load(store: PathBuf) -> Result<Self> {
let ring = fs::read_dir(&store)?
.filter_map(|entry| {
let path = entry.ok()?.path();
let content = fs::read(&path).ok()?;
if path.ends_with(CONFIG) {
return None;
}
serde_json::from_slice(&content)
.map_err(|err| {
tracing::warn!("Failed to load keystore at {path:?}: {err}");
err
})
.ok()
})
.collect::<Vec<_>>();
let config = store.join(CONFIG);
let mut this = if config.exists() {
serde_json::from_slice(&fs::read(&config)?)?
} else {
Self::default()
};
this.ring = ring;
this.store = store;
Ok(this)
}
/// Update and get the primary key.
pub fn primary(&mut self) -> Result<Keystore> {
if self.ring.is_empty() {
return Err(anyhow!(
"No keys in keyring, run {} to create a new one.",
"`gring generate <NAME> -p <PASSPHRASE>`"
.underline()
.cyan()
.bold()
));
}
if let Some(key) = self
.ring
.iter()
.find(|k| k.meta.name == self.primary)
.cloned()
{
Ok(key)
} else {
self.primary = self.ring[0].meta.name.clone();
fs::write(self.store.join(CONFIG), serde_json::to_vec_pretty(&self)?)?;
Ok(self.ring[0].clone())
}
}
/// Set the primary key.
pub fn set_primary(&mut self, name: String) -> Result<Keystore> {
let key = self
.ring
.iter()
.find(|k| k.meta.name == name)
.cloned()
.ok_or_else(|| {
anyhow!(
"Key with name {} not found, run {} to see all keys in keyring.",
name.underline().bold(),
"`gring list`".underline().cyan().bold()
)
})?;
self.primary = name;
fs::write(self.store.join(CONFIG), serde_json::to_vec_pretty(&self)?)?;
Ok(key)
}
/// Add keypair to the keyring
pub fn add(
&mut self,
name: &str,
keypair: Keypair,
passphrase: Option<&str>,
) -> Result<(Keystore, Keypair)> {
let mut keystore = Keystore::encrypt(keypair.clone(), passphrase.map(|p| p.as_bytes()))?;
keystore.meta.name = name.into();
fs::write(
self.store.join(&keystore.meta.name).with_extension("json"),
serde_json::to_vec_pretty(&keystore)?,
)?;
self.ring.push(keystore.clone());
Ok((keystore, keypair))
}
/// create a new key in keyring.
pub fn create(
&mut self,
name: &str,
vanity: Option<&str>,
passphrase: Option<&str>,
) -> Result<(Keystore, Keypair)> {
let keypair = if let Some(vanity) = vanity {
tracing::info!("Generating vanity key with prefix {vanity}...");
let mut keypair = Keypair::generate();
while !ss58::encode(&keypair.public.to_bytes())?.starts_with(vanity) {
keypair = Keypair::generate();
}
keypair
} else {
Keypair::generate()
};
self.add(name, keypair, passphrase)
}
/// List all keystores.
pub fn list(&self) -> &[Keystore] {
self.ring.as_ref()
}
}