Trait sp_core::crypto::Ss58Codec

source ·
pub trait Ss58Codec: Sized + AsMut<[u8]> + AsRef<[u8]> + ByteArray {
    fn format_is_allowed(f: Ss58AddressFormat) -> bool { ... }
    fn from_ss58check(s: &str) -> Result<Self, PublicError> { ... }
    fn from_ss58check_with_version(
        s: &str
    ) -> Result<(Self, Ss58AddressFormat), PublicError> { ... } fn from_string(s: &str) -> Result<Self, PublicError> { ... } fn to_ss58check_with_version(&self, version: Ss58AddressFormat) -> String { ... } fn to_ss58check(&self) -> String { ... } fn from_string_with_version(
        s: &str
    ) -> Result<(Self, Ss58AddressFormat), PublicError> { ... } }
Expand description

Key that can be encoded to/from SS58.

See https://docs.substrate.io/v3/advanced/ss58/ for information on the codec.

Provided Methods§

A format filterer, can be used to ensure that from_ss58check family only decode for allowed identifiers. By default just refuses the two reserved identifiers.

Examples found in repository?
src/crypto.rs (line 288)
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
	fn from_ss58check_with_version(s: &str) -> Result<(Self, Ss58AddressFormat), PublicError> {
		const CHECKSUM_LEN: usize = 2;
		let body_len = Self::LEN;

		let data = s.from_base58().map_err(|_| PublicError::BadBase58)?;
		if data.len() < 2 {
			return Err(PublicError::BadLength)
		}
		let (prefix_len, ident) = match data[0] {
			0..=63 => (1, data[0] as u16),
			64..=127 => {
				// weird bit manipulation owing to the combination of LE encoding and missing two
				// bits from the left.
				// d[0] d[1] are: 01aaaaaa bbcccccc
				// they make the LE-encoded 16-bit value: aaaaaabb 00cccccc
				// so the lower byte is formed of aaaaaabb and the higher byte is 00cccccc
				let lower = (data[0] << 2) | (data[1] >> 6);
				let upper = data[1] & 0b00111111;
				(2, (lower as u16) | ((upper as u16) << 8))
			},
			_ => return Err(PublicError::InvalidPrefix),
		};
		if data.len() != prefix_len + body_len + CHECKSUM_LEN {
			return Err(PublicError::BadLength)
		}
		let format = ident.into();
		if !Self::format_is_allowed(format) {
			return Err(PublicError::FormatNotAllowed)
		}

		let hash = ss58hash(&data[0..body_len + prefix_len]);
		let checksum = &hash[0..CHECKSUM_LEN];
		if data[body_len + prefix_len..body_len + prefix_len + CHECKSUM_LEN] != *checksum {
			// Invalid checksum.
			return Err(PublicError::InvalidChecksum)
		}

		let result = Self::from_slice(&data[prefix_len..body_len + prefix_len])
			.map_err(|()| PublicError::BadLength)?;
		Ok((result, format))
	}

Some if the string is a properly encoded SS58Check address.

Examples found in repository?
src/ed25519.rs (line 149)
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
	fn from_str(s: &str) -> Result<Self, Self::Err> {
		Self::from_ss58check(s)
	}
}

impl UncheckedFrom<[u8; 32]> for Public {
	fn unchecked_from(x: [u8; 32]) -> Self {
		Public::from_raw(x)
	}
}

impl UncheckedFrom<H256> for Public {
	fn unchecked_from(x: H256) -> Self {
		Public::from_h256(x)
	}
}

#[cfg(feature = "std")]
impl std::fmt::Display for Public {
	fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
		write!(f, "{}", self.to_ss58check())
	}
}

