Trait sp_core::crypto::ByteArray

source ·
pub trait ByteArray: AsRef<[u8]> + AsMut<[u8]> + for<'a> TryFrom<&'a [u8], Error = ()> {
    const LEN: usize;

    fn from_slice(data: &[u8]) -> Result<Self, ()> { ... }
    fn to_raw_vec(&self) -> Vec<u8>  { ... }
    fn as_slice(&self) -> &[u8]  { ... }
}
Expand description

Trait used for types that are really just a fixed-length array.

Required Associated Constants§

The “length” of the values of this type, which is always the same.

Provided Methods§

A new instance from the given slice that should be Self::LEN bytes long.

Examples found in repository?
src/crypto.rs (line 299)
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
	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)
		}
	}

Return a Vec<u8> filled with raw data.

Examples found in repository?
src/ecdsa.rs (line 110)
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
	fn to_public_crypto_pair(&self) -> CryptoTypePublicPair {
		CryptoTypePublicPair(CRYPTO_ID, self.to_raw_vec())
	}
}

impl From<Public> for CryptoTypePublicPair {
	fn from(key: Public) -> Self {
		(&key).into()
	}
}

impl From<&Public> for CryptoTypePublicPair {
	fn from(key: &Public) -> Self {
		CryptoTypePublicPair(CRYPTO_ID, key.to_raw_vec())
	}
More examples
Hide additional examples
src/ed25519.rs (line 374)
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
	fn to_public_crypto_pair(&self) -> CryptoTypePublicPair {
		CryptoTypePublicPair(CRYPTO_ID, self.to_raw_vec())
	}
}

impl Derive for Public {}

impl From<Public> for CryptoTypePublicPair {
	fn from(key: Public) -> Self {
		(&key).into()
	}
}

impl From<&Public> for CryptoTypePublicPair {
	fn from(key: &Public) -> Self {
		CryptoTypePublicPair(CRYPTO_ID, key.to_raw_vec())
	}
src/sr25519.rs (line 406)
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
	fn to_public_crypto_pair(&self) -> CryptoTypePublicPair {
		CryptoTypePublicPair(CRYPTO_ID, self.to_raw_vec())
	}
}

impl From<Public> for CryptoTypePublicPair {
	fn from(key: Public) -> Self {
		(&key).into()
	}
}

impl From<&Public> for CryptoTypePublicPair {
	fn from(key: &Public) -> Self {
		CryptoTypePublicPair(CRYPTO_ID, key.to_raw_vec())
	}
src/crypto.rs (line 679)
678
679
680
		fn to_public_crypto_pair(&self) -> CryptoTypePublicPair {
			CryptoTypePublicPair(CryptoTypeId(*b"dumm"), <Self as ByteArray>::to_raw_vec(self))
		}

Return a slice filled with raw data.

Examples found in repository?
src/crypto.rs (line 465)
464
465
466
	fn to_raw_vec(&self) -> Vec<u8> {
		self.as_slice().to_vec()
	}

Implementors§