-
Notifications
You must be signed in to change notification settings - Fork 168
/
helpers.rs
327 lines (295 loc) · 10.8 KB
/
helpers.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
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
316
317
318
319
320
321
322
323
324
325
326
327
//! Common helper functions
use hex;
use sp_core::{crypto::AccountId32, ecdsa, ed25519, sr25519};
use sp_core::{
crypto::{Ss58AddressFormat, Ss58Codec},
hexdisplay::HexDisplay,
Hasher, KeccakHasher, H160, H256,
};
use sp_runtime::MultiSigner;
use std::convert::TryInto;
use crate::crypto::Encryption;
use crate::error::Error;
use crate::error::Result;
/// Decode hexadecimal `&str` into `Vec<u8>`, with descriptive error
///
/// Function could be used both on hot and cold side.
///
/// In addition to encoded `&str` required is input of `T::NotHex`, to produce
/// error with details on what exactly turned out to be invalid hexadecimal
/// string.
pub fn unhex(hex_entry: &str) -> Result<Vec<u8>> {
let hex_entry = {
if let Some(a) = hex_entry.strip_prefix("0x") {
a
} else {
hex_entry
}
};
Ok(hex::decode(hex_entry)?)
}
/// Get `Vec<u8>` public key from
/// [`MultiSigner`](https://docs.rs/sp-runtime/6.0.0/sp_runtime/enum.MultiSigner.html)
pub fn multisigner_to_public(m: &MultiSigner) -> Vec<u8> {
match m {
MultiSigner::Ed25519(a) => a.to_vec(),
MultiSigner::Sr25519(a) => a.to_vec(),
MultiSigner::Ecdsa(a) => a.0.to_vec(),
}
}
/// Get [`Encryption`](crate::crypto::Encryption) from
/// [`MultiSigner`](https://docs.rs/sp-runtime/6.0.0/sp_runtime/enum.MultiSigner.html)
pub fn multisigner_to_encryption(m: &MultiSigner) -> Encryption {
match m {
MultiSigner::Ed25519(_) => Encryption::Ed25519,
MultiSigner::Sr25519(_) => Encryption::Sr25519,
MultiSigner::Ecdsa(_) => Encryption::Ecdsa,
}
}
pub enum IdenticonStyle {
/// Default style for substrate-based networks, dots in a circle.
Dots,
/// Blockies style used in Ethereum networks.
Blockies,
/// Jdenticon style used to identify key sets.
Jdenticon,
}
use crate::navigation::Identicon;
/// Print identicon from
/// [`MultiSigner`](https://docs.rs/sp-runtime/6.0.0/sp_runtime/enum.MultiSigner.html)
pub fn make_identicon_from_multisigner(
multisigner: &MultiSigner,
style: IdenticonStyle,
) -> Identicon {
match style {
IdenticonStyle::Dots => Identicon::Dots {
identity: multisigner_to_public(multisigner),
},
IdenticonStyle::Blockies => {
if let MultiSigner::Ecdsa(ref public) = multisigner {
Identicon::Blockies {
identity: print_ethereum_address(public),
}
} else {
Identicon::Blockies {
identity: "".to_string(),
}
}
}
IdenticonStyle::Jdenticon => Identicon::Jdenticon {
identity: print_multisigner_as_base58_or_eth(
multisigner,
None,
multisigner_to_encryption(multisigner),
),
},
}
}
pub fn make_identicon_from_id20(id: &[u8; 20]) -> Identicon {
let account = format!("0x{}", hex::encode(id));
Identicon::Blockies { identity: account }
}
pub fn make_identicon_from_account(account: AccountId32) -> Identicon {
make_identicon(&<[u8; 32]>::from(account))
}
fn make_identicon(into_id: &[u8]) -> Identicon {
Identicon::Dots {
identity: into_id.into(),
}
}
/// Get [`MultiSigner`](https://docs.rs/sp-runtime/6.0.0/sp_runtime/enum.MultiSigner.html)
/// from public key and [`Encryption`](crate::crypto::Encryption)
pub fn get_multisigner(public: &[u8], encryption: &Encryption) -> Result<MultiSigner> {
match encryption {
Encryption::Ed25519 => {
let into_pubkey: [u8; 32] = public
.to_vec()
.try_into()
.map_err(|_| Error::WrongPublicKeyLength)?;
Ok(MultiSigner::Ed25519(ed25519::Public::from_raw(into_pubkey)))
}
Encryption::Sr25519 => {
let into_pubkey: [u8; 32] = public
.to_vec()
.try_into()
.map_err(|_| Error::WrongPublicKeyLength)?;
Ok(MultiSigner::Sr25519(sr25519::Public::from_raw(into_pubkey)))
}
Encryption::Ecdsa | Encryption::Ethereum => {
let into_pubkey: [u8; 33] = public
.to_vec()
.try_into()
.map_err(|_| Error::WrongPublicKeyLength)?;
Ok(MultiSigner::Ecdsa(ecdsa::Public::from_raw(into_pubkey)))
}
}
}
/// Print [`MultiSigner`](https://docs.rs/sp-runtime/6.0.0/sp_runtime/enum.MultiSigner.html)
/// in base58 format
///
/// Could be done for both
/// [custom](https://docs.rs/sp-core/6.0.0/sp_core/crypto/trait.Ss58Codec.html#method.to_ss58check_with_version)
/// network-specific base58 prefix by providing `Some(value)` as `optional_prefix` or with
/// [default](https://docs.rs/sp-core/6.0.0/sp_core/crypto/trait.Ss58Codec.html#method.to_ss58check)
/// one by leaving it `None`.
pub fn print_multisigner_as_base58_or_eth(
multi_signer: &MultiSigner,
optional_prefix: Option<u16>,
encryption: Encryption,
) -> String {
match optional_prefix {
Some(base58prefix) => {
let version_for_base58 = Ss58AddressFormat::custom(base58prefix);
match multi_signer {
MultiSigner::Ed25519(pubkey) => {
pubkey.to_ss58check_with_version(version_for_base58)
}
MultiSigner::Sr25519(pubkey) => {
pubkey.to_ss58check_with_version(version_for_base58)
}
MultiSigner::Ecdsa(pubkey) => {
if encryption == Encryption::Ethereum {
print_ethereum_address(pubkey)
} else {
pubkey.to_ss58check_with_version(version_for_base58)
}
}
}
}
None => match multi_signer {
MultiSigner::Ed25519(pubkey) => {
let version = Ss58AddressFormat::try_from("BareEd25519")
.expect("unable to make Ss58AddressFormat from `BareEd25519`");
pubkey.to_ss58check_with_version(version)
}
MultiSigner::Sr25519(pubkey) => {
let version = Ss58AddressFormat::try_from("BareSr25519")
.expect("unable to make Ss58AddressFormat from `BareSr25519`");
pubkey.to_ss58check_with_version(version)
}
MultiSigner::Ecdsa(pubkey) => {
if encryption == Encryption::Ethereum {
print_ethereum_address(pubkey)
} else {
pubkey.to_ss58check()
}
}
},
}
}
/// Turn a `ecdsa::Public` addr into an Ethereum address.
pub fn ecdsa_public_to_eth_address(public: &ecdsa::Public) -> Result<H160> {
let decompressed = libsecp256k1::PublicKey::parse_compressed(&public.0)?.serialize();
let mut m = [0u8; 64];
m.copy_from_slice(&decompressed[1..65]);
Ok(H160::from(H256::from_slice(
KeccakHasher::hash(&m).as_bytes(),
)))
}
/// Print a `ecdsa::Public` into `String`.
///
/// Panics if provided ecdsa public key is in wrong format.
fn print_ethereum_address(public: &ecdsa::Public) -> String {
let account = ecdsa_public_to_eth_address(public).expect("Wrong ecdsa public key provided");
format!("0x{:?}", HexDisplay::from(&account.as_bytes()))
}
pub fn base58_or_eth_to_multisigner(
base58_or_eth: &str,
encryption: &Encryption,
) -> Result<MultiSigner> {
match encryption {
Encryption::Ed25519 => {
let pubkey = ed25519::Public::from_ss58check(base58_or_eth)?;
Ok(MultiSigner::Ed25519(pubkey))
}
Encryption::Sr25519 => {
let pubkey = sr25519::Public::from_ss58check(base58_or_eth)?;
Ok(MultiSigner::Sr25519(pubkey))
}
Encryption::Ethereum | Encryption::Ecdsa => {
let pubkey = ecdsa::Public::from_ss58check(base58_or_eth)?;
Ok(MultiSigner::Ecdsa(pubkey))
}
}
}
/// Print id pic for metadata hash
///
/// Currently uses PNG identicon generator, could be changed later.
pub fn pic_meta(meta_hash: &[u8]) -> Identicon {
make_identicon(meta_hash)
}
/// Print id pic for hash of SCALE-encoded types data
///
/// Currently uses PNG identicon generator, could be changed later.
pub fn pic_types(types_hash: &[u8]) -> Identicon {
make_identicon(types_hash)
}
#[cfg(test)]
mod tests {
use super::*;
use pretty_assertions::assert_eq;
use sp_core::Pair;
use sp_runtime::MultiSigner::Sr25519;
#[test]
fn test_eth_account_1() {
let secret_key =
hex::decode("502f97299c472b88754accd412b7c9a6062ef3186fba0c0388365e1edec24875")
.unwrap();
let public_key = ecdsa::Pair::from_seed_slice(&secret_key).unwrap().public();
assert_eq!(
print_ethereum_address(&public_key),
"0x976f8456e4e2034179b284a23c0e0c8f6d3da50c"
)
}
#[test]
fn test_eth_account_2() {
let secret_key =
hex::decode("0f02ba4d7f83e59eaa32eae9c3c4d99b68ce76decade21cdab7ecce8f4aef81a")
.unwrap();
let public_key = ecdsa::Pair::from_seed_slice(&secret_key).unwrap().public();
assert_eq!(
print_ethereum_address(&public_key),
"0x420e9f260b40af7e49440cead3069f8e82a5230f",
)
}
#[test]
fn test_ss85_to_multisigner() {
let secret_key =
hex::decode("46ebddef8cd9bb167dc30878d7113b7e168e6f0646beffd77d69d39bad76b47a")
.unwrap();
let encryption = Encryption::Sr25519;
let public = sr25519::Pair::from_seed_slice(&secret_key)
.unwrap()
.public();
let multisigner = Sr25519(public);
let ss58 = print_multisigner_as_base58_or_eth(&multisigner, None, encryption);
let result = base58_or_eth_to_multisigner(&ss58, &Encryption::Sr25519).unwrap();
assert_eq!(result, multisigner);
}
#[test]
fn test_print_multisigner_polkadot() {
let multisigner = Sr25519(sr25519::Public(
hex::decode("4a755d99a3cbafc1918769c292848bc87bc2e3cb3e09c17856a1c7d0c784b41c")
.unwrap()
.try_into()
.unwrap(),
));
assert_eq!(
print_multisigner_as_base58_or_eth(&multisigner, Some(0), Encryption::Sr25519),
"12gdQgfKFbiuba7hHS81MMr1rQH2amezrCbWixXZoUKzAm3q"
);
}
#[test]
fn test_print_multisigner_no_network() {
let multisigner = Sr25519(sr25519::Public(
hex::decode("4a755d99a3cbafc1918769c292848bc87bc2e3cb3e09c17856a1c7d0c784b41c")
.unwrap()
.try_into()
.unwrap(),
));
assert_eq!(
print_multisigner_as_base58_or_eth(&multisigner, None, Encryption::Sr25519),
"8UHfgCidtbdkdXABy12jG7SVtRKdxHX399eLeAsGKvUT2U6"
);
}
}