Skip to content

Commit 0a6a867

Browse files
committed
Use arkworks to compile in no_std
1 parent 7f8c6ba commit 0a6a867

File tree

19 files changed

+2238
-14752
lines changed

19 files changed

+2238
-14752
lines changed

Cargo.lock

Lines changed: 0 additions & 14505 deletions
This file was deleted.

Cargo.toml

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -345,3 +345,9 @@ partner-chains-demo-runtime = { path = "demo/runtime" }
345345
# Schnorr experiments
346346
schnorr_jubjub = { path = "toolkit/utils/schnorr_jubjub", default-features = false }
347347
hash256-std-hasher = { version = "0.15.2", default-features = false }
348+
ark-ed-on-bls12-381 = { version = "0.5.0", default-features = false }
349+
ark-ff = { version = "0.5.0", default-features = false }
350+
ark-ec = { version = "0.5.0", default-features = false }
351+
ark-serialize = { version = "0.5.0", default-features = false }
352+
rand_core = {version = "0.6.4", default-features = false }
353+
sha2 = {version = "0.10.9", default-features = false }

demo/runtime/Cargo.toml

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -99,12 +99,7 @@ sp-block-producer-fees = { workspace = true }
9999
pallet-block-producer-fees = { workspace = true }
100100

101101
sp-io = { workspace = true }
102-
schnorr_jubjub = { workspace = true }
103-
midnight-circuits = { git = "https://github.com/midnightntwrk/midnight-circuits", branch = "iquerejeta/committee_proof"}
104-
halo2curves = { version = "0.7.0", features = ["derive_serde"] }
105-
blstrs = { git = "https://github.com/davidnevadoc/blstrs", rev = "3dfe5bf" }
106-
group = "0.13"
107-
ff = "0.13"
102+
#schnorr_jubjub = { workspace = true }
108103

109104
[dev-dependencies]
110105
sp-keyring = { workspace = true }
@@ -187,6 +182,7 @@ std = [
187182
"sp-block-participation/std",
188183
"pallet-governed-map/std",
189184
"sp-governed-map/std",
185+
# "schnorr_jubjub/std",
190186
]
191187

