tp_runtime/
multiaddress.rs

1// This file is part of Tetcore.
2
3// Copyright (C) 2017-2021 Parity Technologies (UK) Ltd.
4// SPDX-License-Identifier: Apache-2.0
5
6// Licensed under the Apache License, Version 2.0 (the "License");
7// you may not use this file except in compliance with the License.
8// You may obtain a copy of the License at
9//
10// 	http://www.apache.org/licenses/LICENSE-2.0
11//
12// Unless required by applicable law or agreed to in writing, software
13// distributed under the License is distributed on an "AS IS" BASIS,
14// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15// See the License for the specific language governing permissions and
16// limitations under the License.
17
18//! MultiAddress type is a wrapper for multiple downstream account formats.
19
20use codec::{Encode, Decode};
21use tetcore_std::vec::Vec;
22
23/// A multi-format address wrapper for on-chain accounts.
24#[derive(Encode, Decode, PartialEq, Eq, Clone, crate::RuntimeDebug)]
25#[cfg_attr(feature = "std", derive(Hash))]
26pub enum MultiAddress<AccountId, AccountIndex> {
27	/// It's an account ID (pubkey).
28	Id(AccountId),
29	/// It's an account index.
30	Index(#[codec(compact)] AccountIndex),
31	/// It's some arbitrary raw bytes.
32	Raw(Vec<u8>),
33	/// It's a 32 byte representation.
34	Address32([u8; 32]),
35	/// Its a 20 byte representation.
36	Address20([u8; 20]),
37}
38
39#[cfg(feature = "std")]
40impl<AccountId, AccountIndex> std::fmt::Display for MultiAddress<AccountId, AccountIndex>
41where
42	AccountId: std::fmt::Debug,
43	AccountIndex: std::fmt::Debug,
44{
45	fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
46		use tet_core::hexdisplay::HexDisplay;
47		match self {
48			MultiAddress::Raw(inner) => write!(f, "MultiAddress::Raw({})", HexDisplay::from(inner)),
49			MultiAddress::Address32(inner) => write!(f, "MultiAddress::Address32({})", HexDisplay::from(inner)),
50			MultiAddress::Address20(inner) => write!(f, "MultiAddress::Address20({})", HexDisplay::from(inner)),
51			_ => write!(f, "{:?}", self),
52		}
53	}
54}
55
56impl<AccountId, AccountIndex> From<AccountId> for MultiAddress<AccountId, AccountIndex> {
57	fn from(a: AccountId) -> Self {
58		MultiAddress::Id(a)
59	}
60}
61
62impl<AccountId: Default, AccountIndex> Default for MultiAddress<AccountId, AccountIndex> {
63	fn default() -> Self {
64		MultiAddress::Id(Default::default())
65	}
66}