impl sp_std::fmt::Debug for Public {
	#[cfg(feature = "std")]
	fn fmt(&self, f: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result {
		let s = self.to_ss58check();
		write!(f, "{} ({}...)", crate::hexdisplay::HexDisplay::from(&self.0), &s[0..8])
	}

	#[cfg(not(feature = "std"))]
	fn fmt(&self, _: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result {
		Ok(())
	}
}

#[cfg(feature = "std")]
impl Serialize for Public {
	fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
	where
		S: Serializer,
	{
		serializer.serialize_str(&self.to_ss58check())
	}
}

#[cfg(feature = "std")]
impl<'de> Deserialize<'de> for Public {
	fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
	where
		D: Deserializer<'de>,
	{
		Public::from_ss58check(&String::deserialize(deserializer)?)
			.map_err(|e| de::Error::custom(format!("{:?}", e)))
	}
More examples
Hide additional examples
src/sr25519.rs (line 139)
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
	fn from_str(s: &str) -> Result<Self, Self::Err> {
		Self::from_ss58check(s)
	}
}

impl TryFrom<&[u8]> for Public {
	type Error = ();

	fn try_from(data: &[u8]) -> Result<Self, Self::Error> {
		if data.len() != Self::LEN {
			return Err(())
		}
		let mut r = [0u8; 32];
		r.copy_from_slice(data);
		Ok(Self::unchecked_from(r))
	}
}

impl UncheckedFrom<[u8; 32]> for Public {
	fn unchecked_from(x: [u8; 32]) -> Self {
		Public::from_raw(x)
	}
}

impl UncheckedFrom<H256> for Public {
	fn unchecked_from(x: H256) -> Self {
		Public::from_h256(x)
	}
}

#[cfg(feature = "std")]
impl std::fmt::Display for Public {
	fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
		write!(f, "{}", self.to_ss58check())
	}
}

impl sp_std::fmt::Debug for Public {
	#[cfg(feature = "std")]
	fn fmt(&self, f: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result {
		let s = self.to_ss58check();
		write!(f, "{} ({}...)", crate::hexdisplay::HexDisplay::from(&self.0), &s[0..8])
	}

	#[cfg(not(feature = "std"))]
	fn fmt(&self, _: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result {
		Ok(())
	}
}

#[cfg(feature = "std")]
impl Serialize for Public {
	fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
	where
		S: Serializer,
	{
		serializer.serialize_str(&self.to_ss58check())
	}
}

#[cfg(feature = "std")]
impl<'de> Deserialize<'de> for Public {
	fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
	where
		D: Deserializer<'de>,
	{
		Public::from_ss58check(&String::deserialize(deserializer)?)
			.map_err(|e| de::Error::custom(format!("{:?}", e)))
	}
src/ecdsa.rs (line 202)
198
199
200
201
202
203
204
	fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
	where
		D: Deserializer<'de>,
	{
		Public::from_ss58check(&String::deserialize(deserializer)?)
			.map_err(|e| de::Error::custom(format!("{:?}", e)))
	}
src/crypto.rs (line 427)
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
	fn from_string(s: &str) -> Result<Self, PublicError> {
		let cap = SS58_REGEX.captures(s).ok_or(PublicError::InvalidFormat)?;
		let s = cap.name("ss58").map(|r| r.as_str()).unwrap_or(DEV_ADDRESS);
		let addr = if let Some(stripped) = s.strip_prefix("0x") {
			let d = array_bytes::hex2bytes(stripped).map_err(|_| PublicError::InvalidFormat)?;
			Self::from_slice(&d).map_err(|()| PublicError::BadLength)?
		} else {
			Self::from_ss58check(s)?
		};
		if cap["path"].is_empty() {
			Ok(addr)
		} else {
			let path =
				JUNCTION_REGEX.captures_iter(&cap["path"]).map(|f| DeriveJunction::from(&f[1]));
			addr.derive(path).ok_or(PublicError::InvalidPath)
		}
	}

	fn from_string_with_version(s: &str) -> Result<(Self, Ss58AddressFormat), PublicError> {
		let cap = SS58_REGEX.captures(s).ok_or(PublicError::InvalidFormat)?;
		let (addr, v) = Self::from_ss58check_with_version(
			cap.name("ss58").map(|r| r.as_str()).unwrap_or(DEV_ADDRESS),
		)?;
		if cap["path"].is_empty() {
			Ok((addr, v))
		} else {
			let path =
				JUNCTION_REGEX.captures_iter(&cap["path"]).map(|f| DeriveJunction::from(&f[1]));
			addr.derive(path).ok_or(PublicError::InvalidPath).map(|a| (a, v))
		}
	}
}

/// Trait used for types that are really just a fixed-length array.
pub trait ByteArray: AsRef<[u8]> + AsMut<[u8]> + for<'a> TryFrom<&'a [u8], Error = ()> {
	/// The "length" of the values of this type, which is always the same.
	const LEN: usize;

	/// A new instance from the given slice that should be `Self::LEN` bytes long.
	fn from_slice(data: &[u8]) -> Result<Self, ()> {
		Self::try_from(data)
	}

	/// Return a `Vec<u8>` filled with raw data.
	fn to_raw_vec(&self) -> Vec<u8> {
		self.as_slice().to_vec()
	}

	/// Return a slice filled with raw data.
	fn as_slice(&self) -> &[u8] {
		self.as_ref()
	}
}

/// Trait suitable for typical cryptographic PKI key public type.
pub trait Public: ByteArray + Derive + CryptoType + PartialEq + Eq + Clone + Send + Sync {
	/// Return `CryptoTypePublicPair` from public key.
	fn to_public_crypto_pair(&self) -> CryptoTypePublicPair;
}

/// An opaque 32-byte cryptographic identifier.
#[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Encode, Decode, MaxEncodedLen, TypeInfo)]
#[cfg_attr(feature = "std", derive(Hash))]
pub struct AccountId32([u8; 32]);

impl AccountId32 {
	/// Create a new instance from its raw inner byte value.
	///
	/// Equivalent to this types `From<[u8; 32]>` implementation. For the lack of const
	/// support in traits we have this constructor.
	pub const fn new(inner: [u8; 32]) -> Self {
		Self(inner)
	}
}

impl UncheckedFrom<crate::hash::H256> for AccountId32 {
	fn unchecked_from(h: crate::hash::H256) -> Self {
		AccountId32(h.into())
	}
}

impl ByteArray for AccountId32 {
	const LEN: usize = 32;
}

#[cfg(feature = "std")]
impl Ss58Codec for AccountId32 {}

impl AsRef<[u8]> for AccountId32 {
	fn as_ref(&self) -> &[u8] {
		&self.0[..]
	}
}

impl AsMut<[u8]> for AccountId32 {
	fn as_mut(&mut self) -> &mut [u8] {
		&mut self.0[..]
	}
}

impl AsRef<[u8; 32]> for AccountId32 {
	fn as_ref(&self) -> &[u8; 32] {
		&self.0
	}
}

impl AsMut<[u8; 32]> for AccountId32 {
	fn as_mut(&mut self) -> &mut [u8; 32] {
		&mut self.0
	}
}

impl From<[u8; 32]> for AccountId32 {
	fn from(x: [u8; 32]) -> Self {
		Self::new(x)
	}
}

impl<'a> TryFrom<&'a [u8]> for AccountId32 {
	type Error = ();
	fn try_from(x: &'a [u8]) -> Result<AccountId32, ()> {
		if x.len() == 32 {
			let mut data = [0; 32];
			data.copy_from_slice(x);
			Ok(AccountId32(data))
		} else {
			Err(())
		}
	}
}

impl From<AccountId32> for [u8; 32] {
	fn from(x: AccountId32) -> [u8; 32] {
		x.0
	}
}

impl From<sr25519::Public> for AccountId32 {
	fn from(k: sr25519::Public) -> Self {
		k.0.into()
	}
}

impl From<ed25519::Public> for AccountId32 {
	fn from(k: ed25519::Public) -> Self {
		k.0.into()
	}
}

#[cfg(feature = "std")]
impl std::fmt::Display for AccountId32 {
	fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
		write!(f, "{}", self.to_ss58check())
	}
}

impl sp_std::fmt::Debug for AccountId32 {
	#[cfg(feature = "std")]
	fn fmt(&self, f: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result {
		let s = self.to_ss58check();
		write!(f, "{} ({}...)", crate::hexdisplay::HexDisplay::from(&self.0), &s[0..8])
	}

	#[cfg(not(feature = "std"))]
	fn fmt(&self, _: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result {
		Ok(())
	}
}

#[cfg(feature = "std")]
impl serde::Serialize for AccountId32 {
	fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
	where
		S: serde::Serializer,
	{
		serializer.serialize_str(&self.to_ss58check())
	}
}

#[cfg(feature = "std")]
impl<'de> serde::Deserialize<'de> for AccountId32 {
	fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
	where
		D: serde::Deserializer<'de>,
	{
		Ss58Codec::from_ss58check(&String::deserialize(deserializer)?)
			.map_err(|e| serde::de::Error::custom(format!("{:?}", e)))
	}
}

#[cfg(feature = "std")]
impl sp_std::str::FromStr for AccountId32 {
	type Err = &'static str;

	fn from_str(s: &str) -> Result<Self, Self::Err> {
		let hex_or_ss58_without_prefix = s.trim_start_matches("0x");
		if hex_or_ss58_without_prefix.len() == 64 {
			array_bytes::hex_n_into(hex_or_ss58_without_prefix).map_err(|_| "invalid hex address.")
		} else {
			Self::from_ss58check(s).map_err(|_| "invalid ss58 address.")
		}
	}

Some if the string is a properly encoded SS58Check address.

Examples found in repository?
src/crypto.rs (line 253)
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
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
	fn from_ss58check(s: &str) -> Result<Self, PublicError> {
		Self::from_ss58check_with_version(s).and_then(|(r, v)| match v {
			v if !v.is_custom() => Ok(r),
			v if v == default_ss58_version() => Ok(r),
			v => Err(PublicError::UnknownSs58AddressFormat(v)),
		})
	}

	/// Some if the string is a properly encoded SS58Check address.
	#[cfg(feature = "std")]
	fn from_ss58check_with_version(s: &str) -> Result<(Self, Ss58AddressFormat), PublicError> {
		const CHECKSUM_LEN: usize = 2;
		let body_len = Self::LEN;

		let data = s.from_base58().map_err(|_| PublicError::BadBase58)?;
		if data.len() < 2 {
			return Err(PublicError::BadLength)
		}
		let (prefix_len, ident) = match data[0] {
			0..=63 => (1, data[0] as u16),
			64..=127 => {
				// weird bit manipulation owing to the combination of LE encoding and missing two
				// bits from the left.
				// d[0] d[1] are: 01aaaaaa bbcccccc
				// they make the LE-encoded 16-bit value: aaaaaabb 00cccccc
				// so the lower byte is formed of aaaaaabb and the higher byte is 00cccccc
				let lower = (data[0] << 2) | (data[1] >> 6);
				let upper = data[1] & 0b00111111;
				(2, (lower as u16) | ((upper as u16) << 8))
			},
			_ => return Err(PublicError::InvalidPrefix),
		};
		if data.len() != prefix_len + body_len + CHECKSUM_LEN {
			return Err(PublicError::BadLength)
		}
		let format = ident.into();
		if !Self::format_is_allowed(format) {
			return Err(PublicError::FormatNotAllowed)
		}

		let hash = ss58hash(&data[0..body_len + prefix_len]);
		let checksum = &hash[0..CHECKSUM_LEN];
		if data[body_len + prefix_len..body_len + prefix_len + CHECKSUM_LEN] != *checksum {
			// Invalid checksum.
			return Err(PublicError::InvalidChecksum)
		}

		let result = Self::from_slice(&data[prefix_len..body_len + prefix_len])
			.map_err(|()| PublicError::BadLength)?;
		Ok((result, format))
	}

	/// Some if the string is a properly encoded SS58Check address, optionally with
	/// a derivation path following.
	#[cfg(feature = "std")]
	fn from_string(s: &str) -> Result<Self, PublicError> {
		Self::from_string_with_version(s).and_then(|(r, v)| match v {
			v if !v.is_custom() => Ok(r),
			v if v == default_ss58_version() => Ok(r),
			v => Err(PublicError::UnknownSs58AddressFormat(v)),
		})
	}

	/// Return the ss58-check string for this key.
	#[cfg(feature = "std")]
	fn to_ss58check_with_version(&self, version: Ss58AddressFormat) -> String {
		// We mask out the upper two bits of the ident - SS58 Prefix currently only supports 14-bits
		let ident: u16 = u16::from(version) & 0b0011_1111_1111_1111;
		let mut v = match ident {
			0..=63 => vec![ident as u8],
			64..=16_383 => {
				// upper six bits of the lower byte(!)
				let first = ((ident & 0b0000_0000_1111_1100) as u8) >> 2;
				// lower two bits of the lower byte in the high pos,
				// lower bits of the upper byte in the low pos
				let second = ((ident >> 8) as u8) | ((ident & 0b0000_0000_0000_0011) as u8) << 6;
				vec![first | 0b01000000, second]
			},
			_ => unreachable!("masked out the upper two bits; qed"),
		};
		v.extend(self.as_ref());
		let r = ss58hash(&v);
		v.extend(&r[0..2]);
		v.to_base58()
	}

	/// Return the ss58-check string for this key.
	#[cfg(feature = "std")]
	fn to_ss58check(&self) -> String {
		self.to_ss58check_with_version(default_ss58_version())
	}

	/// Some if the string is a properly encoded SS58Check address, optionally with
	/// a derivation path following.
	#[cfg(feature = "std")]
	fn from_string_with_version(s: &str) -> Result<(Self, Ss58AddressFormat), PublicError> {
		Self::from_ss58check_with_version(s)
	}
}

/// Derivable key trait.
pub trait Derive: Sized {
	/// Derive a child key from a series of given junctions.
	///
	/// Will be `None` for public keys if there are any hard junctions in there.
	#[cfg(feature = "std")]
	fn derive<Iter: Iterator<Item = DeriveJunction>>(&self, _path: Iter) -> Option<Self> {
		None
	}
}

#[cfg(feature = "std")]
const PREFIX: &[u8] = b"SS58PRE";

#[cfg(feature = "std")]
fn ss58hash(data: &[u8]) -> Vec<u8> {
	use blake2::{Blake2b512, Digest};

	let mut ctx = Blake2b512::new();
	ctx.update(PREFIX);
	ctx.update(data);
	ctx.finalize().to_vec()
}

/// Default prefix number
#[cfg(feature = "std")]
static DEFAULT_VERSION: core::sync::atomic::AtomicU16 = std::sync::atomic::AtomicU16::new(
	from_known_address_format(Ss58AddressFormatRegistry::SubstrateAccount),
);

/// Returns default SS58 format used by the current active process.
#[cfg(feature = "std")]
pub fn default_ss58_version() -> Ss58AddressFormat {
	DEFAULT_VERSION.load(std::sync::atomic::Ordering::Relaxed).into()
}

/// Returns either the input address format or the default.
#[cfg(feature = "std")]
pub fn unwrap_or_default_ss58_version(network: Option<Ss58AddressFormat>) -> Ss58AddressFormat {
	network.unwrap_or_else(default_ss58_version)
}

/// Set the default SS58 "version".
///
/// This SS58 version/format will be used when encoding/decoding SS58 addresses.
///
/// If you want to support a custom SS58 prefix (that isn't yet registered in the `ss58-registry`),
/// you are required to call this function with your desired prefix [`Ss58AddressFormat::custom`].
/// This will enable the node to decode ss58 addresses with this prefix.
///
/// This SS58 version/format is also only used by the node and not by the runtime.
#[cfg(feature = "std")]
pub fn set_default_ss58_version(new_default: Ss58AddressFormat) {
	DEFAULT_VERSION.store(new_default.into(), std::sync::atomic::Ordering::Relaxed);
}

#[cfg(feature = "std")]
lazy_static::lazy_static! {
	static ref SS58_REGEX: Regex = Regex::new(r"^(?P<ss58>[\w\d ]+)?(?P<path>(//?[^/]+)*)$")
		.expect("constructed from known-good static value; qed");
	static ref SECRET_PHRASE_REGEX: Regex = Regex::new(r"^(?P<phrase>[\d\w ]+)?(?P<path>(//?[^/]+)*)(///(?P<password>.*))?$")
		.expect("constructed from known-good static value; qed");
	static ref JUNCTION_REGEX: Regex = Regex::new(r"/(/?[^/]+)")
		.expect("constructed from known-good static value; qed");
}

#[cfg(feature = "std")]
impl<T: Sized + AsMut<[u8]> + AsRef<[u8]> + Public + Derive> Ss58Codec for T {
	fn from_string(s: &str) -> Result<Self, PublicError> {
		let cap = SS58_REGEX.captures(s).ok_or(PublicError::InvalidFormat)?;
		let s = cap.name("ss58").map(|r| r.as_str()).unwrap_or(DEV_ADDRESS);
		let addr = if let Some(stripped) = s.strip_prefix("0x") {
			let d = array_bytes::hex2bytes(stripped).map_err(|_| PublicError::InvalidFormat)?;
			Self::from_slice(&d).map_err(|()| PublicError::BadLength)?
		} else {
			Self::from_ss58check(s)?
		};
		if cap["path"].is_empty() {
			Ok(addr)
		} else {
			let path =
				JUNCTION_REGEX.captures_iter(&cap["path"]).map(|f| DeriveJunction::from(&f[1]));
			addr.derive(path).ok_or(PublicError::InvalidPath)
		}
	}

	fn from_string_with_version(s: &str) -> Result<(Self, Ss58AddressFormat), PublicError> {
		let cap = SS58_REGEX.captures(s).ok_or(PublicError::InvalidFormat)?;
		let (addr, v) = Self::from_ss58check_with_version(
			cap.name("ss58").map(|r| r.as_str()).unwrap_or(DEV_ADDRESS),
		)?;
		if cap["path"].is_empty() {
			Ok((addr, v))
		} else {
			let path =
				JUNCTION_REGEX.captures_iter(&cap["path"]).map(|f| DeriveJunction::from(&f[1]));
			addr.derive(path).ok_or(PublicError::InvalidPath).map(|a| (a, v))
		}
	}

Some if the string is a properly encoded SS58Check address, optionally with a derivation path following.

Return the ss58-check string for this key.

Examples found in repository?
src/crypto.rs (line 341)
340
341
342
	fn to_ss58check(&self) -> String {
		self.to_ss58check_with_version(default_ss58_version())
	}

Return the ss58-check string for this key.

Examples found in repository?
src/crypto.rs (line 572)
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
	fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
		write!(f, "{}", self.to_ss58check())
	}
}

impl sp_std::fmt::Debug for AccountId32 {
	#[cfg(feature = "std")]
	fn fmt(&self, f: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result {
		let s = self.to_ss58check();
		write!(f, "{} ({}...)", crate::hexdisplay::HexDisplay::from(&self.0), &s[0..8])
	}

	#[cfg(not(feature = "std"))]
	fn fmt(&self, _: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result {
		Ok(())
	}
}

#[cfg(feature = "std")]
impl serde::Serialize for AccountId32 {
	fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
	where
		S: serde::Serializer,
	{
		serializer.serialize_str(&self.to_ss58check())
	}
More examples
Hide additional examples
src/ecdsa.rs (line 169)
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
	fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
		write!(f, "{}", self.to_ss58check())
	}
}

impl sp_std::fmt::Debug for Public {
	#[cfg(feature = "std")]
	fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
		let s = self.to_ss58check();
		write!(f, "{} ({}...)", crate::hexdisplay::HexDisplay::from(&self.as_ref()), &s[0..8])
	}

