Implement crypto byte array newtypes in term of a shared type (#3684)

Introduces `CryptoBytes` type defined as:

```rust
pub struct CryptoBytes<const N: usize, Tag = ()>(pub [u8; N], PhantomData<fn() -> Tag>);
```

The type implements a bunch of methods and traits which are typically
expected from a byte array newtype
(NOTE: some of the methods and trait implementations IMO are a bit
redundant, but I decided to maintain them all to not change too much
stuff in this PR)

It also introduces two (generic) typical consumers of `CryptoBytes`:
`PublicBytes` and `SignatureBytes`.

```rust
pub struct PublicTag;
pub PublicBytes<const N: usize, CryptoTag> = CryptoBytes<N, (PublicTag, CryptoTag)>;

pub struct SignatureTag;
pub SignatureBytes<const N: usize, CryptoTag> = CryptoBytes<N, (SignatureTag, CryptoTag)>;
```

Both of them use a tag to differentiate the two types at a higher level.
Downstream specializations will further specialize using a dedicated
crypto tag. For example in ECDSA:


```rust
pub struct EcdsaTag;

pub type Public = PublicBytes<PUBLIC_KEY_SERIALIZED_SIZE, EcdsaTag>;
pub type Signature = PublicBytes<PUBLIC_KEY_SERIALIZED_SIZE, EcdsaTag>;
```

Overall we have a cleaner and most importantly **consistent** code for
all the types involved

All these details are opaque to the end user which can use `Public` and
`Signature` for the cryptos as before
This commit is contained in:
Davide Galassi
2024-03-19 16:47:42 +01:00
committed by GitHub
parent 5fd72a1f5e
commit 1e9fd23776
29 changed files with 492 additions and 1163 deletions
+25 -230
View File
@@ -15,119 +15,45 @@
// See the License for the specific language governing permissions and
// limitations under the License.
// tag::description[]
//! Simple Ed25519 API.
// end::description[]
use sp_std::vec::Vec;
use crate::{
crypto::ByteArray,
hash::{H256, H512},
};
use codec::{Decode, Encode, MaxEncodedLen};
use scale_info::TypeInfo;
#[cfg(feature = "serde")]
use crate::crypto::Ss58Codec;
use crate::crypto::{
CryptoType, CryptoTypeId, Derive, DeriveError, DeriveJunction, FromEntropy, Pair as TraitPair,
Public as TraitPublic, SecretStringError, UncheckedFrom,
ByteArray, CryptoType, CryptoTypeId, Derive, DeriveError, DeriveJunction, Pair as TraitPair,
Public as TraitPublic, PublicBytes, SecretStringError, SignatureBytes,
};
#[cfg(feature = "full_crypto")]
use core::convert::TryFrom;
use ed25519_zebra::{SigningKey, VerificationKey};
#[cfg(feature = "serde")]
use serde::{de, Deserialize, Deserializer, Serialize, Serializer};
use sp_runtime_interface::pass_by::PassByInner;
#[cfg(all(not(feature = "std"), feature = "serde"))]
use sp_std::alloc::{format, string::String};
use sp_std::ops::Deref;
use sp_std::vec::Vec;
/// An identifier used to match public keys against ed25519 keys
pub const CRYPTO_ID: CryptoTypeId = CryptoTypeId(*b"ed25");
/// The byte length of public key
pub const PUBLIC_KEY_SERIALIZED_SIZE: usize = 32;
/// The byte length of signature
pub const SIGNATURE_SERIALIZED_SIZE: usize = 64;
/// A secret seed. It's not called a "secret key" because ring doesn't expose the secret keys
/// of the key pair (yeah, dumb); as such we're forced to remember the seed manually if we
/// will need it later (such as for HDKD).
type Seed = [u8; 32];
#[doc(hidden)]
pub struct Ed25519Tag;
/// A public key.
#[derive(
PartialEq,
Eq,
PartialOrd,
Ord,
Clone,
Copy,
Encode,
Decode,
PassByInner,
MaxEncodedLen,
TypeInfo,
Hash,
)]
pub struct Public(pub [u8; 32]);
pub type Public = PublicBytes<PUBLIC_KEY_SERIALIZED_SIZE, Ed25519Tag>;
/// A key pair.
#[derive(Copy, Clone)]
pub struct Pair {
public: VerificationKey,
secret: SigningKey,
}
impl TraitPublic for Public {}
impl FromEntropy for Public {
fn from_entropy(input: &mut impl codec::Input) -> Result<Self, codec::Error> {
let mut result = Self([0u8; 32]);
input.read(&mut result.0[..])?;
Ok(result)
}
}
impl AsRef<[u8; 32]> for Public {
fn as_ref(&self) -> &[u8; 32] {
&self.0
}
}
impl AsRef<[u8]> for Public {
fn as_ref(&self) -> &[u8] {
&self.0[..]
}
}
impl AsMut<[u8]> for Public {
fn as_mut(&mut self) -> &mut [u8] {
&mut self.0[..]
}
}
impl Deref for Public {
type Target = [u8];
fn deref(&self) -> &Self::Target {
&self.0
}
}
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; Self::LEN];
r.copy_from_slice(data);
Ok(Self::unchecked_from(r))
}
}
impl From<Public> for [u8; 32] {
fn from(x: Public) -> Self {
x.0
}
}
impl Derive for Public {}
#[cfg(feature = "full_crypto")]
impl From<Pair> for Public {
@@ -136,12 +62,6 @@ impl From<Pair> for Public {
}
}
impl From<Public> for H256 {
fn from(x: Public) -> Self {
x.0.into()
}
}
#[cfg(feature = "std")]
impl std::str::FromStr for Public {
type Err = crate::crypto::PublicError;
@@ -151,18 +71,6 @@ impl std::str::FromStr for Public {
}
}
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 {
@@ -204,23 +112,8 @@ impl<'de> Deserialize<'de> for Public {
}
}
/// A signature (a 512-bit value).
#[derive(Encode, Decode, MaxEncodedLen, PassByInner, TypeInfo, PartialEq, Eq, Hash)]
pub struct Signature(pub [u8; 64]);
impl TryFrom<&[u8]> for Signature {
type Error = ();
fn try_from(data: &[u8]) -> Result<Self, Self::Error> {
if data.len() == 64 {
let mut inner = [0u8; 64];
inner.copy_from_slice(data);
Ok(Signature(inner))
} else {
Err(())
}
}
}
/// A signature.
pub type Signature = SignatureBytes<SIGNATURE_SERIALIZED_SIZE, Ed25519Tag>;
#[cfg(feature = "serde")]
impl Serialize for Signature {
@@ -245,44 +138,6 @@ impl<'de> Deserialize<'de> for Signature {
}
}
impl Clone for Signature {
fn clone(&self) -> Self {
let mut r = [0u8; 64];
r.copy_from_slice(&self.0[..]);
Signature(r)
}
}
impl From<Signature> for H512 {
fn from(v: Signature) -> H512 {
H512::from(v.0)
}
}
impl From<Signature> for [u8; 64] {
fn from(v: Signature) -> [u8; 64] {
v.0
}
}
impl AsRef<[u8; 64]> for Signature {
fn as_ref(&self) -> &[u8; 64] {
&self.0
}
}
impl AsRef<[u8]> for Signature {
fn as_ref(&self) -> &[u8] {
&self.0[..]
}
}
impl AsMut<[u8]> for Signature {
fn as_mut(&mut self) -> &mut [u8] {
&mut self.0[..]
}
}
impl sp_std::fmt::Debug for Signature {
#[cfg(feature = "std")]
fn fmt(&self, f: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result {
@@ -295,76 +150,16 @@ impl sp_std::fmt::Debug for Signature {
}
}
impl UncheckedFrom<[u8; 64]> for Signature {
fn unchecked_from(data: [u8; 64]) -> Signature {
Signature(data)
}
/// A key pair.
#[derive(Copy, Clone)]
pub struct Pair {
public: VerificationKey,
secret: SigningKey,
}
impl Signature {
/// A new instance from the given 64-byte `data`.
///
/// NOTE: No checking goes on to ensure this is a real signature. Only use it if
/// you are certain that the array actually is a signature. GIGO!
pub fn from_raw(data: [u8; 64]) -> Signature {
Signature(data)
}
/// A new instance from the given slice that should be 64 bytes long.
///
/// NOTE: No checking goes on to ensure this is a real signature. Only use it if
/// you are certain that the array actually is a signature. GIGO!
pub fn from_slice(data: &[u8]) -> Option<Self> {
if data.len() != 64 {
return None
}
let mut r = [0u8; 64];
r.copy_from_slice(data);
Some(Signature(r))
}
/// A new instance from an H512.
///
/// NOTE: No checking goes on to ensure this is a real signature. Only use it if
/// you are certain that the array actually is a signature. GIGO!
pub fn from_h512(v: H512) -> Signature {
Signature(v.into())
}
}
impl Public {
/// A new instance from the given 32-byte `data`.
///
/// NOTE: No checking goes on to ensure this is a real public key. Only use it if
/// you are certain that the array actually is a pubkey. GIGO!
pub fn from_raw(data: [u8; 32]) -> Self {
Public(data)
}
/// A new instance from an H256.
///
/// NOTE: No checking goes on to ensure this is a real public key. Only use it if
/// you are certain that the array actually is a pubkey. GIGO!
pub fn from_h256(x: H256) -> Self {
Public(x.into())
}
/// Return a slice filled with raw data.
pub fn as_array_ref(&self) -> &[u8; 32] {
self.as_ref()
}
}
impl ByteArray for Public {
const LEN: usize = 32;
}
impl TraitPublic for Public {}
impl Derive for Public {}
/// Derive a single hard junction.
fn derive_hard_junction(secret_seed: &Seed, cc: &[u8; 32]) -> Seed {
use codec::Encode;
("Ed25519HDKD", secret_seed, cc).using_encoded(sp_crypto_hashing::blake2_256)
}
@@ -402,7 +197,7 @@ impl TraitPair for Pair {
/// Get the public key.
fn public(&self) -> Public {
Public(self.public.into())
Public::from_raw(self.public.into())
}
/// Sign a message.