mirror of
https://github.com/pezkuwichain/pezkuwi-subxt.git
synced 2026-06-13 01:11:10 +00:00
Run cargo fmt on the whole code base (#9394)
* Run cargo fmt on the whole code base * Second run * Add CI check * Fix compilation * More unnecessary braces * Handle weights * Use --all * Use correct attributes... * Fix UI tests * AHHHHHHHHH * 🤦 * Docs * Fix compilation * 🤷 * Please stop * 🤦 x 2 * More * make rustfmt.toml consistent with polkadot Co-authored-by: André Silva <andrerfosilva@gmail.com>
This commit is contained in:
@@ -17,9 +17,12 @@
|
||||
|
||||
//! Batch/parallel verification.
|
||||
|
||||
use sp_core::{ed25519, sr25519, ecdsa, crypto::Pair, traits::SpawnNamed};
|
||||
use std::sync::{Arc, atomic::{AtomicBool, Ordering as AtomicOrdering}};
|
||||
use futures::{future::FutureExt, channel::oneshot};
|
||||
use futures::{channel::oneshot, future::FutureExt};
|
||||
use sp_core::{crypto::Pair, ecdsa, ed25519, sr25519, traits::SpawnNamed};
|
||||
use std::sync::{
|
||||
atomic::{AtomicBool, Ordering as AtomicOrdering},
|
||||
Arc,
|
||||
};
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
struct Sr25519BatchItem {
|
||||
@@ -61,7 +64,9 @@ impl BatchVerifier {
|
||||
name: &'static str,
|
||||
) -> bool {
|
||||
// there is already invalid transaction encountered
|
||||
if self.invalid.load(AtomicOrdering::Relaxed) { return false; }
|
||||
if self.invalid.load(AtomicOrdering::Relaxed) {
|
||||
return false
|
||||
}
|
||||
|
||||
let invalid_clone = self.invalid.clone();
|
||||
let (sender, receiver) = oneshot::channel();
|
||||
@@ -78,7 +83,8 @@ impl BatchVerifier {
|
||||
log::warn!("Verification halted while result was pending");
|
||||
invalid_clone.store(true, AtomicOrdering::Relaxed);
|
||||
}
|
||||
}.boxed(),
|
||||
}
|
||||
.boxed(),
|
||||
);
|
||||
|
||||
true
|
||||
@@ -110,7 +116,9 @@ impl BatchVerifier {
|
||||
pub_key: sr25519::Public,
|
||||
message: Vec<u8>,
|
||||
) -> bool {
|
||||
if self.invalid.load(AtomicOrdering::Relaxed) { return false; }
|
||||
if self.invalid.load(AtomicOrdering::Relaxed) {
|
||||
return false
|
||||
}
|
||||
self.sr25519_items.push(Sr25519BatchItem { signature, pub_key, message });
|
||||
|
||||
if self.sr25519_items.len() >= 128 {
|
||||
@@ -163,7 +171,7 @@ impl BatchVerifier {
|
||||
);
|
||||
|
||||
if !Self::verify_sr25519_batch(std::mem::take(&mut self.sr25519_items)) {
|
||||
return false;
|
||||
return false
|
||||
}
|
||||
|
||||
if pending.len() > 0 {
|
||||
@@ -172,10 +180,12 @@ impl BatchVerifier {
|
||||
"substrate_batch_verify_join",
|
||||
async move {
|
||||
futures::future::join_all(pending).await;
|
||||
sender.send(())
|
||||
.expect("Channel never panics if receiver is live. \
|
||||
Receiver is always live until received this data; qed. ");
|
||||
}.boxed(),
|
||||
sender.send(()).expect(
|
||||
"Channel never panics if receiver is live. \
|
||||
Receiver is always live until received this data; qed. ",
|
||||
);
|
||||
}
|
||||
.boxed(),
|
||||
);
|
||||
|
||||
if receiver.recv().is_err() {
|
||||
@@ -184,7 +194,7 @@ impl BatchVerifier {
|
||||
"Haven't received async result from verification task. Returning false.",
|
||||
);
|
||||
|
||||
return false;
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+163
-194
@@ -18,14 +18,16 @@
|
||||
//! I/O host interface for substrate runtime.
|
||||
|
||||
#![warn(missing_docs)]
|
||||
|
||||
#![cfg_attr(not(feature = "std"), no_std)]
|
||||
#![cfg_attr(not(feature = "std"), feature(alloc_error_handler))]
|
||||
|
||||
#![cfg_attr(feature = "std",
|
||||
doc = "Substrate runtime standard library as compiled when linked with Rust's standard library.")]
|
||||
#![cfg_attr(not(feature = "std"),
|
||||
doc = "Substrate's runtime standard library as compiled without Rust's standard library.")]
|
||||
#![cfg_attr(
|
||||
feature = "std",
|
||||
doc = "Substrate runtime standard library as compiled when linked with Rust's standard library."
|
||||
)]
|
||||
#![cfg_attr(
|
||||
not(feature = "std"),
|
||||
doc = "Substrate's runtime standard library as compiled without Rust's standard library."
|
||||
)]
|
||||
|
||||
use sp_std::vec::Vec;
|
||||
|
||||
@@ -35,31 +37,35 @@ use tracing;
|
||||
#[cfg(feature = "std")]
|
||||
use sp_core::{
|
||||
crypto::Pair,
|
||||
traits::{TaskExecutorExt, RuntimeSpawnExt},
|
||||
offchain::{OffchainDbExt, OffchainWorkerExt, TransactionPoolExt},
|
||||
hexdisplay::HexDisplay,
|
||||
offchain::{OffchainDbExt, OffchainWorkerExt, TransactionPoolExt},
|
||||
storage::ChildInfo,
|
||||
traits::{RuntimeSpawnExt, TaskExecutorExt},
|
||||
};
|
||||
#[cfg(feature = "std")]
|
||||
use sp_keystore::{KeystoreExt, SyncCryptoStore};
|
||||
|
||||
use sp_core::{
|
||||
OpaquePeerId, crypto::KeyTypeId, ed25519, sr25519, ecdsa, H256, LogLevel, LogLevelFilter,
|
||||
crypto::KeyTypeId,
|
||||
ecdsa, ed25519,
|
||||
offchain::{
|
||||
Timestamp, HttpRequestId, HttpRequestStatus, HttpError, StorageKind, OpaqueNetworkState,
|
||||
HttpError, HttpRequestId, HttpRequestStatus, OpaqueNetworkState, StorageKind, Timestamp,
|
||||
},
|
||||
sr25519, LogLevel, LogLevelFilter, OpaquePeerId, H256,
|
||||
};
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
use sp_trie::{TrieConfiguration, trie_types::Layout};
|
||||
use sp_trie::{trie_types::Layout, TrieConfiguration};
|
||||
|
||||
use sp_runtime_interface::{runtime_interface, Pointer};
|
||||
use sp_runtime_interface::pass_by::{PassBy, PassByCodec};
|
||||
use sp_runtime_interface::{
|
||||
pass_by::{PassBy, PassByCodec},
|
||||
runtime_interface, Pointer,
|
||||
};
|
||||
|
||||
use codec::{Encode, Decode};
|
||||
use codec::{Decode, Encode};
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
use sp_externalities::{ExternalitiesExt, Externalities};
|
||||
use sp_externalities::{Externalities, ExternalitiesExt};
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
mod batch_verifier;
|
||||
@@ -167,7 +173,6 @@ pub trait Storage {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// Append the encoded `value` to the storage item at `key`.
|
||||
///
|
||||
/// The storage item needs to implement [`EncodeAppend`](codec::EncodeAppend).
|
||||
@@ -255,11 +260,7 @@ pub trait DefaultChildStorage {
|
||||
///
|
||||
/// Parameter `storage_key` is the unprefixed location of the root of the child trie in the parent trie.
|
||||
/// Result is `None` if the value for `key` in the child storage can not be found.
|
||||
fn get(
|
||||
&self,
|
||||
storage_key: &[u8],
|
||||
key: &[u8],
|
||||
) -> Option<Vec<u8>> {
|
||||
fn get(&self, storage_key: &[u8], key: &[u8]) -> Option<Vec<u8>> {
|
||||
let child_info = ChildInfo::new_default(storage_key);
|
||||
self.child_storage(&child_info, key).map(|s| s.to_vec())
|
||||
}
|
||||
@@ -279,25 +280,19 @@ pub trait DefaultChildStorage {
|
||||
value_offset: u32,
|
||||
) -> Option<u32> {
|
||||
let child_info = ChildInfo::new_default(storage_key);
|
||||
self.child_storage(&child_info, key)
|
||||
.map(|value| {
|
||||
let value_offset = value_offset as usize;
|
||||
let data = &value[value_offset.min(value.len())..];
|
||||
let written = std::cmp::min(data.len(), value_out.len());
|
||||
value_out[..written].copy_from_slice(&data[..written]);
|
||||
data.len() as u32
|
||||
})
|
||||
self.child_storage(&child_info, key).map(|value| {
|
||||
let value_offset = value_offset as usize;
|
||||
let data = &value[value_offset.min(value.len())..];
|
||||
let written = std::cmp::min(data.len(), value_out.len());
|
||||
value_out[..written].copy_from_slice(&data[..written]);
|
||||
data.len() as u32
|
||||
})
|
||||
}
|
||||
|
||||
/// Set a child storage value.
|
||||
///
|
||||
/// Set `key` to `value` in the child storage denoted by `storage_key`.
|
||||
fn set(
|
||||
&mut self,
|
||||
storage_key: &[u8],
|
||||
key: &[u8],
|
||||
value: &[u8],
|
||||
) {
|
||||
fn set(&mut self, storage_key: &[u8], key: &[u8], value: &[u8]) {
|
||||
let child_info = ChildInfo::new_default(storage_key);
|
||||
self.set_child_storage(&child_info, key.to_vec(), value.to_vec());
|
||||
}
|
||||
@@ -305,11 +300,7 @@ pub trait DefaultChildStorage {
|
||||
/// Clear a child storage key.
|
||||
///
|
||||
/// For the default child storage at `storage_key`, clear value at `key`.
|
||||
fn clear(
|
||||
&mut self,
|
||||
storage_key: &[u8],
|
||||
key: &[u8],
|
||||
) {
|
||||
fn clear(&mut self, storage_key: &[u8], key: &[u8]) {
|
||||
let child_info = ChildInfo::new_default(storage_key);
|
||||
self.clear_child_storage(&child_info, key);
|
||||
}
|
||||
@@ -318,10 +309,7 @@ pub trait DefaultChildStorage {
|
||||
///
|
||||
/// If it exists, the child storage for `storage_key`
|
||||
/// is removed.
|
||||
fn storage_kill(
|
||||
&mut self,
|
||||
storage_key: &[u8],
|
||||
) {
|
||||
fn storage_kill(&mut self, storage_key: &[u8]) {
|
||||
let child_info = ChildInfo::new_default(storage_key);
|
||||
self.kill_child_storage(&child_info, None);
|
||||
}
|
||||
@@ -352,11 +340,7 @@ pub trait DefaultChildStorage {
|
||||
/// Check a child storage key.
|
||||
///
|
||||
/// Check whether the given `key` exists in default child defined at `storage_key`.
|
||||
fn exists(
|
||||
&self,
|
||||
storage_key: &[u8],
|
||||
key: &[u8],
|
||||
) -> bool {
|
||||
fn exists(&self, storage_key: &[u8], key: &[u8]) -> bool {
|
||||
let child_info = ChildInfo::new_default(storage_key);
|
||||
self.exists_child_storage(&child_info, key)
|
||||
}
|
||||
@@ -364,11 +348,7 @@ pub trait DefaultChildStorage {
|
||||
/// Clear child default key by prefix.
|
||||
///
|
||||
/// Clear the child storage of each key-value pair where the key starts with the given `prefix`.
|
||||
fn clear_prefix(
|
||||
&mut self,
|
||||
storage_key: &[u8],
|
||||
prefix: &[u8],
|
||||
) {
|
||||
fn clear_prefix(&mut self, storage_key: &[u8], prefix: &[u8]) {
|
||||
let child_info = ChildInfo::new_default(storage_key);
|
||||
let _ = self.clear_child_prefix(&child_info, prefix, None);
|
||||
}
|
||||
@@ -397,10 +377,7 @@ pub trait DefaultChildStorage {
|
||||
/// The hashing algorithm is defined by the `Block`.
|
||||
///
|
||||
/// Returns a `Vec<u8>` that holds the SCALE encoded hash.
|
||||
fn root(
|
||||
&mut self,
|
||||
storage_key: &[u8],
|
||||
) -> Vec<u8> {
|
||||
fn root(&mut self, storage_key: &[u8]) -> Vec<u8> {
|
||||
let child_info = ChildInfo::new_default(storage_key);
|
||||
self.child_storage_root(&child_info)
|
||||
}
|
||||
@@ -408,11 +385,7 @@ pub trait DefaultChildStorage {
|
||||
/// Child storage key iteration.
|
||||
///
|
||||
/// Get the next key in storage after the given one in lexicographic order in child storage.
|
||||
fn next_key(
|
||||
&mut self,
|
||||
storage_key: &[u8],
|
||||
key: &[u8],
|
||||
) -> Option<Vec<u8>> {
|
||||
fn next_key(&mut self, storage_key: &[u8], key: &[u8]) -> Option<Vec<u8>> {
|
||||
let child_info = ChildInfo::new_default(storage_key);
|
||||
self.next_child_storage_key(&child_info, key)
|
||||
}
|
||||
@@ -447,7 +420,8 @@ pub trait Trie {
|
||||
&root,
|
||||
proof,
|
||||
&[(key, Some(value))],
|
||||
).is_ok()
|
||||
)
|
||||
.is_ok()
|
||||
}
|
||||
|
||||
/// Verify trie proof
|
||||
@@ -456,7 +430,8 @@ pub trait Trie {
|
||||
&root,
|
||||
proof,
|
||||
&[(key, Some(value))],
|
||||
).is_ok()
|
||||
)
|
||||
.is_ok()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -516,7 +491,7 @@ pub trait Misc {
|
||||
err,
|
||||
);
|
||||
None
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -526,7 +501,8 @@ pub trait Misc {
|
||||
pub trait Crypto {
|
||||
/// Returns all `ed25519` public keys for the given key id from the keystore.
|
||||
fn ed25519_public_keys(&mut self, id: KeyTypeId) -> Vec<ed25519::Public> {
|
||||
let keystore = &***self.extension::<KeystoreExt>()
|
||||
let keystore = &***self
|
||||
.extension::<KeystoreExt>()
|
||||
.expect("No `keystore` associated for the current context!");
|
||||
SyncCryptoStore::ed25519_public_keys(keystore, id)
|
||||
}
|
||||
@@ -539,7 +515,8 @@ pub trait Crypto {
|
||||
/// Returns the public key.
|
||||
fn ed25519_generate(&mut self, id: KeyTypeId, seed: Option<Vec<u8>>) -> ed25519::Public {
|
||||
let seed = seed.as_ref().map(|s| std::str::from_utf8(&s).expect("Seed is valid utf8!"));
|
||||
let keystore = &***self.extension::<KeystoreExt>()
|
||||
let keystore = &***self
|
||||
.extension::<KeystoreExt>()
|
||||
.expect("No `keystore` associated for the current context!");
|
||||
SyncCryptoStore::ed25519_generate_new(keystore, id, seed)
|
||||
.expect("`ed25519_generate` failed")
|
||||
@@ -555,7 +532,8 @@ pub trait Crypto {
|
||||
pub_key: &ed25519::Public,
|
||||
msg: &[u8],
|
||||
) -> Option<ed25519::Signature> {
|
||||
let keystore = &***self.extension::<KeystoreExt>()
|
||||
let keystore = &***self
|
||||
.extension::<KeystoreExt>()
|
||||
.expect("No `keystore` associated for the current context!");
|
||||
SyncCryptoStore::sign_with(keystore, id, &pub_key.into(), msg)
|
||||
.ok()
|
||||
@@ -566,11 +544,7 @@ pub trait Crypto {
|
||||
/// Verify `ed25519` signature.
|
||||
///
|
||||
/// Returns `true` when the verification was successful.
|
||||
fn ed25519_verify(
|
||||
sig: &ed25519::Signature,
|
||||
msg: &[u8],
|
||||
pub_key: &ed25519::Public,
|
||||
) -> bool {
|
||||
fn ed25519_verify(sig: &ed25519::Signature, msg: &[u8], pub_key: &ed25519::Public) -> bool {
|
||||
ed25519::Pair::verify(sig, msg, pub_key)
|
||||
}
|
||||
|
||||
@@ -588,20 +562,16 @@ pub trait Crypto {
|
||||
msg: &[u8],
|
||||
pub_key: &ed25519::Public,
|
||||
) -> bool {
|
||||
self.extension::<VerificationExt>().map(
|
||||
|extension| extension.push_ed25519(sig.clone(), pub_key.clone(), msg.to_vec())
|
||||
).unwrap_or_else(|| ed25519_verify(sig, msg, pub_key))
|
||||
self.extension::<VerificationExt>()
|
||||
.map(|extension| extension.push_ed25519(sig.clone(), pub_key.clone(), msg.to_vec()))
|
||||
.unwrap_or_else(|| ed25519_verify(sig, msg, pub_key))
|
||||
}
|
||||
|
||||
/// Verify `sr25519` signature.
|
||||
///
|
||||
/// Returns `true` when the verification was successful.
|
||||
#[version(2)]
|
||||
fn sr25519_verify(
|
||||
sig: &sr25519::Signature,
|
||||
msg: &[u8],
|
||||
pub_key: &sr25519::Public,
|
||||
) -> bool {
|
||||
fn sr25519_verify(sig: &sr25519::Signature, msg: &[u8], pub_key: &sr25519::Public) -> bool {
|
||||
sr25519::Pair::verify(sig, msg, pub_key)
|
||||
}
|
||||
|
||||
@@ -619,14 +589,15 @@ pub trait Crypto {
|
||||
msg: &[u8],
|
||||
pub_key: &sr25519::Public,
|
||||
) -> bool {
|
||||
self.extension::<VerificationExt>().map(
|
||||
|extension| extension.push_sr25519(sig.clone(), pub_key.clone(), msg.to_vec())
|
||||
).unwrap_or_else(|| sr25519_verify(sig, msg, pub_key))
|
||||
self.extension::<VerificationExt>()
|
||||
.map(|extension| extension.push_sr25519(sig.clone(), pub_key.clone(), msg.to_vec()))
|
||||
.unwrap_or_else(|| sr25519_verify(sig, msg, pub_key))
|
||||
}
|
||||
|
||||
/// Start verification extension.
|
||||
fn start_batch_verify(&mut self) {
|
||||
let scheduler = self.extension::<TaskExecutorExt>()
|
||||
let scheduler = self
|
||||
.extension::<TaskExecutorExt>()
|
||||
.expect("No task executor associated with the current context!")
|
||||
.clone();
|
||||
|
||||
@@ -641,7 +612,8 @@ pub trait Crypto {
|
||||
///
|
||||
/// Will panic if no `VerificationExt` is registered (`start_batch_verify` was not called).
|
||||
fn finish_batch_verify(&mut self) -> bool {
|
||||
let result = self.extension::<VerificationExt>()
|
||||
let result = self
|
||||
.extension::<VerificationExt>()
|
||||
.expect("`finish_batch_verify` should only be called after `start_batch_verify`")
|
||||
.verify_and_clear();
|
||||
|
||||
@@ -653,7 +625,8 @@ pub trait Crypto {
|
||||
|
||||
/// Returns all `sr25519` public keys for the given key id from the keystore.
|
||||
fn sr25519_public_keys(&mut self, id: KeyTypeId) -> Vec<sr25519::Public> {
|
||||
let keystore = &*** self.extension::<KeystoreExt>()
|
||||
let keystore = &***self
|
||||
.extension::<KeystoreExt>()
|
||||
.expect("No `keystore` associated for the current context!");
|
||||
SyncCryptoStore::sr25519_public_keys(keystore, id)
|
||||
}
|
||||
@@ -666,7 +639,8 @@ pub trait Crypto {
|
||||
/// Returns the public key.
|
||||
fn sr25519_generate(&mut self, id: KeyTypeId, seed: Option<Vec<u8>>) -> sr25519::Public {
|
||||
let seed = seed.as_ref().map(|s| std::str::from_utf8(&s).expect("Seed is valid utf8!"));
|
||||
let keystore = &***self.extension::<KeystoreExt>()
|
||||
let keystore = &***self
|
||||
.extension::<KeystoreExt>()
|
||||
.expect("No `keystore` associated for the current context!");
|
||||
SyncCryptoStore::sr25519_generate_new(keystore, id, seed)
|
||||
.expect("`sr25519_generate` failed")
|
||||
@@ -682,7 +656,8 @@ pub trait Crypto {
|
||||
pub_key: &sr25519::Public,
|
||||
msg: &[u8],
|
||||
) -> Option<sr25519::Signature> {
|
||||
let keystore = &***self.extension::<KeystoreExt>()
|
||||
let keystore = &***self
|
||||
.extension::<KeystoreExt>()
|
||||
.expect("No `keystore` associated for the current context!");
|
||||
SyncCryptoStore::sign_with(keystore, id, &pub_key.into(), msg)
|
||||
.ok()
|
||||
@@ -700,7 +675,8 @@ pub trait Crypto {
|
||||
|
||||
/// Returns all `ecdsa` public keys for the given key id from the keystore.
|
||||
fn ecdsa_public_keys(&mut self, id: KeyTypeId) -> Vec<ecdsa::Public> {
|
||||
let keystore = &***self.extension::<KeystoreExt>()
|
||||
let keystore = &***self
|
||||
.extension::<KeystoreExt>()
|
||||
.expect("No `keystore` associated for the current context!");
|
||||
SyncCryptoStore::ecdsa_public_keys(keystore, id)
|
||||
}
|
||||
@@ -713,10 +689,10 @@ pub trait Crypto {
|
||||
/// Returns the public key.
|
||||
fn ecdsa_generate(&mut self, id: KeyTypeId, seed: Option<Vec<u8>>) -> ecdsa::Public {
|
||||
let seed = seed.as_ref().map(|s| std::str::from_utf8(&s).expect("Seed is valid utf8!"));
|
||||
let keystore = &***self.extension::<KeystoreExt>()
|
||||
let keystore = &***self
|
||||
.extension::<KeystoreExt>()
|
||||
.expect("No `keystore` associated for the current context!");
|
||||
SyncCryptoStore::ecdsa_generate_new(keystore, id, seed)
|
||||
.expect("`ecdsa_generate` failed")
|
||||
SyncCryptoStore::ecdsa_generate_new(keystore, id, seed).expect("`ecdsa_generate` failed")
|
||||
}
|
||||
|
||||
/// Sign the given `msg` with the `ecdsa` key that corresponds to the given public key and
|
||||
@@ -729,7 +705,8 @@ pub trait Crypto {
|
||||
pub_key: &ecdsa::Public,
|
||||
msg: &[u8],
|
||||
) -> Option<ecdsa::Signature> {
|
||||
let keystore = &***self.extension::<KeystoreExt>()
|
||||
let keystore = &***self
|
||||
.extension::<KeystoreExt>()
|
||||
.expect("No `keystore` associated for the current context!");
|
||||
SyncCryptoStore::sign_with(keystore, id, &pub_key.into(), msg)
|
||||
.ok()
|
||||
@@ -740,11 +717,7 @@ pub trait Crypto {
|
||||
/// Verify `ecdsa` signature.
|
||||
///
|
||||
/// Returns `true` when the verification was successful.
|
||||
fn ecdsa_verify(
|
||||
sig: &ecdsa::Signature,
|
||||
msg: &[u8],
|
||||
pub_key: &ecdsa::Public,
|
||||
) -> bool {
|
||||
fn ecdsa_verify(sig: &ecdsa::Signature, msg: &[u8], pub_key: &ecdsa::Public) -> bool {
|
||||
ecdsa::Pair::verify(sig, msg, pub_key)
|
||||
}
|
||||
|
||||
@@ -762,9 +735,9 @@ pub trait Crypto {
|
||||
msg: &[u8],
|
||||
pub_key: &ecdsa::Public,
|
||||
) -> bool {
|
||||
self.extension::<VerificationExt>().map(
|
||||
|extension| extension.push_ecdsa(sig.clone(), pub_key.clone(), msg.to_vec())
|
||||
).unwrap_or_else(|| ecdsa_verify(sig, msg, pub_key))
|
||||
self.extension::<VerificationExt>()
|
||||
.map(|extension| extension.push_ecdsa(sig.clone(), pub_key.clone(), msg.to_vec()))
|
||||
.unwrap_or_else(|| ecdsa_verify(sig, msg, pub_key))
|
||||
}
|
||||
|
||||
/// Verify and recover a SECP256k1 ECDSA signature.
|
||||
@@ -778,10 +751,11 @@ pub trait Crypto {
|
||||
sig: &[u8; 65],
|
||||
msg: &[u8; 32],
|
||||
) -> Result<[u8; 64], EcdsaVerifyError> {
|
||||
let rs = secp256k1::Signature::parse_slice(&sig[0..64])
|
||||
.map_err(|_| EcdsaVerifyError::BadRS)?;
|
||||
let v = secp256k1::RecoveryId::parse(if sig[64] > 26 { sig[64] - 27 } else { sig[64] } as u8)
|
||||
.map_err(|_| EcdsaVerifyError::BadV)?;
|
||||
let rs =
|
||||
secp256k1::Signature::parse_slice(&sig[0..64]).map_err(|_| EcdsaVerifyError::BadRS)?;
|
||||
let v =
|
||||
secp256k1::RecoveryId::parse(if sig[64] > 26 { sig[64] - 27 } else { sig[64] } as u8)
|
||||
.map_err(|_| EcdsaVerifyError::BadV)?;
|
||||
let pubkey = secp256k1::recover(&secp256k1::Message::parse(msg), &rs, &v)
|
||||
.map_err(|_| EcdsaVerifyError::BadSignature)?;
|
||||
let mut res = [0u8; 64];
|
||||
@@ -799,10 +773,11 @@ pub trait Crypto {
|
||||
sig: &[u8; 65],
|
||||
msg: &[u8; 32],
|
||||
) -> Result<[u8; 33], EcdsaVerifyError> {
|
||||
let rs = secp256k1::Signature::parse_slice(&sig[0..64])
|
||||
.map_err(|_| EcdsaVerifyError::BadRS)?;
|
||||
let v = secp256k1::RecoveryId::parse(if sig[64] > 26 { sig[64] - 27 } else { sig[64] } as u8)
|
||||
.map_err(|_| EcdsaVerifyError::BadV)?;
|
||||
let rs =
|
||||
secp256k1::Signature::parse_slice(&sig[0..64]).map_err(|_| EcdsaVerifyError::BadRS)?;
|
||||
let v =
|
||||
secp256k1::RecoveryId::parse(if sig[64] > 26 { sig[64] - 27 } else { sig[64] } as u8)
|
||||
.map_err(|_| EcdsaVerifyError::BadV)?;
|
||||
let pubkey = secp256k1::recover(&secp256k1::Message::parse(msg), &rs, &v)
|
||||
.map_err(|_| EcdsaVerifyError::BadSignature)?;
|
||||
Ok(pubkey.serialize_compressed())
|
||||
@@ -907,8 +882,10 @@ pub trait Offchain {
|
||||
/// The transaction will end up in the pool.
|
||||
fn submit_transaction(&mut self, data: Vec<u8>) -> Result<(), ()> {
|
||||
self.extension::<TransactionPoolExt>()
|
||||
.expect("submit_transaction can be called only in the offchain call context with
|
||||
TransactionPool capabilities enabled")
|
||||
.expect(
|
||||
"submit_transaction can be called only in the offchain call context with
|
||||
TransactionPool capabilities enabled",
|
||||
)
|
||||
.submit_transaction(data)
|
||||
}
|
||||
|
||||
@@ -949,8 +926,10 @@ pub trait Offchain {
|
||||
/// offchain worker tasks running on the same machine. It IS persisted between runs.
|
||||
fn local_storage_set(&mut self, kind: StorageKind, key: &[u8], value: &[u8]) {
|
||||
self.extension::<OffchainDbExt>()
|
||||
.expect("local_storage_set can be called only in the offchain call context with
|
||||
OffchainDb extension")
|
||||
.expect(
|
||||
"local_storage_set can be called only in the offchain call context with
|
||||
OffchainDb extension",
|
||||
)
|
||||
.local_storage_set(kind, key, value)
|
||||
}
|
||||
|
||||
@@ -960,8 +939,10 @@ pub trait Offchain {
|
||||
/// offchain worker tasks running on the same machine. It IS persisted between runs.
|
||||
fn local_storage_clear(&mut self, kind: StorageKind, key: &[u8]) {
|
||||
self.extension::<OffchainDbExt>()
|
||||
.expect("local_storage_clear can be called only in the offchain call context with
|
||||
OffchainDb extension")
|
||||
.expect(
|
||||
"local_storage_clear can be called only in the offchain call context with
|
||||
OffchainDb extension",
|
||||
)
|
||||
.local_storage_clear(kind, key)
|
||||
}
|
||||
|
||||
@@ -982,14 +963,11 @@ pub trait Offchain {
|
||||
new_value: &[u8],
|
||||
) -> bool {
|
||||
self.extension::<OffchainDbExt>()
|
||||
.expect("local_storage_compare_and_set can be called only in the offchain call context
|
||||
with OffchainDb extension")
|
||||
.local_storage_compare_and_set(
|
||||
kind,
|
||||
key,
|
||||
old_value.as_deref(),
|
||||
new_value,
|
||||
.expect(
|
||||
"local_storage_compare_and_set can be called only in the offchain call context
|
||||
with OffchainDb extension",
|
||||
)
|
||||
.local_storage_compare_and_set(kind, key, old_value.as_deref(), new_value)
|
||||
}
|
||||
|
||||
/// Gets a value from the local storage.
|
||||
@@ -999,8 +977,10 @@ pub trait Offchain {
|
||||
/// offchain worker tasks running on the same machine. It IS persisted between runs.
|
||||
fn local_storage_get(&mut self, kind: StorageKind, key: &[u8]) -> Option<Vec<u8>> {
|
||||
self.extension::<OffchainDbExt>()
|
||||
.expect("local_storage_get can be called only in the offchain call context with
|
||||
OffchainDb extension")
|
||||
.expect(
|
||||
"local_storage_get can be called only in the offchain call context with
|
||||
OffchainDb extension",
|
||||
)
|
||||
.local_storage_get(kind, key)
|
||||
}
|
||||
|
||||
@@ -1128,12 +1108,7 @@ pub trait Logging {
|
||||
/// Instead of using directly, prefer setting up `RuntimeLogger` and using `log` macros.
|
||||
fn log(level: LogLevel, target: &str, message: &[u8]) {
|
||||
if let Ok(message) = std::str::from_utf8(message) {
|
||||
log::log!(
|
||||
target: target,
|
||||
log::Level::from(level),
|
||||
"{}",
|
||||
message,
|
||||
)
|
||||
log::log!(target: target, log::Level::from(level), "{}", message,)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1153,7 +1128,6 @@ impl<T: Encode + Decode> PassBy for Crossing<T> {
|
||||
}
|
||||
|
||||
impl<T: Encode + Decode> Crossing<T> {
|
||||
|
||||
/// Convert into the inner type
|
||||
pub fn into_inner(self) -> T {
|
||||
self.0
|
||||
@@ -1162,12 +1136,12 @@ impl<T: Encode + Decode> Crossing<T> {
|
||||
|
||||
// useful for testing
|
||||
impl<T> core::default::Default for Crossing<T>
|
||||
where T: core::default::Default + Encode + Decode
|
||||
where
|
||||
T: core::default::Default + Encode + Decode,
|
||||
{
|
||||
fn default() -> Self {
|
||||
Self(Default::default())
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/// Interface to provide tracing facilities for wasm. Modelled after tokios `tracing`-crate
|
||||
@@ -1184,9 +1158,7 @@ pub trait WasmTracing {
|
||||
/// chose to cache the result for the execution of the entire block.
|
||||
fn enabled(&mut self, metadata: Crossing<sp_tracing::WasmMetadata>) -> bool {
|
||||
let metadata: &tracing_core::metadata::Metadata<'static> = (&metadata.into_inner()).into();
|
||||
tracing::dispatcher::get_default(|d| {
|
||||
d.enabled(metadata)
|
||||
})
|
||||
tracing::dispatcher::get_default(|d| d.enabled(metadata))
|
||||
}
|
||||
|
||||
/// Open a new span with the given attributes. Return the u64 Id of the span.
|
||||
@@ -1205,9 +1177,7 @@ pub trait WasmTracing {
|
||||
d.enter(&final_id);
|
||||
final_id.into_u64()
|
||||
}),
|
||||
_ => {
|
||||
0
|
||||
}
|
||||
_ => 0,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1226,19 +1196,18 @@ pub trait WasmTracing {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(all(not(feature="std"), feature="with-tracing"))]
|
||||
#[cfg(all(not(feature = "std"), feature = "with-tracing"))]
|
||||
mod tracing_setup {
|
||||
use super::{wasm_tracing, Crossing};
|
||||
use core::sync::atomic::{AtomicBool, Ordering};
|
||||
use tracing_core::{
|
||||
dispatcher::{Dispatch, set_global_default},
|
||||
span::{Id, Record, Attributes},
|
||||
Metadata, Event,
|
||||
dispatcher::{set_global_default, Dispatch},
|
||||
span::{Attributes, Id, Record},
|
||||
Event, Metadata,
|
||||
};
|
||||
use super::{wasm_tracing, Crossing};
|
||||
|
||||
static TRACING_SET: AtomicBool = AtomicBool::new(false);
|
||||
|
||||
|
||||
/// The PassingTracingSubscriber implements `tracing_core::Subscriber`
|
||||
/// and pushes the information across the runtime interface to the host
|
||||
struct PassingTracingSubsciber;
|
||||
@@ -1256,12 +1225,12 @@ mod tracing_setup {
|
||||
/// Not implemented! We do not support recording values later
|
||||
/// Will panic when used.
|
||||
fn record(&self, span: &Id, values: &Record<'_>) {
|
||||
unimplemented!{} // this usage is not supported
|
||||
unimplemented! {} // this usage is not supported
|
||||
}
|
||||
/// Not implemented! We do not support recording values later
|
||||
/// Will panic when used.
|
||||
fn record_follows_from(&self, span: &Id, follows: &Id) {
|
||||
unimplemented!{ } // this usage is not supported
|
||||
unimplemented! {} // this usage is not supported
|
||||
}
|
||||
fn event(&self, event: &Event<'_>) {
|
||||
wasm_tracing::event(Crossing(event.into()))
|
||||
@@ -1271,7 +1240,6 @@ mod tracing_setup {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// Initialize tracing of sp_tracing on wasm with `with-tracing` enabled.
|
||||
/// Can be called multiple times from within the same process and will only
|
||||
/// set the global bridging subscriber once.
|
||||
@@ -1284,11 +1252,11 @@ mod tracing_setup {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(all(not(feature="std"), feature="with-tracing")))]
|
||||
#[cfg(not(all(not(feature = "std"), feature = "with-tracing")))]
|
||||
mod tracing_setup {
|
||||
/// Initialize tracing of sp_tracing not necessary – noop. To enable build
|
||||
/// without std and with the `with-tracing`-feature.
|
||||
pub fn init_tracing() { }
|
||||
pub fn init_tracing() {}
|
||||
}
|
||||
|
||||
pub use tracing_setup::init_tracing;
|
||||
@@ -1319,14 +1287,16 @@ pub trait Sandbox {
|
||||
return_val_len: u32,
|
||||
state_ptr: Pointer<u8>,
|
||||
) -> u32 {
|
||||
self.sandbox().invoke(
|
||||
instance_idx,
|
||||
&function,
|
||||
&args,
|
||||
return_val_ptr,
|
||||
return_val_len,
|
||||
state_ptr.into(),
|
||||
).expect("Failed to invoke function with sandbox")
|
||||
self.sandbox()
|
||||
.invoke(
|
||||
instance_idx,
|
||||
&function,
|
||||
&args,
|
||||
return_val_ptr,
|
||||
return_val_len,
|
||||
state_ptr.into(),
|
||||
)
|
||||
.expect("Failed to invoke function with sandbox")
|
||||
}
|
||||
|
||||
/// Create a new memory instance with the given `initial` and `maximum` size.
|
||||
@@ -1364,20 +1334,30 @@ pub trait Sandbox {
|
||||
|
||||
/// Teardown the memory instance with the given `memory_idx`.
|
||||
fn memory_teardown(&mut self, memory_idx: u32) {
|
||||
self.sandbox().memory_teardown(memory_idx).expect("Failed to teardown memory with sandbox")
|
||||
self.sandbox()
|
||||
.memory_teardown(memory_idx)
|
||||
.expect("Failed to teardown memory with sandbox")
|
||||
}
|
||||
|
||||
/// Teardown the sandbox instance with the given `instance_idx`.
|
||||
fn instance_teardown(&mut self, instance_idx: u32) {
|
||||
self.sandbox().instance_teardown(instance_idx).expect("Failed to teardown sandbox instance")
|
||||
self.sandbox()
|
||||
.instance_teardown(instance_idx)
|
||||
.expect("Failed to teardown sandbox instance")
|
||||
}
|
||||
|
||||
/// Get the value from a global with the given `name`. The sandbox is determined by the given
|
||||
/// `instance_idx`.
|
||||
///
|
||||
/// Returns `Some(_)` when the requested global variable could be found.
|
||||
fn get_global_val(&mut self, instance_idx: u32, name: &str) -> Option<sp_wasm_interface::Value> {
|
||||
self.sandbox().get_global_val(instance_idx, name).expect("Failed to get global from sandbox")
|
||||
fn get_global_val(
|
||||
&mut self,
|
||||
instance_idx: u32,
|
||||
name: &str,
|
||||
) -> Option<sp_wasm_interface::Value> {
|
||||
self.sandbox()
|
||||
.get_global_val(instance_idx, name)
|
||||
.expect("Failed to get global from sandbox")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1390,11 +1370,13 @@ pub trait RuntimeTasks {
|
||||
///
|
||||
/// This should not be used directly. Use `sp_tasks::spawn` instead.
|
||||
fn spawn(dispatcher_ref: u32, entry: u32, payload: Vec<u8>) -> u64 {
|
||||
sp_externalities::with_externalities(|mut ext|{
|
||||
let runtime_spawn = ext.extension::<RuntimeSpawnExt>()
|
||||
sp_externalities::with_externalities(|mut ext| {
|
||||
let runtime_spawn = ext
|
||||
.extension::<RuntimeSpawnExt>()
|
||||
.expect("Cannot spawn without dynamic runtime dispatcher (RuntimeSpawnExt)");
|
||||
runtime_spawn.spawn_call(dispatcher_ref, entry, payload)
|
||||
}).expect("`RuntimeTasks::spawn`: called outside of externalities context")
|
||||
})
|
||||
.expect("`RuntimeTasks::spawn`: called outside of externalities context")
|
||||
}
|
||||
|
||||
/// Wasm host function for joining a task.
|
||||
@@ -1402,12 +1384,14 @@ pub trait RuntimeTasks {
|
||||
/// This should not be used directly. Use `join` of `sp_tasks::spawn` result instead.
|
||||
fn join(handle: u64) -> Vec<u8> {
|
||||
sp_externalities::with_externalities(|mut ext| {
|
||||
let runtime_spawn = ext.extension::<RuntimeSpawnExt>()
|
||||
let runtime_spawn = ext
|
||||
.extension::<RuntimeSpawnExt>()
|
||||
.expect("Cannot join without dynamic runtime dispatcher (RuntimeSpawnExt)");
|
||||
runtime_spawn.join(handle)
|
||||
}).expect("`RuntimeTasks::join`: called outside of externalities context")
|
||||
})
|
||||
.expect("`RuntimeTasks::join`: called outside of externalities context")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Allocator used by Substrate when executing the Wasm runtime.
|
||||
#[cfg(not(feature = "std"))]
|
||||
@@ -1483,10 +1467,8 @@ pub type SubstrateHostFunctions = (
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use sp_core::{map, storage::Storage, testing::TaskExecutor, traits::TaskExecutorExt};
|
||||
use sp_state_machine::BasicExternalities;
|
||||
use sp_core::{
|
||||
storage::Storage, map, traits::TaskExecutorExt, testing::TaskExecutor,
|
||||
};
|
||||
use std::any::TypeId;
|
||||
|
||||
#[test]
|
||||
@@ -1542,7 +1524,10 @@ mod tests {
|
||||
});
|
||||
|
||||
t.execute_with(|| {
|
||||
assert!(matches!(storage::clear_prefix(b":abc", None), KillStorageResult::AllRemoved(2)));
|
||||
assert!(matches!(
|
||||
storage::clear_prefix(b":abc", None),
|
||||
KillStorageResult::AllRemoved(2)
|
||||
));
|
||||
|
||||
assert!(storage::get(b":a").is_some());
|
||||
assert!(storage::get(b":abdd").is_some());
|
||||
@@ -1583,11 +1568,7 @@ mod tests {
|
||||
}
|
||||
|
||||
// push invlaid
|
||||
crypto::sr25519_batch_verify(
|
||||
&Default::default(),
|
||||
&Vec::new(),
|
||||
&Default::default(),
|
||||
);
|
||||
crypto::sr25519_batch_verify(&Default::default(), &Vec::new(), &Default::default());
|
||||
assert!(!crypto::finish_batch_verify());
|
||||
|
||||
crypto::start_batch_verify();
|
||||
@@ -1607,11 +1588,7 @@ mod tests {
|
||||
ext.execute_with(|| {
|
||||
// invalid ed25519 signature
|
||||
crypto::start_batch_verify();
|
||||
crypto::ed25519_batch_verify(
|
||||
&Default::default(),
|
||||
&Vec::new(),
|
||||
&Default::default(),
|
||||
);
|
||||
crypto::ed25519_batch_verify(&Default::default(), &Vec::new(), &Default::default());
|
||||
assert!(!crypto::finish_batch_verify());
|
||||
|
||||
// 2 valid ed25519 signatures
|
||||
@@ -1637,11 +1614,7 @@ mod tests {
|
||||
let signature = pair.sign(msg);
|
||||
crypto::ed25519_batch_verify(&signature, msg, &pair.public());
|
||||
|
||||
crypto::ed25519_batch_verify(
|
||||
&Default::default(),
|
||||
&Vec::new(),
|
||||
&Default::default(),
|
||||
);
|
||||
crypto::ed25519_batch_verify(&Default::default(), &Vec::new(), &Default::default());
|
||||
|
||||
assert!(!crypto::finish_batch_verify());
|
||||
|
||||
@@ -1673,11 +1646,7 @@ mod tests {
|
||||
let signature = pair.sign(msg);
|
||||
crypto::sr25519_batch_verify(&signature, msg, &pair.public());
|
||||
|
||||
crypto::sr25519_batch_verify(
|
||||
&Default::default(),
|
||||
&Vec::new(),
|
||||
&Default::default(),
|
||||
);
|
||||
crypto::sr25519_batch_verify(&Default::default(), &Vec::new(), &Default::default());
|
||||
|
||||
assert!(!crypto::finish_batch_verify());
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user