	#[cfg(not(feature = "std"))]
	fn fmt(&self, _: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result {
		Ok(())
	}
}

#[cfg(feature = "std")]
impl Serialize for Public {
	fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
	where
		S: Serializer,
	{
		serializer.serialize_str(&self.to_ss58check())
	}
src/ed25519.rs (line 168)
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
	fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
		write!(f, "{}", self.to_ss58check())
	}
}

impl sp_std::fmt::Debug for Public {
	#[cfg(feature = "std")]
	fn fmt(&self, f: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result {
		let s = self.to_ss58check();
		write!(f, "{} ({}...)", crate::hexdisplay::HexDisplay::from(&self.0), &s[0..8])
	}

	#[cfg(not(feature = "std"))]
	fn fmt(&self, _: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result {
		Ok(())
	}
}

#[cfg(feature = "std")]
impl Serialize for Public {
	fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
	where
		S: Serializer,
	{
		serializer.serialize_str(&self.to_ss58check())
	}
src/sr25519.rs (line 171)
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
	fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
		write!(f, "{}", self.to_ss58check())
	}
}

impl sp_std::fmt::Debug for Public {
	#[cfg(feature = "std")]
	fn fmt(&self, f: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result {
		let s = self.to_ss58check();
		write!(f, "{} ({}...)", crate::hexdisplay::HexDisplay::from(&self.0), &s[0..8])
	}

	#[cfg(not(feature = "std"))]
	fn fmt(&self, _: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result {
		Ok(())
	}
}

#[cfg(feature = "std")]
impl Serialize for Public {
	fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
	where
		S: Serializer,
	{
		serializer.serialize_str(&self.to_ss58check())
	}

Some if the string is a properly encoded SS58Check address, optionally with a derivation path following.

Examples found in repository?
src/crypto.rs (line 308)
307
308
309
310
311
312
313
	fn from_string(s: &str) -> Result<Self, PublicError> {
		Self::from_string_with_version(s).and_then(|(r, v)| match v {
			v if !v.is_custom() => Ok(r),
			v if v == default_ss58_version() => Ok(r),
			v => Err(PublicError::UnknownSs58AddressFormat(v)),
		})
	}

Implementors§