use super::*;
use serde::de::{Error, Visitor};
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use std::fmt::Formatter;
use std::{
convert::{TryFrom, TryInto},
fmt,
iter::FusedIterator,
mem,
};
mod builder;
pub use builder::Builder;
pub mod iter;
mod ext;
pub use ext::AccountIdExt;
#[derive(Clone, Copy, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct AccountId(RawAccountId);
impl AccountId {
pub const MAX_DEPTH: AccountIdDepth = 7;
pub fn from_raw(raw: RawAccountId) -> Result<Self, AccountIdError> {
let depth = usize::from((raw as AccountIdDepth) & ACCOUNT_ID_DEPTH_MASK);
if depth > usize::from(Self::MAX_DEPTH) {
return Err(AccountIdError::InvalidDepth);
}
let issuance_count = depth / 2;
let leaf_count = depth % 2;
let chain_bit_count = ROOT_ACCOUNT_INDEX_BIT_COUNT
+ (ISSUANCE_ACCOUNT_INDEX_BIT_COUNT + 1) * issuance_count
+ (LEAF_ACCOUNT_INDEX_BIT_COUNT + 1) * leaf_count;
let unused_bit_count =
mem::size_of::<RawAccountId>() * 8 - ACCOUNT_ID_DEPTH_BIT_COUNT - chain_bit_count;
let unused_mask: RawAccountId = ((1 << unused_bit_count) - 1) << ACCOUNT_ID_DEPTH_BIT_COUNT;
let mut expected_bits: RawAccountId = 0;
let mut next_issuance_flag: RawAccountId =
1 << (mem::size_of::<RawAccountId>() * 8 - ROOT_ACCOUNT_INDEX_BIT_COUNT - 1);
for _ in 0..issuance_count {
expected_bits |= next_issuance_flag;
next_issuance_flag >>= ISSUANCE_ACCOUNT_INDEX_BIT_COUNT + 1;
}
let issuance_flag_mask = if leaf_count != 0 {
expected_bits | next_issuance_flag
} else {
expected_bits
};
if raw & (issuance_flag_mask | unused_mask) != expected_bits {
return Err(AccountIdError::InvalidSpecialBits);
}
Ok(Self(raw))
}
pub const unsafe fn from_raw_unchecked(raw: RawAccountId) -> Self {
Self(raw)
}
pub fn from_root_account_index<RootIndexT>(index: RootIndexT) -> Result<Self, AccountIdError>
where
RootIndexT: TryInto<RootAccountIndex>,
AccountIdError: From<RootIndexT::Error>,
{
Ok(Self(
(index.try_into()?.as_raw() as RawAccountId)
<< (mem::size_of::<RawAccountId>() * 8 - ROOT_ACCOUNT_INDEX_BIT_COUNT),
))
}
#[inline]
pub const fn as_raw(self) -> RawAccountId {
self.0
}
#[inline]
pub const fn depth(self) -> AccountIdDepth {
(self.0 as AccountIdDepth) & ACCOUNT_ID_DEPTH_MASK
}
#[inline]
pub const fn is_leaf(self) -> bool {
self.0 & 0x1 != 0
}
#[inline]
pub const fn is_issuance(self) -> bool {
self.0 & 0x1 == 0
}
#[inline]
pub const fn root_account_index(self) -> RootAccountIndex {
let index_offset = mem::size_of::<RawAccountId>() * 8 - ROOT_ACCOUNT_INDEX_BIT_COUNT;
let raw_index = (self.0 >> index_offset) as RawAccountIndex & ROOT_ACCOUNT_INDEX_MASK;
RootAccountIndex(raw_index)
}
#[inline]
pub fn hierarchy(self) -> iter::AccountHierarchyIter {
iter::AccountHierarchyIter::new(self)
}
#[inline]
pub fn issuance_account_indexes(self) -> iter::IssuanceAccountIndexIter {
iter::IssuanceAccountIndexIter::new(self)
}
#[inline]
pub fn leaf_account_index(self) -> Option<LeafAccountIndex> {
let depth = usize::from(self.depth());
if depth & 0x1 == 0 {
return None;
}
let issuance_count = depth / 2;
let index_offset = mem::size_of::<RawAccountId>() * 8
- ROOT_ACCOUNT_INDEX_BIT_COUNT
- (ISSUANCE_ACCOUNT_INDEX_BIT_COUNT + 1) * issuance_count
- (LEAF_ACCOUNT_INDEX_BIT_COUNT + 1);
let raw_index = (self.0 >> index_offset) as RawAccountIndex & LEAF_ACCOUNT_INDEX_MASK;
Some(LeafAccountIndex(raw_index))
}
#[inline]
pub fn account_indexes(self) -> iter::AccountIndexIter {
iter::AccountIndexIter::new(self)
}
pub fn parent_id(self) -> Option<Self> {
let depth = usize::from(self.depth());
if depth == 0 {
return None;
}
let depth = (depth - 1) & !0x1;
let issuance_count = depth / 2;
let chain_bit_count =
ROOT_ACCOUNT_INDEX_BIT_COUNT + (ISSUANCE_ACCOUNT_INDEX_BIT_COUNT + 1) * issuance_count;
let chain_shift = mem::size_of::<RawAccountId>() * 8 - chain_bit_count;
let chain_mask: RawAccountId = ((1 << chain_bit_count) - 1) << chain_shift;
Some(Self((self.0 & chain_mask) | depth as RawAccountId))
}
#[inline]
pub fn child_id(
self,
child_index: impl Into<NonRootAccountIndex>,
) -> Result<Self, AccountIdError> {
let mut builder = Builder::from_id(self)?;
Ok(match child_index.into() {
NonRootAccountIndex::Issuance(index) => builder.push(index)?.issuance_id(),
NonRootAccountIndex::Leaf(index) => builder.leaf_id(index)?,
})
}
pub fn is_descendant_of(self, id: AccountId) -> bool {
if !id.is_issuance() || self.depth() <= id.depth() {
return false;
}
let id_shift = mem::size_of::<RawAccountId>() * 8
- ROOT_ACCOUNT_INDEX_BIT_COUNT
- (ISSUANCE_ACCOUNT_INDEX_BIT_COUNT + 1) * (id.depth() as usize / 2);
let id_mask = u128::MAX << id_shift;
(self.0 ^ id.0) & id_mask == 0
}
pub fn is_eq_or_descendant_of(self, id: AccountId) -> bool {
self == id || self.is_descendant_of(id)
}
#[inline]
pub fn to_be_bytes(self) -> [u8; mem::size_of::<RawAccountId>()] {
self.0.to_be_bytes()
}
#[inline]
pub fn to_vec(self) -> Vec<u8> {
self.0.to_be_bytes().to_vec()
}
#[inline]
pub fn try_from_be_bytes(
bytes: [u8; mem::size_of::<RawAccountId>()],
) -> Result<Self, AccountIdError> {
Self::from_raw(RawAccountId::from_be_bytes(bytes))
}
#[inline]
pub fn try_from_be_slice(bytes: &[u8]) -> Result<Self, AccountIdError> {
Self::from_raw(RawAccountId::from_be_bytes(
bytes.try_into().map_err(|_| AccountIdError::InvalidLen)?,
))
}
}
impl TryFrom<&[u8]> for AccountId {
type Error = AccountIdError;
#[inline]
fn try_from(bytes: &[u8]) -> Result<Self, Self::Error> {
Self::try_from_be_slice(bytes)
}
}
#[cfg(feature = "format")]
impl std::str::FromStr for AccountId {
type Err = AccountIdError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let s_clean: String = s.chars().filter(|&c| c != '-').collect();
if s_clean.len() != 32 {
return Err(AccountIdError::InvalidLen);
}
let mut buf = [0u8; 16];
hex::decode_to_slice(&s_clean, &mut buf).map_err(|_| AccountIdError::InvalidLen)?;
Self::try_from_be_bytes(buf)
}
}
impl Serialize for AccountId {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
use serde::ser::Error;
let mut buffer = [0u8; 32];
hex::encode_to_slice(self.to_be_bytes(), &mut buffer).map_err(S::Error::custom)?;
serializer.serialize_str(std::str::from_utf8(&buffer).map_err(S::Error::custom)?)
}
}
struct HexAccountId;
impl Visitor<'_> for HexAccountId {
type Value = AccountId;
fn expecting(&self, formatter: &mut Formatter) -> fmt::Result {
formatter.write_str("Hex-encoded byte buffer")
}
fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
where
E: Error,
{
let mut buffer = [0u8; 16];
hex::decode_to_slice(v, &mut buffer).map_err(E::custom)?;
let id = AccountId::try_from_be_bytes(buffer).map_err(E::custom)?;
Ok(id)
}
}
impl<'de> Deserialize<'de> for AccountId {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
deserializer.deserialize_str(HexAccountId)
}
}
impl TryFrom<RawAccountId> for AccountId {
type Error = AccountIdError;
#[inline]
fn try_from(raw: RawAccountId) -> Result<Self, Self::Error> {
Self::from_raw(raw)
}
}
impl From<AccountId> for RawAccountId {
#[inline]
fn from(id: AccountId) -> Self {
id.as_raw()
}
}
#[cfg(feature = "format")]
impl fmt::Display for AccountId {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", hex::encode(self.to_be_bytes()))
}
}
impl fmt::Debug for AccountId {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "[{}", self.root_account_index())?;
for index in self.issuance_account_indexes() {
write!(f, ", {}", index)?;
}
if let Some(index) = self.leaf_account_index() {
write!(f, "; {}", index)?;
}
write!(f, "]")
}
}
#[macro_export]
macro_rules! account_id {
($root:expr, $($idx:expr),* $(,)?) => {
(|| -> ::core::result::Result<_, $crate::account::AccountIdError> {
#[allow(unused_mut)]
let mut builder = $crate::account::id::Builder::from_root_account_index($root)?;
$(builder.push($idx)?;)*
Ok(builder.issuance_id())
})()
};
($root:expr) => {
$crate::account_id!($root,)
};
($root:expr, $($idx:expr),*; $leaf:expr $(,)?) => {
(|| -> ::core::result::Result<_, $crate::account::AccountIdError> {
#[allow(unused_mut)]
let mut builder = $crate::account::id::Builder::from_root_account_index($root)?;
$(builder.push($idx)?;)*
builder.leaf_id($leaf)
})()
};
($root:expr; $leaf:expr $(,)?) => {
$crate::account_id!($root,; $leaf)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn account_id_builder() {
let mut builder =
Builder::from_root_account_index(0).expect("Could not establish root account");
builder
.push(1)
.expect("Could not push an issuance account onto the root");
builder
.push(2)
.expect("Could not push an issuance account onto an issuance account");
builder
.push(3)
.expect("Could not push an issuance account onto an issuance account");
let id_from_builder = builder.issuance_id();
let id_from_chain = AccountId::from_root_account_index(0)
.expect("Could not create a root account id")
.child_id(IssuanceAccountIndex::new(1).expect("Could not create issuance index 1"))
.expect("Could not get account id from root + issuance 1")
.child_id(IssuanceAccountIndex::new(2).expect("Could not create issuance index 2"))
.expect("Could not get account id from root + issuance 1 + issuance 2")
.child_id(IssuanceAccountIndex::new(3).expect("Could not create issuance index 3"))
.expect("Could not get account id from root + issuance 1..3");
assert_eq!(
id_from_builder, id_from_chain,
"Got {} vs {}",
id_from_builder, id_from_chain,
);
let id_from_builder = builder
.leaf_id(10)
.expect("Could not push a leaf account onto an issuance account");
let id_from_chain = id_from_chain
.child_id(LeafAccountIndex::new(10).expect("Could not create leaf index 10"))
.expect("Could not get account id from root + issuance 1..3 + leaf 10");
assert_eq!(
id_from_builder, id_from_chain,
"Got {} vs {}",
id_from_builder, id_from_chain,
);
}
}