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
//! Signing keyring. Presently specialized for Ed25519 and ECDSA.

pub mod ecdsa;
pub mod ed25519;
pub mod format;
pub mod providers;
pub mod signature;

pub use self::{format::Format, providers::SigningProvider, signature::Signature};
use crate::{
    chain,
    config::provider::ProviderConfig,
    error::{Error, ErrorKind::*},
    prelude::*,
    Map,
};
use tendermint::{account, TendermintKey};

/// File encoding for software-backed secret keys
pub type SecretKeyEncoding = subtle_encoding::Base64;

/// Signing keyring
pub struct KeyRing {
    /// ECDSA keys in the keyring
    ecdsa_keys: Map<TendermintKey, ecdsa::Signer>,

    /// Ed25519 keys in the keyring
    ed25519_keys: Map<TendermintKey, ed25519::Signer>,

    /// Formatting configuration when displaying keys (e.g. bech32)
    format: Format,
}

impl KeyRing {
    /// Create a new keyring
    pub fn new(format: Format) -> Self {
        Self {
            ecdsa_keys: Map::new(),
            ed25519_keys: Map::new(),
            format,
        }
    }

    /// Add na ECDSA key to the keyring, returning an error if we already have a
    /// signer registered for the given public key
    pub fn add_ecdsa(&mut self, signer: ecdsa::Signer) -> Result<(), Error> {
        let provider = signer.provider();
        let public_key = signer.public_key();
        let public_key_serialized = self.format.serialize(public_key);
        let key_type = match public_key {
            TendermintKey::AccountKey(_) => "account",
            TendermintKey::ConsensusKey(_) => unimplemented!(
                "ECDSA consensus keys unsupported: {:?}",
                public_key_serialized
            ),
        };

        info!(
            "[keyring:{}] added {} ECDSA key: {}",
            provider, key_type, public_key_serialized
        );

        if let Some(other) = self.ecdsa_keys.insert(public_key, signer) {
            fail!(
                InvalidKey,
                "[keyring:{}] duplicate key {} already registered as {}",
                provider,
                public_key_serialized,
                other.provider(),
            )
        } else {
            Ok(())
        }
    }

    /// Add a key to the keyring, returning an error if we already have a
    /// signer registered for the given public key
    pub fn add_ed25519(&mut self, signer: ed25519::Signer) -> Result<(), Error> {
        let provider = signer.provider();
        let public_key = signer.public_key();
        let public_key_serialized = self.format.serialize(public_key);
        let key_type = match public_key {
            TendermintKey::AccountKey(_) => unimplemented!(
                "Ed25519 account keys unsupported: {:?}",
                public_key_serialized
            ),
            TendermintKey::ConsensusKey(_) => "consensus",
        };

        info!(
            "[keyring:{}] added {} Ed25519 key: {}",
            provider, key_type, public_key_serialized
        );

        if let Some(other) = self.ed25519_keys.insert(public_key, signer) {
            fail!(
                InvalidKey,
                "[keyring:{}] duplicate key {} already registered as {}",
                provider,
                public_key_serialized,
                other.provider(),
            )
        } else {
            Ok(())
        }
    }

    /// Get the default Ed25519 (i.e. consensus) public key for this keyring
    pub fn default_pubkey(&self) -> Result<TendermintKey, Error> {
        if !self.ed25519_keys.is_empty() {
            let mut keys = self.ed25519_keys.keys();

            if keys.len() == 1 {
                Ok(*keys.next().unwrap())
            } else {
                fail!(InvalidKey, "expected only one ed25519 key in keyring");
            }
        } else if !self.ecdsa_keys.is_empty() {
            let mut keys = self.ecdsa_keys.keys();

            if keys.len() == 1 {
                Ok(*keys.next().unwrap())
            } else {
                fail!(InvalidKey, "expected only one ecdsa key in keyring");
            }
        } else {
            fail!(InvalidKey, "keyring is empty");
        }
    }

    /// Get ECDSA public key bytes for a given account ID
    pub fn get_account_pubkey(&self, account_id: account::Id) -> Option<tendermint::PublicKey> {
        for key in self.ecdsa_keys.keys() {
            if let TendermintKey::AccountKey(pk) = key {
                if account_id == account::Id::from(*pk) {
                    return Some(*pk);
                }
            }
        }

        None
    }

    /// Sign a message using ECDSA
    pub fn sign_ecdsa(
        &self,
        account_id: account::Id,
        msg: &[u8],
    ) -> Result<ecdsa::Signature, Error> {
        for (key, signer) in &self.ecdsa_keys {
            if let TendermintKey::AccountKey(pk) = key {
                if account_id == account::Id::from(*pk) {
                    return signer.sign(msg);
                }
            }
        }

        fail!(
            InvalidKey,
            "no ECDSA key in keyring for account ID: {}",
            account_id
        )
    }

    /// Sign a message using the secret key associated with the given public key
    /// (if it is in our keyring)
    pub fn sign(&self, public_key: Option<&TendermintKey>, msg: &[u8]) -> Result<Signature, Error> {
        if self.ed25519_keys.len() > 1 || self.ecdsa_keys.len() > 1 {
            fail!(SigningError, "expected only one key in keyring");
        }

        if !self.ed25519_keys.is_empty() {
            let signer = match public_key {
                Some(public_key) => self.ed25519_keys.get(public_key).ok_or_else(|| {
                    format_err!(
                        InvalidKey,
                        "not in keyring: {}",
                        match public_key {
                            TendermintKey::AccountKey(pk) => pk.to_bech32(""),
                            TendermintKey::ConsensusKey(pk) => pk.to_bech32(""),
                        }
                    )
                }),
                None => self
                    .ed25519_keys
                    .values()
                    .next()
                    .ok_or_else(|| format_err!(InvalidKey, "ed25519 keyring is empty")),
            }?;

            Ok(Signature::Ed25519(signer.sign(msg)?))
        } else if !self.ecdsa_keys.is_empty() {
            let signer = match public_key {
                Some(public_key) => self.ecdsa_keys.get(public_key).ok_or_else(|| {
                    format_err!(
                        InvalidKey,
                        "not in keyring: {}",
                        match public_key {
                            TendermintKey::AccountKey(pk) => pk.to_bech32(""),
                            TendermintKey::ConsensusKey(pk) => pk.to_bech32(""),
                        }
                    )
                }),
                None => self
                    .ecdsa_keys
                    .values()
                    .next()
                    .ok_or_else(|| format_err!(InvalidKey, "ecdsa keyring is empty")),
            }?;

            Ok(Signature::Ecdsa(signer.sign(msg)?))
        } else {
            Err(format_err!(InvalidKey, "keyring is empty").into())
        }
    }
}

/// Initialize the keyring from the configuration file
pub fn load_config(registry: &mut chain::Registry, config: &ProviderConfig) -> Result<(), Error> {
    #[cfg(feature = "softsign")]
    providers::softsign::init(registry, &config.softsign)?;

    #[cfg(feature = "yubihsm")]
    providers::yubihsm::init(registry, &config.yubihsm)?;

    #[cfg(feature = "ledger")]
    providers::ledgertm::init(registry, &config.ledgertm)?;

    #[cfg(feature = "fortanixdsm")]
    providers::fortanixdsm::init(registry, &config.fortanixdsm)?;

    Ok(())
}