192188
runtime-benchmarks = [

demo/runtime/src/lib.rs

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,6 @@ use sp_core::ByteArray;
5454
use sp_core::{OpaqueMetadata, crypto::KeyTypeId};
5555
use sp_governed_map::MainChainScriptsV1;
5656
use sp_inherents::InherentIdentifier;
57-
use sp_runtime::traits::Keccak256;
5857
use sp_runtime::{
5958
ApplyExtrinsicResult, MultiSignature, Perbill, generic, impl_opaque_keys,
6059
traits::{
@@ -67,6 +66,8 @@ use sp_sidechain::SidechainStatus;
6766
use sp_std::prelude::*;
6867
use sp_version::RuntimeVersion;
6968
use sp_weights::Weight;
69+
use schnorr_jubjub::PoseidonJubjub;
70+
use crate::mmr::Hashing;
7071

7172
// Make the WASM binary available.
7273
#[cfg(feature = "std")]
@@ -662,8 +663,10 @@ parameter_types! {
662663
pub const BeefySetIdSessionEntries: u32 = BondingDuration::get() * SessionsPerEra::get();
663664
}
664665

666+
665667
impl pallet_beefy::Config for Runtime {
666668
type BeefyId = BeefyId;
669+
type SignatureHasher = PoseidonJubjub;
667670
type MaxAuthorities = MaxValidators;
668671
type MaxNominators = ConstU32<0>;
669672
type MaxSetIdSessionEntries = BeefySetIdSessionEntries;
@@ -689,7 +692,8 @@ mod mmr {
689692

690693
impl pallet_mmr::Config for Runtime {
691694
const INDEXING_PREFIX: &'static [u8] = b"mmr";
692-
type Hashing = Keccak256;
695+
// TODO: Think about changing the leaf data (so that encode/decode can be efficient)
696+
type Hashing = PoseidonJubjub;
693697
type LeafData = pallet_mmr::ParentNumberAndHash<Self>;
694698
type OnNewRoot = pallet_beefy_mmr::DepositBeefyDigest<Runtime>;
695699
type BlockHashProvider = pallet_mmr::DefaultBlockHashProvider<Runtime>;

toolkit/committee-selection/authority-selection-inherents/src/filter_invalid_candidates.rs

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ use frame_support::pallet_prelude::TypeInfo;
55
use parity_scale_codec::{Decode, Encode};
66
use plutus::*;
77
use plutus_datum_derive::ToDatum;
8-
use schnorr_jubjub;
8+
// use schnorr_jubjub;
99
#[cfg(feature = "std")]
1010
use serde::{Deserialize, Serialize};
1111
use sidechain_domain::*;
@@ -107,7 +107,7 @@ pub fn filter_trustless_candidates_registrations<TAccountId, TAccountKeys>(
107107
genesis_utxo: UtxoId,
108108
) -> Vec<(Candidate<TAccountId, TAccountKeys>, selection::Weight)>
109109
where
110-
TAccountKeys: From<(sr25519::Public, schnorr_jubjub::Public, ed25519::Public)>,
110+
TAccountKeys: From<(sr25519::Public, ed25519::Public, ed25519::Public)>,
111111
TAccountId: From<ecdsa::Public>,
112112
{
113113
candidate_registrations
@@ -126,7 +126,7 @@ pub fn filter_invalid_permissioned_candidates<TAccountId, TAccountKeys>(
126126
permissioned_candidates: Vec<PermissionedCandidateData>,
127127
) -> Vec<Candidate<TAccountId, TAccountKeys>>
128128
where
129-
TAccountKeys: From<(sr25519::Public, schnorr_jubjub::Public, ed25519::Public)>,
129+
TAccountKeys: From<(sr25519::Public, ed25519::Public, ed25519::Public)>,
130130
TAccountId: TryFrom<sidechain_domain::SidechainPublicKey>,
131131
{
132132
permissioned_candidates
@@ -146,7 +146,7 @@ fn select_latest_valid_candidate<TAccountId, TAccountKeys>(
146146
) -> Option<CandidateWithStake<TAccountId, TAccountKeys>>
147147
where
148148
TAccountId: From<ecdsa::Public>,
149-
TAccountKeys: From<(sr25519::Public, schnorr_jubjub::Public, ed25519::Public)>,
149+
TAccountKeys: From<(sr25519::Public, ed25519::Public, ed25519::Public)>,
150150
{
151151
let stake_delegation = validate_stake(candidate_registrations.stake_delegation).ok()?;
152152
let stake_pool_pub_key = candidate_registrations.stake_pool_public_key;
@@ -241,7 +241,7 @@ pub enum PermissionedCandidateDataError {
241241
pub fn validate_permissioned_candidate_data<AccountId: TryFrom<SidechainPublicKey>>(
242242
candidate: PermissionedCandidateData,
243243
) -> Result<
244-
(AccountId, sr25519::Public, schnorr_jubjub::Public, ed25519::Public),
244+
(AccountId, sr25519::Public, ed25519::Public, ed25519::Public),
245245
PermissionedCandidateDataError,
246246
> {
247247
Ok((
@@ -255,7 +255,7 @@ pub fn validate_permissioned_candidate_data<AccountId: TryFrom<SidechainPublicKe
255255
.ok_or(PermissionedCandidateDataError::InvalidAuraKey)?,
256256
candidate
257257
.beefy_public_key
258-
.try_into_schnorr()
258+
.try_into_ed25519()
259259
.ok_or(PermissionedCandidateDataError::InvalidBeefyKey)?,
260260
candidate
261261
.grandpa_public_key
@@ -276,7 +276,7 @@ pub fn validate_registration_data(
276276
registration_data: &RegistrationData,
277277
genesis_utxo: UtxoId,
278278
) -> Result<
279-
(ecdsa::Public, (sr25519::Public, schnorr_jubjub::Public, ed25519::Public)),
279+
(ecdsa::Public, (sr25519::Public, ed25519::Public, ed25519::Public)),
280280
RegistrationDataError,
281281
> {
282282
let aura_pub_key = registration_data
@@ -285,7 +285,7 @@ pub fn validate_registration_data(
285285
.ok_or(RegistrationDataError::InvalidAuraKey)?;
286286
let beefy_pub_key = registration_data
287287
.beefy_pub_key
288-
.try_into_schnorr()
288+
.try_into_ed25519()
289289
.ok_or(RegistrationDataError::InvalidBeefyKey)?;
290290
let grandpa_pub_key = registration_data
291291
.grandpa_pub_key

toolkit/committee-selection/authority-selection-inherents/src/select_authorities.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ use sp_core::{U256, ecdsa, ed25519, sr25519};
1414
/// Seed is constructed from the MC epoch nonce and the sidechain epoch.
1515
pub fn select_authorities<
1616
TAccountId: Clone + Ord + TryFrom<sidechain_domain::SidechainPublicKey> + From<ecdsa::Public>,
17-
TAccountKeys: Clone + Ord + From<(sr25519::Public, schnorr_jubjub::Public, ed25519::Public)>,
17+
TAccountKeys: Clone + Ord + From<(sr25519::Public, ed25519::Public, ed25519::Public)>,
1818
>(
1919
genesis_utxo: UtxoId,
2020
input: AuthoritySelectionInputs,

toolkit/sidechain/domain/src/lib.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1051,8 +1051,8 @@ impl From<sr25519::Public> for AuraPublicKey {
10511051
pub struct BeefyPublicKey(pub Vec<u8>);
10521052
impl BeefyPublicKey {
10531053
/// Attempts to cast this public key to a valid [ecdsa::Public]
1054-
pub fn try_into_schnorr(&self) -> Option<schnorr_jubjub::Public> {
1055-
Some(schnorr_jubjub::Public::try_from(self.0.as_slice()).ok()?)
1054+
pub fn try_into_ed25519(&self) -> Option<ed25519::Public> {
1055+
Some(ed25519::Public::try_from(self.0.as_slice()).ok()?)
10561056
}
10571057
}
10581058

toolkit/utils/schnorr_jubjub/Cargo.toml

Lines changed: 41 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -7,30 +7,63 @@ repository.workspace = true
77
version.workspace = true
88

99
[dependencies]
10-
midnight-circuits = { git = "https://github.com/midnightntwrk/midnight-circuits", branch = "iquerejeta/committee_proof"}
11-
halo2curves = { version = "0.7.0", features = ["derive_serde"] }
12-
blstrs = { git = "https://github.com/davidnevadoc/blstrs", rev = "3dfe5bf" }
13-
group = "0.13"
14-
ff = "0.13"
1510
frame-support = { workspace = true }
1611
pallet-beefy-mmr = { workspace = true }
1712
parity-scale-codec = { workspace = true }
18-
rand_core = "0.6.4"
13+
rand_core = { workspace = true }
1914
scale-info = {workspace = true}
2015
sc-keystore = { workspace = true }
21-
sp-core = { workspace = true }
16+
sp-core = { workspace = true, features = ["serde"] }
2217
sp-application-crypto = { workspace = true }
2318
sp-consensus-beefy = { workspace = true }
2419
sp-runtime = { workspace = true }
2520
sp-runtime-interface = { workspace = true }
2621
sp-io = { workspace = true }
2722
sp-keystore = { workspace = true }
2823
sp-externalities = { workspace = true }
29-
sha2 = "0.10.9"
24+
sha2 = { workspace = true }
3025
serde = {workspace = true }
3126
hex = {workspace = true }
3227
hash256-std-hasher = { workspace = true }
3328
sp-trie = { workspace = true }
29+
rand = { version = "0.8.5", default-features = false }
30+
rand_chacha = { version = "0.3.1", default-features = false }
31+
#rand = { workspace = true }
32+
#rand_chacha = { workspace = true }
33+
ark-ed-on-bls12-381 = { workspace = true }
34+
ark-ff = { workspace = true }
35+
ark-ec = { workspace = true }
36+
ark-serialize = { workspace = true }
37+
38+
39+
[features]
40+
default = ["std"]
41+
std = [
42+
"ark-ed-on-bls12-381/std",
43+
"ark-ff/std",
44+
"ark-ec/std",
45+
"ark-serialize/std",
46+
"frame-support/std",
47+
"pallet-beefy-mmr/std",
48+
"parity-scale-codec/std",
49+
"rand_core/std",
50+
"scale-info/std",
51+
"sp-core/std",
52+
"sp-application-crypto/std",
53+
"sp-consensus-beefy/std",
54+
"sp-runtime/std",
55+
"sp-runtime-interface/std",
56+
"sp-io/std",
57+
"sp-keystore/std",
58+
"sp-externalities/std",
59+
"sha2/std",
60+
"serde/std",
61+
"hex/std",
62+
"hash256-std-hasher/std",
63+
"sp-trie/std",
64+
"rand/std",
65+
"rand_chacha/std",
66+
]
3467

3568
[lints]
3669
workspace = true

toolkit/utils/schnorr_jubjub/src/beefy_structures.rs

Lines changed: 19 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -6,16 +6,19 @@
66
//! protocol, ensuring compatibility with Substrate's runtime and cryptographic
77
//! infrastructure.
88
9-
use core::fmt::{Debug, Formatter};
10-
use std::{convert::TryInto, fmt::Display, hash::Hash};
9+
use alloc::vec::Vec;
10+
use core::fmt::{Debug, Display, Formatter};
11+
// use std::{convert::TryInto, fmt::Display, hash::Hash};
1112

1213
use crate::poseidon::PoseidonJubjub;
13-
use blstrs::{Fr, JubjubSubgroup};
14-
use group::{Group, GroupEncoding};
14+
use ark_ed_on_bls12_381::{Fr, EdwardsAffine};
15+
use ark_ff::fields::Field;
16+
use ark_ec::AffineRepr;
17+
use ark_serialize::CanonicalSerialize;
1518
use rand_core::OsRng;
1619
use serde::{Deserialize, Deserializer, Serialize, Serializer};
1720
use sha2::Digest;
18-
use sp_consensus_beefy::{AuthorityIdBound, BeefyAuthorityId, BeefySignatureHasher};
21+
use sp_consensus_beefy::{AuthorityIdBound, BeefyAuthorityId};
1922
use sp_core::{
2023
ByteArray, Decode, DecodeWithMemTracking, DeriveJunction, Encode, MaxEncodedLen,
2124
Pair as TraitPair,
@@ -29,6 +32,7 @@ use sp_runtime::{
2932
app_crypto::{AppCrypto, AppPair, AppPublic, AppSignature},
3033
traits::Convert,
3134
};
35+
use sp_runtime::biguint::BigUint;
3236

3337
use crate::primitive::{SchnorrSignature, VerifyingKey};
3438

@@ -69,7 +73,7 @@ pub type InnerPublicBytes = PublicBytes<PUBLIC_SERIALIZED_SIZE, SchnorrJubJubTag
6973
pub struct Public(pub InnerPublicBytes);
7074

7175
impl Display for Public {
72-
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
76+
fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
7377
write!(f, "0x{}", hex::encode(self.as_slice()))
7478
}
7579
}
@@ -108,6 +112,7 @@ impl Debug for Public {
108112
}
109113

110114
impl AuthorityIdBound for Public {
115+
type SignatureHasher = PoseidonJubjub;
111116
type BoundedSignature = Signature;
112117
}
113118

@@ -269,8 +274,8 @@ impl TraitPair for crate::primitive::KeyPair {
269274

270275
let h = sha2::Sha512::digest(&seed);
271276

272-
let secret = Fr::from_bytes_wide(&h.as_slice().try_into().unwrap());
273-
Ok(Self { 0: secret, 1: JubjubSubgroup::generator() * &secret })
277+
let secret = Fr::from_random_bytes(h.as_slice()).expect("Failed to deserialize random bytes. This is a bug.");
278+
Ok(Self { 0: secret, 1: (EdwardsAffine::generator() * &secret).into() })
274279
}
275280

276281
fn sign(&self, message: &[u8]) -> Self::Signature {
@@ -297,15 +302,17 @@ impl TraitPair for crate::primitive::KeyPair {
297302
}
298303

299304
fn public(&self) -> Self::Public {
300-
let bytes: [u8; 32] = self.1.to_bytes().try_into().unwrap();
305+
let mut writer = Vec::new();
306+
self.1.serialize_compressed(&mut writer).expect("Serialisation should not fail - writer is big enough");
307+
let bytes: [u8; 32] = writer.try_into().unwrap();
301308

302309
Public(PublicBytes::from(bytes))
303310
}
304311

305312
fn to_raw_vec(&self) -> Vec<u8> {
306313
let mut res = Vec::with_capacity(64);
307-
res.extend_from_slice(&self.0.to_bytes());
308-
res.extend_from_slice(&self.1.to_bytes());
314+
self.0.serialize_compressed(&mut res);
315+
self.1.serialize_compressed(&mut res);
309316

310317
res
311318
}
@@ -339,7 +346,7 @@ impl AppPair for crate::primitive::KeyPair {
339346
/// [`crate::primitive::KeyPair`].
340347
type Seed = [u8; SEED_SERIALIZED_SIZE];
341348

342-
impl BeefyAuthorityId<BeefySignatureHasher> for Public {
349+
impl BeefyAuthorityId<PoseidonJubjub> for Public {
343350
fn verify(&self, signature: &<Self as RuntimeAppPublic>::Signature, msg: &[u8]) -> bool {
344351
<crate::primitive::KeyPair as TraitPair>::verify(signature, msg, self)
345352
}

toolkit/utils/schnorr_jubjub/src/keystore.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
//! signatures over the JubJub curve, which the default implementation does not
66
//! support due to lack of genericity.
77
8+
use alloc::vec::Vec;
89
use sc_keystore::LocalKeystore;
910
use sp_application_crypto::Pair as TraitPair;
1011
use sp_core::{

0 commit comments

Comments
 (0)