mirror of
https://github.com/serai-dex/serai.git
synced 2025-12-08 04:09:23 +00:00
Processor (#259)
* Initial work on a message box * Finish message-box (untested) * Expand documentation * Embed the recipient in the signature challenge Prevents a message from A -> B from being read as from A -> C. * Update documentation by bifurcating sender/receiver * Panic on receiving an invalid signature If we've received an invalid signature in an authenticated system, a service is malicious, critically faulty (equivalent to malicious), or the message layer has been compromised (or is otherwise critically faulty). Please note a receiver who handles a message they shouldn't will trigger this. That falls under being critically faulty. * Documentation and helper methods SecureMessage::new and SecureMessage::serialize. Secure Debug for MessageBox. * Have SecureMessage not be serialized by default Allows passing around in-memory, if desired, and moves the error from decrypt to new (which performs deserialization). Decrypt no longer has an error since it panics if given an invalid signature, due to this being intranet code. * Explain and improve nonce handling Includes a missing zeroize call. * Rebase to latest develop Updates to transcript 0.2.0. * Add a test for the MessageBox * Export PrivateKey and PublicKey * Also test serialization * Add a key_gen binary to message_box * Have SecureMessage support Serde * Add encrypt_to_bytes and decrypt_from_bytes * Support String ser via base64 * Rename encrypt/decrypt to encrypt_bytes/decrypt_to_bytes * Directly operate with values supporting Borsh * Use bincode instead of Borsh By staying inside of serde, we'll support many more structs. While bincode isn't canonical, we don't need canonicity on an authenticated, internal system. * Turn PrivateKey, PublicKey into structs Uses Zeroizing for the PrivateKey per #150. * from_string functions intended for loading from an env * Use &str for PublicKey from_string (now from_str) The PrivateKey takes the String to take ownership of its memory and zeroize it. That isn't needed with PublicKeys. * Finish updating from develop * Resolve warning * Use ZeroizingAlloc on the key_gen binary * Move message-box from crypto/ to common/ * Move key serialization functions to ser * add/remove functions in MessageBox * Implement Hash on dalek_ff_group Points * Make MessageBox generic to its key Exposes a &'static str variant for internal use and a RistrettoPoint variant for external use. * Add Private to_string as deprecated Stub before more competent tooling is deployed. * Private to_public * Test both Internal and External MessageBox, only use PublicKey in the pub API * Remove panics on invalid signatures Leftover from when this was solely internal which is now unsafe. * Chicken scratch a Scanner task * Add a write function to the DKG library Enables writing directly to a file. Also modifies serialize to return Zeroizing<Vec<u8>> instead of just Vec<u8>. * Make dkg::encryption pub * Remove encryption from MessageBox * Use a 64-bit block number in Substrate We use a 64-bit block number in general since u32 only works for 120 years (with a 1 second block time). As some chains even push the 1 second threshold, especially ones based on DAG consensus, this becomes potentially as low as 60 years. While that should still be plenty, it's not worth wondering/debating. Since Serai uses 64-bit block numbers elsewhere, this ensures consistency. * Misc crypto lints * Get the scanner scratch to compile * Initial scanner test * First few lines of scheduler * Further work on scheduler, solidify API * Define Scheduler TX format * Branch creation algorithm * Document when the branch algorithm isn't perfect * Only scanned confirmed blocks * Document Coin * Remove Canonical/ChainNumber from processor The processor should be abstracted from canonical numbers thanks to the coordinator, making this unnecessary. * Add README documenting processor flow * Use Zeroize on substrate primitives * Define messages from/to the processor * Correct over-specified versioning * Correct build re: in_instructions::primitives * Debug/some serde in crypto/ * Use a struct for ValidatorSetInstance * Add a processor key_gen task Redos DB handling code. * Replace trait + impl with wrapper struct * Add a key confirmation flow to the key gen task * Document concerns on key_gen * Start on a signer task * Add Send to FROST traits * Move processor lib.rs to main.rs Adds a dummy main to reduce clippy dead_code warnings. * Further flesh out main.rs * Move the DB trait to AsRef<[u8]> * Signer task * Remove a panic in bitcoin when there's insufficient funds Unchecked underflow. * Have Monero's mine_block mine one block, not 10 It was initially a nicety to deal with the 10 block lock. C::CONFIRMATIONS should be used for that instead. * Test signer * Replace channel expects with log statements The expects weren't problematic and had nicer code. They just clutter test output. * Remove the old wallet file It predates the coordinator design and shouldn't be used. * Rename tests/scan.rs to tests/scanner.rs * Add a wallet test Complements the recently removed wallet file by adding a test for the scanner, scheduler, and signer together. * Work on a run function Triggers a clippy ICE. * Resolve clippy ICE The issue was the non-fully specified lambda in signer. * Add KeyGenEvent and KeyGenOrder Needed so we get KeyConfirmed messages from the key gen task. While we could've read the CoordinatorMessage to see that, routing through the key gen tasks ensures we only handle it once it's been successfully saved to disk. * Expand scanner test * Clarify processor documentation * Have the Scanner load keys on boot/save outputs to disk * Use Vec<u8> for Block ID Much more flexible. * Panic if we see the same output multiple times * Have the Scanner DB mark itself as corrupt when doing a multi-put This REALLY should be a TX. Since we don't have a TX API right now, this at least offers detection. * Have DST'd DB keys accept AsRef<[u8]> * Restore polling all signers Writes a custom future to do so. Also loads signers on boot using what the scanner claims are active keys. * Schedule OutInstructions Adds a data field to Payment. Also cleans some dead code. * Panic if we create an invalid transaction Saves the TX once it's successfully signed so if we do panic, we have a copy. * Route coordinator messages to their respective signer Requires adding key to the SignId. * Send SignTransaction orders for all plans * Add a timer to retry sign_plans when prepare_send fails * Minor fmt'ing * Basic Fee API * Move the change key into Plan * Properly route activation_number * Remove ScannerEvent::Block It's not used under current designs * Nicen logs * Add utilities to get a block's number * Have main issue AckBlock Also has a few misc lints. * Parse instructions out of outputs * Tweak TODOs and remove an unwrap * Update Bitcoin max input/output quantity * Only read one piece of data from Monero Due to output randomization, it's infeasible. * Embed plan IDs into the TXs they create We need to stop attempting signing if we've already signed a protocol. Ideally, any one of the participating signers should be able to provide a proof the TX was successfully signed. We can't just run a second signing protocol though as a single malicious signer could complete the TX signature, and publish it, yet not complete the secondary signature. The TX itself has to be sufficient to show that the TX matches the plan. This is done by embedding the ID, so matching addresses/amounts plans are distinguished, and by allowing verification a TX actually matches a set of addresses/amounts. For Monero, this will need augmenting with the ephemeral keys (or usage of a static seed for them). * Don't use OP_RETURN to encode the plan ID on Bitcoin We can use the inputs to distinguih identical-output plans without issue. * Update OP_RETURN data access It's not required to be the last output. * Add Eventualities to Monero An Eventuality is an effective equivalent to a SignableTransaction. That is declared not by the inputs it spends, yet the outputs it creates. Eventualities are also bound to a 32-byte RNG seed, enabling usage of a hash-based identifier in a SignableTransaction, allowing multiple SignableTransactions with the same output set to have different Eventualities. In order to prevent triggering the burning bug, the RNG seed is hashed with the planned-to-be-used inputs' output keys. While this does bind to them, it's only loosely bound. The TX actually created may use different inputs entirely if a forgery is crafted (which requires no brute forcing). Binding to the key images would provide a strong binding, yet would require knowing the key images, which requires active communication with the spend key. The purpose of this is so a multisig can identify if a Transaction the entire group planned has been executed by a subset of the group or not. Once a plan is created, it can have an Eventuality made. The Eventuality's extra is able to be inserted into a HashMap, so all new on-chain transactions can be trivially checked as potential candidates. Once a potential candidate is found, a check involving ECC ops can be performed. While this is arguably a DoS vector, the underlying Monero blockchain would need to be spammed with transactions to trigger it. Accordingly, it becomes a Monero blockchain DoS vector, when this code is written on the premise of the Monero blockchain functioning. Accordingly, it is considered handled. If a forgery does match, it must have created the exact same outputs the multisig would've. Accordingly, it's argued the multisig shouldn't mind. This entire suite of code is only necessary due to the lack of outgoing view keys, yet it's able to avoid an interactive protocol to communicate key images on every single received output. While this could be locked to the multisig feature, there's no practical benefit to doing so. * Add support for encoding Monero address to instructions * Move Serai's Monero address encoding into serai-client serai-client is meant to be a single library enabling using Serai. While it was originally written as an RPC client for Serai, apps actually using Serai will primarily be sending transactions on connected networks. Sending those transactions require proper {In, Out}Instructions, including proper address encoding. Not only has address encoding been moved, yet the subxt client is now behind a feature. coin integrations have their own features, which are on by default. primitives are always exposed. * Reorganize file layout a bit, add feature flags to processor * Tidy up ETH Dockerfile * Add Bitcoin address encoding * Move Bitcoin::Address to serai-client's * Comment where tweaking needs to happen * Add an API to check if a plan was completed in a specific TX This allows any participating signer to submit the TX ID to prevent further signing attempts. Also performs some API cleanup. * Minimize FROST dependencies * Use a seeded RNG for key gen * Tweak keys from Key gen * Test proper usage of Branch/Change addresses Adds a more descriptive error to an error case in decoys, and pads Monero payments as needed. * Also test spending the change output * Add queued_plans to the Scheduler queued_plans is for payments to be issued when an amount appears, yet the amount is currently pre-fee. One the output is actually created, the Scheduler should be notified of the amount it was created with, moving from queued_plans to plans under the actual amount. Also tightens debug_asserts to asserts for invariants which may are at risk of being exclusive to prod. * Add missing tweak_keys call * Correct decoy selection height handling * Add a few log statements to the scheduler * Simplify test's get_block_number * Simplify, while making more robust, branch address handling in Scheduler * Have fees deducted from payments Corrects Monero's handling of fees when there's no change address. Adds a DUST variable, as needed due to 1_00_000_000 not being enough to pay its fee on Monero. * Add comment to Monero * Consolidate BTC/XMR prepare_send code These aren't fully consolidated. We'd need a SignableTransaction trait for that. This is a lot cleaner though. * Ban integrated addresses The reasoning why is accordingly documented. * Tidy TODOs/dust handling * Update README TODO * Use a determinisitic protocol version in Monero * Test rebuilt KeyGen machines function as expected * Use a more robust KeyGen entropy system * Add DB TXNs Also load entropy from env * Add a loop for processing messages from substrate Allows detecting if we're behind, and if so, waiting to handle the message * Set Monero MAX_INPUTS properly The previous number was based on an old hard fork. With the ring size having increased, transactions have since got larger. * Distinguish TODOs into TODO and TODO2s TODO2s are for after protonet * Zeroize secret share repr in ThresholdCore write * Work on Eventualities Adds serialization and stops signing when an eventuality is proven. * Use a more robust DB key schema * Update to {k, p}256 0.12 * cargo +nightly clippy * cargo update * Slight message-box tweaks * Update to recent Monero merge * Add a Coordinator trait for communication with coordinator * Remove KeyGenHandle for just KeyGen While KeyGen previously accepted instructions over a channel, this breaks the ack flow needed for coordinator communication. Now, KeyGen is the direct object with a handle() function for messages. Thankfully, this ended up being rather trivial for KeyGen as it has no background tasks. * Add a handle function to Signer Enables determining when it's finished handling a CoordinatorMessage and therefore creating an acknowledgement. * Save transactions used to complete eventualities * Use a more intelligent sleep in the signer * Emit SignedTransaction with the first ID *we can still get from our node* * Move Substrate message handling into the new coordinator recv loop * Add handle function to Scanner * Remove the plans timer Enables ensuring the ordring on the handling of plans. * Remove the outputs function which panicked if a precondition wasn't met The new API only returns outputs upon satisfaction of the precondition. * Convert SignerOrder::SignTransaction to a function * Remove the key_gen object from sign_plans * Refactor out get_fee/prepare_send into dedicated functions * Save plans being signed to the DB * Reload transactions being signed on boot * Stop reloading TXs being signed (and report it to peers) * Remove message-box from the processor branch We don't use it here yet. * cargo +nightly fmt * Move back common/zalloc * Update subxt to 0.27 * Zeroize ^1.5, not 1 * Update GitHub workflow * Remove usage of SignId in completed
This commit is contained in:
@@ -8,7 +8,7 @@ use jsonrpsee_http_client::HttpClientBuilder;
|
||||
|
||||
use sp_inherents::{Error, InherentData, InherentIdentifier};
|
||||
|
||||
use in_instructions_pallet::{INHERENT_IDENTIFIER, Updates, InherentError};
|
||||
use in_instructions_pallet::{primitives::Updates, INHERENT_IDENTIFIER, InherentError};
|
||||
|
||||
pub struct InherentDataProvider;
|
||||
impl InherentDataProvider {
|
||||
|
||||
@@ -17,9 +17,6 @@ thiserror = { version = "1", optional = true }
|
||||
scale = { package = "parity-scale-codec", version = "3", default-features = false, features = ["derive", "max-encoded-len"] }
|
||||
scale-info = { version = "2", default-features = false, features = ["derive"] }
|
||||
|
||||
serde = { version = "1", optional = true }
|
||||
|
||||
sp-std = { git = "https://github.com/serai-dex/substrate", default-features = false }
|
||||
sp-inherents = { git = "https://github.com/serai-dex/substrate", default-features = false }
|
||||
sp-runtime = { git = "https://github.com/serai-dex/substrate", default-features = false }
|
||||
|
||||
@@ -38,9 +35,6 @@ std = [
|
||||
"scale/std",
|
||||
"scale-info/std",
|
||||
|
||||
"serde",
|
||||
|
||||
"sp-std/std",
|
||||
"sp-inherents/std",
|
||||
"sp-runtime/std",
|
||||
|
||||
|
||||
@@ -3,12 +3,7 @@
|
||||
#![cfg_attr(not(feature = "std"), no_std)]
|
||||
|
||||
use scale::{Encode, Decode};
|
||||
use scale_info::TypeInfo;
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
use serde::{Serialize, Deserialize};
|
||||
|
||||
use sp_std::vec::Vec;
|
||||
use sp_inherents::{InherentIdentifier, IsFatalError};
|
||||
|
||||
use sp_runtime::RuntimeDebug;
|
||||
@@ -16,29 +11,10 @@ use sp_runtime::RuntimeDebug;
|
||||
use serai_primitives::{BlockNumber, BlockHash, Coin, WithAmount, Balance};
|
||||
|
||||
pub use in_instructions_primitives as primitives;
|
||||
use primitives::InInstruction;
|
||||
use primitives::{InInstruction, Updates};
|
||||
|
||||
pub const INHERENT_IDENTIFIER: InherentIdentifier = *b"ininstrs";
|
||||
|
||||
#[derive(Clone, PartialEq, Eq, Encode, Decode, TypeInfo, RuntimeDebug)]
|
||||
#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
|
||||
pub struct Batch {
|
||||
pub id: BlockHash,
|
||||
pub instructions: Vec<WithAmount<InInstruction>>,
|
||||
}
|
||||
|
||||
#[derive(Clone, PartialEq, Eq, Encode, Decode, TypeInfo, RuntimeDebug)]
|
||||
#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
|
||||
pub struct Update {
|
||||
// Coin's latest block number
|
||||
pub block_number: BlockNumber,
|
||||
pub batches: Vec<Batch>,
|
||||
}
|
||||
|
||||
// None if the current block producer isn't operating over this coin or otherwise failed to get
|
||||
// data
|
||||
pub type Updates = Vec<Option<Update>>;
|
||||
|
||||
#[derive(Clone, Copy, Encode, RuntimeDebug)]
|
||||
#[cfg_attr(feature = "std", derive(Decode, thiserror::Error))]
|
||||
pub enum InherentError {
|
||||
@@ -94,7 +70,7 @@ pub mod pallet {
|
||||
use super::*;
|
||||
|
||||
#[pallet::config]
|
||||
pub trait Config: frame_system::Config<BlockNumber = u32> + TokensConfig {
|
||||
pub trait Config: frame_system::Config<BlockNumber = u64> + TokensConfig {
|
||||
type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;
|
||||
}
|
||||
|
||||
|
||||
@@ -11,14 +11,32 @@ all-features = true
|
||||
rustdoc-args = ["--cfg", "docsrs"]
|
||||
|
||||
[dependencies]
|
||||
zeroize = { version = "^1.5", features = ["derive"], optional = true }
|
||||
|
||||
scale = { package = "parity-scale-codec", version = "3", default-features = false, features = ["derive"] }
|
||||
scale-info = { version = "2", default-features = false, features = ["derive"] }
|
||||
|
||||
serde = { version = "1", features = ["derive"], optional = true }
|
||||
|
||||
sp-std = { git = "https://github.com/serai-dex/substrate", default-features = false }
|
||||
sp-runtime = { git = "https://github.com/serai-dex/substrate", default-features = false }
|
||||
|
||||
serai-primitives = { path = "../../serai/primitives", default-features = false }
|
||||
tokens-primitives = { path = "../../tokens/primitives", default-features = false }
|
||||
|
||||
[features]
|
||||
std = ["scale/std", "scale-info/std", "serde", "serai-primitives/std", "tokens-primitives/std"]
|
||||
std = [
|
||||
"zeroize",
|
||||
|
||||
"scale/std",
|
||||
"scale-info/std",
|
||||
|
||||
"serde",
|
||||
|
||||
"sp-std/std",
|
||||
"sp-runtime/std",
|
||||
|
||||
"serai-primitives/std",
|
||||
"tokens-primitives/std"
|
||||
]
|
||||
default = ["std"]
|
||||
|
||||
@@ -2,40 +2,66 @@
|
||||
#![cfg_attr(docsrs, feature(doc_auto_cfg))]
|
||||
#![cfg_attr(not(feature = "std"), no_std)]
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
use zeroize::Zeroize;
|
||||
|
||||
use scale::{Encode, Decode, MaxEncodedLen};
|
||||
use scale_info::TypeInfo;
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
use serde::{Serialize, Deserialize};
|
||||
|
||||
use serai_primitives::{SeraiAddress, ExternalAddress, Data};
|
||||
#[cfg(not(feature = "std"))]
|
||||
use sp_std::vec::Vec;
|
||||
use sp_runtime::RuntimeDebug;
|
||||
|
||||
use serai_primitives::{BlockNumber, BlockHash, SeraiAddress, ExternalAddress, Data, WithAmount};
|
||||
|
||||
mod shorthand;
|
||||
pub use shorthand::*;
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Debug, Encode, Decode, MaxEncodedLen, TypeInfo)]
|
||||
#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
|
||||
#[cfg_attr(feature = "std", derive(Zeroize, Serialize, Deserialize))]
|
||||
pub enum Application {
|
||||
DEX,
|
||||
}
|
||||
|
||||
#[derive(Clone, PartialEq, Eq, Debug, Encode, Decode, MaxEncodedLen, TypeInfo)]
|
||||
#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
|
||||
#[cfg_attr(feature = "std", derive(Zeroize, Serialize, Deserialize))]
|
||||
pub struct ApplicationCall {
|
||||
application: Application,
|
||||
data: Data,
|
||||
}
|
||||
|
||||
#[derive(Clone, PartialEq, Eq, Debug, Encode, Decode, MaxEncodedLen, TypeInfo)]
|
||||
#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
|
||||
#[cfg_attr(feature = "std", derive(Zeroize, Serialize, Deserialize))]
|
||||
pub enum InInstruction {
|
||||
Transfer(SeraiAddress),
|
||||
Call(ApplicationCall),
|
||||
}
|
||||
|
||||
#[derive(Clone, PartialEq, Eq, Debug, Encode, Decode, MaxEncodedLen, TypeInfo)]
|
||||
#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
|
||||
#[cfg_attr(feature = "std", derive(Zeroize, Serialize, Deserialize))]
|
||||
pub struct RefundableInInstruction {
|
||||
pub origin: Option<ExternalAddress>,
|
||||
pub instruction: InInstruction,
|
||||
}
|
||||
|
||||
#[derive(Clone, PartialEq, Eq, Encode, Decode, TypeInfo, RuntimeDebug)]
|
||||
#[cfg_attr(feature = "std", derive(Zeroize, Serialize, Deserialize))]
|
||||
pub struct Batch {
|
||||
pub id: BlockHash,
|
||||
pub instructions: Vec<WithAmount<InInstruction>>,
|
||||
}
|
||||
|
||||
#[derive(Clone, PartialEq, Eq, Encode, Decode, TypeInfo, RuntimeDebug)]
|
||||
#[cfg_attr(feature = "std", derive(Zeroize, Serialize, Deserialize))]
|
||||
pub struct Update {
|
||||
// Coin's latest block number
|
||||
pub block_number: BlockNumber,
|
||||
pub batches: Vec<Batch>,
|
||||
}
|
||||
|
||||
// None if the current block producer isn't operating over this coin or otherwise failed to get
|
||||
// data
|
||||
pub type Updates = Vec<Option<Update>>;
|
||||
|
||||
@@ -1,3 +1,6 @@
|
||||
#[cfg(feature = "std")]
|
||||
use zeroize::Zeroize;
|
||||
|
||||
use scale::{Encode, Decode, MaxEncodedLen};
|
||||
use scale_info::TypeInfo;
|
||||
|
||||
@@ -13,7 +16,7 @@ use crate::RefundableInInstruction;
|
||||
use crate::InInstruction;
|
||||
|
||||
#[derive(Clone, PartialEq, Eq, Debug, Encode, Decode, MaxEncodedLen, TypeInfo)]
|
||||
#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
|
||||
#[cfg_attr(feature = "std", derive(Zeroize, Serialize, Deserialize))]
|
||||
pub enum Shorthand {
|
||||
Raw(Data),
|
||||
Swap {
|
||||
|
||||
@@ -57,8 +57,8 @@ pub fn create_benchmark_extrinsic(
|
||||
system::CheckTxVersion::<Runtime>::new(),
|
||||
system::CheckGenesis::<Runtime>::new(),
|
||||
system::CheckEra::<Runtime>::from(sp_runtime::generic::Era::mortal(
|
||||
u64::from(BlockHashCount::get().checked_next_power_of_two().map(|c| c / 2).unwrap_or(2)),
|
||||
client.chain_info().best_number.into(),
|
||||
BlockHashCount::get().checked_next_power_of_two().map(|c| c / 2).unwrap_or(2),
|
||||
client.chain_info().best_number,
|
||||
)),
|
||||
system::CheckNonce::<Runtime>::from(nonce),
|
||||
system::CheckWeight::<Runtime>::new(),
|
||||
|
||||
@@ -55,7 +55,7 @@ use transaction_payment::CurrencyAdapter;
|
||||
use session::PeriodicSessions;
|
||||
|
||||
/// An index to a block.
|
||||
pub type BlockNumber = u32;
|
||||
pub type BlockNumber = u64;
|
||||
|
||||
/// Index of a transaction in the chain, for a given account.
|
||||
pub type Index = u32;
|
||||
@@ -100,7 +100,7 @@ pub const BLOCK_SIZE: u32 = 1024 * 1024;
|
||||
pub const TARGET_BLOCK_TIME: u64 = 6;
|
||||
|
||||
/// Measured in blocks.
|
||||
pub const MINUTES: BlockNumber = 60 / (TARGET_BLOCK_TIME as BlockNumber);
|
||||
pub const MINUTES: BlockNumber = 60 / TARGET_BLOCK_TIME;
|
||||
pub const HOURS: BlockNumber = MINUTES * 60;
|
||||
pub const DAYS: BlockNumber = HOURS * 24;
|
||||
|
||||
@@ -249,7 +249,7 @@ impl in_instructions::Config for Runtime {
|
||||
}
|
||||
|
||||
const SESSION_LENGTH: BlockNumber = 5 * DAYS;
|
||||
type Sessions = PeriodicSessions<ConstU32<{ SESSION_LENGTH }>, ConstU32<{ SESSION_LENGTH }>>;
|
||||
type Sessions = PeriodicSessions<ConstU64<{ SESSION_LENGTH }>, ConstU64<{ SESSION_LENGTH }>>;
|
||||
|
||||
pub struct IdentityValidatorIdOf;
|
||||
impl Convert<PublicKey, Option<PublicKey>> for IdentityValidatorIdOf {
|
||||
|
||||
@@ -13,18 +13,31 @@ all-features = true
|
||||
rustdoc-args = ["--cfg", "docsrs"]
|
||||
|
||||
[dependencies]
|
||||
thiserror = "1"
|
||||
thiserror = { version = "1", optional = true }
|
||||
|
||||
scale = { package = "parity-scale-codec", version = "3" }
|
||||
scale-info = "2"
|
||||
scale-value = "0.6"
|
||||
scale-info = { version = "2", optional = true }
|
||||
|
||||
sp-core = { git = "https://github.com/serai-dex/substrate", version = "7" }
|
||||
|
||||
serai-primitives = { path = "../primitives", version = "0.1" }
|
||||
serai-runtime = { path = "../../runtime", version = "0.1" }
|
||||
|
||||
subxt = "0.25"
|
||||
sp-core = { git = "https://github.com/serai-dex/substrate" }
|
||||
subxt = { version = "0.27", default-features = false, features = ["jsonrpsee-ws"], optional = true }
|
||||
|
||||
bitcoin = { version = "0.29", optional = true }
|
||||
|
||||
ciphersuite = { path = "../../../crypto/ciphersuite", version = "0.2", optional = true }
|
||||
monero-serai = { path = "../../../coins/monero", version = "0.1.3-alpha", optional = true }
|
||||
|
||||
[features]
|
||||
serai = ["thiserror", "scale-info", "subxt"]
|
||||
|
||||
coins = []
|
||||
bitcoin = ["coins", "dep:bitcoin"]
|
||||
monero = ["coins", "ciphersuite/ed25519", "monero-serai"]
|
||||
|
||||
# Assumes the default usage is to use Serai as a DEX, which doesn't actually
|
||||
# require connecting to a Serai node
|
||||
default = ["bitcoin", "monero"]
|
||||
|
||||
[dev-dependencies]
|
||||
lazy_static = "1"
|
||||
|
||||
89
substrate/serai/client/src/coins/bitcoin.rs
Normal file
89
substrate/serai/client/src/coins/bitcoin.rs
Normal file
@@ -0,0 +1,89 @@
|
||||
use core::str::FromStr;
|
||||
|
||||
use scale::{Encode, Decode};
|
||||
|
||||
use bitcoin::{
|
||||
hashes::{Hash as HashTrait, hash160::Hash},
|
||||
PubkeyHash, ScriptHash,
|
||||
network::constants::Network,
|
||||
util::address::{Error, WitnessVersion, Payload, Address as BAddress},
|
||||
};
|
||||
|
||||
#[derive(Clone, PartialEq, Eq, Debug)]
|
||||
pub struct Address(pub BAddress);
|
||||
|
||||
impl FromStr for Address {
|
||||
type Err = Error;
|
||||
fn from_str(str: &str) -> Result<Address, Error> {
|
||||
BAddress::from_str(str).map(Address)
|
||||
}
|
||||
}
|
||||
|
||||
impl ToString for Address {
|
||||
fn to_string(&self) -> String {
|
||||
self.0.to_string()
|
||||
}
|
||||
}
|
||||
|
||||
// SCALE-encoded variant of Monero addresses.
|
||||
#[derive(Clone, PartialEq, Eq, Debug, Encode, Decode)]
|
||||
enum EncodedAddress {
|
||||
P2PKH([u8; 20]),
|
||||
P2SH([u8; 20]),
|
||||
P2WPKH([u8; 20]),
|
||||
P2WSH([u8; 32]),
|
||||
P2TR([u8; 32]),
|
||||
}
|
||||
|
||||
impl TryFrom<Vec<u8>> for Address {
|
||||
type Error = ();
|
||||
fn try_from(data: Vec<u8>) -> Result<Address, ()> {
|
||||
Ok(Address(BAddress {
|
||||
network: Network::Bitcoin,
|
||||
payload: match EncodedAddress::decode(&mut data.as_ref()).map_err(|_| ())? {
|
||||
EncodedAddress::P2PKH(hash) => {
|
||||
Payload::PubkeyHash(PubkeyHash::from_hash(Hash::from_inner(hash)))
|
||||
}
|
||||
EncodedAddress::P2SH(hash) => {
|
||||
Payload::ScriptHash(ScriptHash::from_hash(Hash::from_inner(hash)))
|
||||
}
|
||||
EncodedAddress::P2WPKH(hash) => {
|
||||
Payload::WitnessProgram { version: WitnessVersion::V0, program: hash.to_vec() }
|
||||
}
|
||||
EncodedAddress::P2WSH(hash) => {
|
||||
Payload::WitnessProgram { version: WitnessVersion::V0, program: hash.to_vec() }
|
||||
}
|
||||
EncodedAddress::P2TR(hash) => {
|
||||
Payload::WitnessProgram { version: WitnessVersion::V1, program: hash.to_vec() }
|
||||
}
|
||||
},
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(clippy::from_over_into)]
|
||||
impl TryInto<Vec<u8>> for Address {
|
||||
type Error = ();
|
||||
fn try_into(self) -> Result<Vec<u8>, ()> {
|
||||
Ok(
|
||||
(match self.0.payload {
|
||||
Payload::PubkeyHash(hash) => EncodedAddress::P2PKH(hash.as_hash().into_inner()),
|
||||
Payload::ScriptHash(hash) => EncodedAddress::P2SH(hash.as_hash().into_inner()),
|
||||
Payload::WitnessProgram { version: WitnessVersion::V0, program } => {
|
||||
if program.len() == 20 {
|
||||
EncodedAddress::P2WPKH(program.try_into().map_err(|_| ())?)
|
||||
} else if program.len() == 32 {
|
||||
EncodedAddress::P2WSH(program.try_into().map_err(|_| ())?)
|
||||
} else {
|
||||
Err(())?
|
||||
}
|
||||
}
|
||||
Payload::WitnessProgram { version: WitnessVersion::V1, program } => {
|
||||
EncodedAddress::P2TR(program.try_into().map_err(|_| ())?)
|
||||
}
|
||||
_ => Err(())?,
|
||||
})
|
||||
.encode(),
|
||||
)
|
||||
}
|
||||
}
|
||||
5
substrate/serai/client/src/coins/mod.rs
Normal file
5
substrate/serai/client/src/coins/mod.rs
Normal file
@@ -0,0 +1,5 @@
|
||||
#[cfg(feature = "bitcoin")]
|
||||
pub mod bitcoin;
|
||||
|
||||
#[cfg(feature = "monero")]
|
||||
pub mod monero;
|
||||
101
substrate/serai/client/src/coins/monero.rs
Normal file
101
substrate/serai/client/src/coins/monero.rs
Normal file
@@ -0,0 +1,101 @@
|
||||
use core::str::FromStr;
|
||||
|
||||
use scale::{Encode, Decode};
|
||||
|
||||
use ciphersuite::{Ciphersuite, Ed25519};
|
||||
|
||||
use monero_serai::wallet::address::{AddressError, Network, AddressType, AddressMeta, MoneroAddress};
|
||||
|
||||
#[derive(Clone, PartialEq, Eq, Debug)]
|
||||
pub struct Address(MoneroAddress);
|
||||
impl Address {
|
||||
pub fn new(address: MoneroAddress) -> Option<Address> {
|
||||
if address.payment_id().is_some() {
|
||||
return None;
|
||||
}
|
||||
Some(Address(address))
|
||||
}
|
||||
}
|
||||
|
||||
impl FromStr for Address {
|
||||
type Err = AddressError;
|
||||
fn from_str(str: &str) -> Result<Address, AddressError> {
|
||||
MoneroAddress::from_str(Network::Mainnet, str).map(Address)
|
||||
}
|
||||
}
|
||||
|
||||
impl ToString for Address {
|
||||
fn to_string(&self) -> String {
|
||||
self.0.to_string()
|
||||
}
|
||||
}
|
||||
|
||||
// SCALE-encoded variant of Monero addresses.
|
||||
#[derive(Clone, PartialEq, Eq, Debug, Encode, Decode)]
|
||||
enum EncodedAddressType {
|
||||
Standard,
|
||||
Subaddress,
|
||||
Featured(u8),
|
||||
}
|
||||
|
||||
#[derive(Clone, PartialEq, Eq, Debug, Encode, Decode)]
|
||||
struct EncodedAddress {
|
||||
kind: EncodedAddressType,
|
||||
spend: [u8; 32],
|
||||
view: [u8; 32],
|
||||
}
|
||||
|
||||
impl TryFrom<Vec<u8>> for Address {
|
||||
type Error = ();
|
||||
fn try_from(data: Vec<u8>) -> Result<Address, ()> {
|
||||
// Decode as SCALE
|
||||
let addr = EncodedAddress::decode(&mut data.as_ref()).map_err(|_| ())?;
|
||||
// Convert over
|
||||
Ok(Address(MoneroAddress::new(
|
||||
AddressMeta::new(
|
||||
Network::Mainnet,
|
||||
match addr.kind {
|
||||
EncodedAddressType::Standard => AddressType::Standard,
|
||||
EncodedAddressType::Subaddress => AddressType::Subaddress,
|
||||
EncodedAddressType::Featured(flags) => {
|
||||
let subaddress = (flags & 1) != 0;
|
||||
let integrated = (flags & (1 << 1)) != 0;
|
||||
let guaranteed = (flags & (1 << 2)) != 0;
|
||||
if integrated {
|
||||
Err(())?;
|
||||
}
|
||||
AddressType::Featured { subaddress, payment_id: None, guaranteed }
|
||||
}
|
||||
},
|
||||
),
|
||||
Ed25519::read_G(&mut addr.spend.as_ref()).map_err(|_| ())?.0,
|
||||
Ed25519::read_G(&mut addr.view.as_ref()).map_err(|_| ())?.0,
|
||||
)))
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(clippy::from_over_into)]
|
||||
impl Into<MoneroAddress> for Address {
|
||||
fn into(self) -> MoneroAddress {
|
||||
self.0
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(clippy::from_over_into)]
|
||||
impl Into<Vec<u8>> for Address {
|
||||
fn into(self) -> Vec<u8> {
|
||||
EncodedAddress {
|
||||
kind: match self.0.meta.kind {
|
||||
AddressType::Standard => EncodedAddressType::Standard,
|
||||
AddressType::Subaddress => EncodedAddressType::Subaddress,
|
||||
AddressType::Integrated(_) => panic!("integrated address became Serai Monero address"),
|
||||
AddressType::Featured { subaddress, payment_id: _, guaranteed } => {
|
||||
EncodedAddressType::Featured(u8::from(subaddress) + (u8::from(guaranteed) << 2))
|
||||
}
|
||||
},
|
||||
spend: self.0.spend.compress().0,
|
||||
view: self.0.view.compress().0,
|
||||
}
|
||||
.encode()
|
||||
}
|
||||
}
|
||||
@@ -1,126 +1,28 @@
|
||||
use thiserror::Error;
|
||||
#[cfg(feature = "coins")]
|
||||
pub mod coins;
|
||||
|
||||
use scale::{Encode, Decode};
|
||||
mod scale_value;
|
||||
pub(crate) use crate::scale_value::{scale_value, scale_composite};
|
||||
use ::scale_value::Value;
|
||||
#[cfg(feature = "serai")]
|
||||
mod serai;
|
||||
#[cfg(feature = "serai")]
|
||||
pub use serai::*;
|
||||
|
||||
use subxt::{
|
||||
utils::Encoded,
|
||||
tx::{Signer, DynamicTxPayload, BaseExtrinsicParams, BaseExtrinsicParamsBuilder, TxClient},
|
||||
Config as SubxtConfig, OnlineClient,
|
||||
};
|
||||
|
||||
pub use serai_primitives as primitives;
|
||||
use primitives::{Signature, SeraiAddress};
|
||||
|
||||
use serai_runtime::{
|
||||
system::Config, support::traits::PalletInfo as PalletInfoTrait, PalletInfo, Runtime,
|
||||
};
|
||||
|
||||
pub mod tokens;
|
||||
pub mod in_instructions;
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Default, Debug, Encode, Decode)]
|
||||
pub struct Tip {
|
||||
#[codec(compact)]
|
||||
pub tip: u64,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
|
||||
pub struct SeraiConfig;
|
||||
impl SubxtConfig for SeraiConfig {
|
||||
type BlockNumber = <Runtime as Config>::BlockNumber;
|
||||
|
||||
type Hash = <Runtime as Config>::Hash;
|
||||
type Hashing = <Runtime as Config>::Hashing;
|
||||
|
||||
type Index = <Runtime as Config>::Index;
|
||||
type AccountId = <Runtime as Config>::AccountId;
|
||||
// TODO: Bech32m
|
||||
type Address = SeraiAddress;
|
||||
|
||||
type Header = <Runtime as Config>::Header;
|
||||
type Signature = Signature;
|
||||
|
||||
type ExtrinsicParams = BaseExtrinsicParams<SeraiConfig, Tip>;
|
||||
}
|
||||
|
||||
#[derive(Clone, Error, Debug)]
|
||||
pub enum SeraiError {
|
||||
#[error("failed to connect to serai")]
|
||||
RpcError,
|
||||
#[error("serai-client library was intended for a different runtime version")]
|
||||
InvalidRuntime,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct Serai(OnlineClient<SeraiConfig>);
|
||||
|
||||
impl Serai {
|
||||
pub async fn new(url: &str) -> Result<Self, SeraiError> {
|
||||
Ok(Serai(OnlineClient::<SeraiConfig>::from_url(url).await.map_err(|_| SeraiError::RpcError)?))
|
||||
// If we aren't exposing the Serai client (subxt), still expose all primitives
|
||||
#[cfg(not(feature = "serai"))]
|
||||
pub use serai_runtime::primitives;
|
||||
#[cfg(not(feature = "serai"))]
|
||||
mod other_primitives {
|
||||
pub mod in_instructions {
|
||||
pub use serai_runtime::in_instructions::primitives;
|
||||
}
|
||||
|
||||
async fn storage<R: Decode>(
|
||||
&self,
|
||||
pallet: &'static str,
|
||||
name: &'static str,
|
||||
keys: Option<Vec<Value>>,
|
||||
block: [u8; 32],
|
||||
) -> Result<Option<R>, SeraiError> {
|
||||
let storage = self.0.storage();
|
||||
let address = subxt::dynamic::storage(pallet, name, keys.unwrap_or(vec![]));
|
||||
debug_assert!(storage.validate(&address).is_ok(), "invalid storage address");
|
||||
|
||||
storage
|
||||
.fetch(&address, Some(block.into()))
|
||||
.await
|
||||
.map_err(|_| SeraiError::RpcError)?
|
||||
.map(|res| R::decode(&mut res.encoded()).map_err(|_| SeraiError::InvalidRuntime))
|
||||
.transpose()
|
||||
pub mod tokens {
|
||||
pub use serai_runtime::tokens::primitives;
|
||||
}
|
||||
|
||||
async fn events<P: 'static, E: Decode>(
|
||||
&self,
|
||||
block: [u8; 32],
|
||||
filter: impl Fn(&E) -> bool,
|
||||
) -> Result<Vec<E>, SeraiError> {
|
||||
let mut res = vec![];
|
||||
for event in
|
||||
self.0.events().at(Some(block.into())).await.map_err(|_| SeraiError::RpcError)?.iter()
|
||||
{
|
||||
let event = event.map_err(|_| SeraiError::InvalidRuntime)?;
|
||||
if PalletInfo::index::<P>().unwrap() == usize::from(event.pallet_index()) {
|
||||
let mut with_variant: &[u8] =
|
||||
&[[event.variant_index()].as_ref(), event.field_bytes()].concat();
|
||||
let event = E::decode(&mut with_variant).map_err(|_| SeraiError::InvalidRuntime)?;
|
||||
if filter(&event) {
|
||||
res.push(event);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(res)
|
||||
}
|
||||
|
||||
pub async fn get_latest_block_hash(&self) -> Result<[u8; 32], SeraiError> {
|
||||
Ok(self.0.rpc().finalized_head().await.map_err(|_| SeraiError::RpcError)?.into())
|
||||
}
|
||||
|
||||
pub fn sign<S: Send + Sync + Signer<SeraiConfig>>(
|
||||
&self,
|
||||
signer: &S,
|
||||
payload: &DynamicTxPayload<'static>,
|
||||
nonce: u32,
|
||||
params: BaseExtrinsicParamsBuilder<SeraiConfig, Tip>,
|
||||
) -> Result<Encoded, SeraiError> {
|
||||
TxClient::new(self.0.offline())
|
||||
.create_signed_with_nonce(payload, signer, nonce, params)
|
||||
.map(|tx| Encoded(tx.into_encoded()))
|
||||
.map_err(|_| SeraiError::InvalidRuntime)
|
||||
}
|
||||
|
||||
pub async fn publish(&self, tx: &Encoded) -> Result<[u8; 32], SeraiError> {
|
||||
self.0.rpc().submit_extrinsic(tx).await.map(Into::into).map_err(|_| SeraiError::RpcError)
|
||||
pub mod validator_sets {
|
||||
pub use serai_runtime::validator_sets::primitives;
|
||||
}
|
||||
}
|
||||
#[cfg(not(feature = "serai"))]
|
||||
pub use other_primitives::*;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
155
substrate/serai/client/src/serai/mod.rs
Normal file
155
substrate/serai/client/src/serai/mod.rs
Normal file
@@ -0,0 +1,155 @@
|
||||
use thiserror::Error;
|
||||
|
||||
use scale::{Encode, Decode};
|
||||
mod scale_value;
|
||||
pub(crate) use scale_value::{scale_value, scale_composite};
|
||||
use subxt::ext::scale_value::Value;
|
||||
|
||||
use sp_core::{Pair as PairTrait, sr25519::Pair};
|
||||
use subxt::{
|
||||
utils::Encoded,
|
||||
config::{
|
||||
substrate::{BlakeTwo256, SubstrateHeader},
|
||||
extrinsic_params::{BaseExtrinsicParams, BaseExtrinsicParamsBuilder},
|
||||
},
|
||||
tx::{Signer, DynamicTxPayload, TxClient},
|
||||
Config as SubxtConfig, OnlineClient,
|
||||
};
|
||||
|
||||
pub use serai_runtime::primitives;
|
||||
use primitives::{Signature, SeraiAddress};
|
||||
|
||||
use serai_runtime::{
|
||||
system::Config, support::traits::PalletInfo as PalletInfoTrait, PalletInfo, Runtime,
|
||||
};
|
||||
|
||||
pub mod tokens;
|
||||
pub mod in_instructions;
|
||||
pub mod validator_sets {
|
||||
pub use serai_runtime::validator_sets::primitives;
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Default, Debug, Encode, Decode)]
|
||||
pub struct Tip {
|
||||
#[codec(compact)]
|
||||
pub tip: u64,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
|
||||
pub struct SeraiConfig;
|
||||
impl SubxtConfig for SeraiConfig {
|
||||
type Hash = <Runtime as Config>::Hash;
|
||||
type Hasher = BlakeTwo256;
|
||||
|
||||
type Index = <Runtime as Config>::Index;
|
||||
type AccountId = <Runtime as Config>::AccountId;
|
||||
// TODO: Bech32m
|
||||
type Address = SeraiAddress;
|
||||
|
||||
type Header = SubstrateHeader<<Runtime as Config>::BlockNumber, BlakeTwo256>;
|
||||
type Signature = Signature;
|
||||
|
||||
type ExtrinsicParams = BaseExtrinsicParams<SeraiConfig, Tip>;
|
||||
}
|
||||
|
||||
#[derive(Clone, Error, Debug)]
|
||||
pub enum SeraiError {
|
||||
#[error("failed to connect to serai")]
|
||||
RpcError,
|
||||
#[error("serai-client library was intended for a different runtime version")]
|
||||
InvalidRuntime,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct Serai(OnlineClient<SeraiConfig>);
|
||||
|
||||
impl Serai {
|
||||
pub async fn new(url: &str) -> Result<Self, SeraiError> {
|
||||
Ok(Serai(OnlineClient::<SeraiConfig>::from_url(url).await.map_err(|_| SeraiError::RpcError)?))
|
||||
}
|
||||
|
||||
async fn storage<R: Decode>(
|
||||
&self,
|
||||
pallet: &'static str,
|
||||
name: &'static str,
|
||||
keys: Option<Vec<Value>>,
|
||||
block: [u8; 32],
|
||||
) -> Result<Option<R>, SeraiError> {
|
||||
let storage = self.0.storage();
|
||||
let address = subxt::dynamic::storage(pallet, name, keys.unwrap_or(vec![]));
|
||||
debug_assert!(storage.validate(&address).is_ok(), "invalid storage address");
|
||||
|
||||
storage
|
||||
.at(Some(block.into()))
|
||||
.await
|
||||
.map_err(|_| SeraiError::RpcError)?
|
||||
.fetch(&address)
|
||||
.await
|
||||
.map_err(|_| SeraiError::RpcError)?
|
||||
.map(|res| R::decode(&mut res.encoded()).map_err(|_| SeraiError::InvalidRuntime))
|
||||
.transpose()
|
||||
}
|
||||
|
||||
async fn events<P: 'static, E: Decode>(
|
||||
&self,
|
||||
block: [u8; 32],
|
||||
filter: impl Fn(&E) -> bool,
|
||||
) -> Result<Vec<E>, SeraiError> {
|
||||
let mut res = vec![];
|
||||
for event in
|
||||
self.0.events().at(Some(block.into())).await.map_err(|_| SeraiError::RpcError)?.iter()
|
||||
{
|
||||
let event = event.map_err(|_| SeraiError::InvalidRuntime)?;
|
||||
if PalletInfo::index::<P>().unwrap() == usize::from(event.pallet_index()) {
|
||||
let mut with_variant: &[u8] =
|
||||
&[[event.variant_index()].as_ref(), event.field_bytes()].concat();
|
||||
let event = E::decode(&mut with_variant).map_err(|_| SeraiError::InvalidRuntime)?;
|
||||
if filter(&event) {
|
||||
res.push(event);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(res)
|
||||
}
|
||||
|
||||
pub async fn get_latest_block_hash(&self) -> Result<[u8; 32], SeraiError> {
|
||||
Ok(self.0.rpc().finalized_head().await.map_err(|_| SeraiError::RpcError)?.into())
|
||||
}
|
||||
|
||||
pub fn sign<S: Send + Sync + Signer<SeraiConfig>>(
|
||||
&self,
|
||||
signer: &S,
|
||||
payload: &DynamicTxPayload<'static>,
|
||||
nonce: u32,
|
||||
params: BaseExtrinsicParamsBuilder<SeraiConfig, Tip>,
|
||||
) -> Result<Encoded, SeraiError> {
|
||||
TxClient::new(self.0.offline())
|
||||
.create_signed_with_nonce(payload, signer, nonce, params)
|
||||
.map(|tx| Encoded(tx.into_encoded()))
|
||||
.map_err(|_| SeraiError::InvalidRuntime)
|
||||
}
|
||||
|
||||
pub async fn publish(&self, tx: &Encoded) -> Result<[u8; 32], SeraiError> {
|
||||
self.0.rpc().submit_extrinsic(tx).await.map(Into::into).map_err(|_| SeraiError::RpcError)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct PairSigner(Pair, <SeraiConfig as SubxtConfig>::AccountId);
|
||||
impl PairSigner {
|
||||
pub fn new(pair: Pair) -> Self {
|
||||
let id = pair.public();
|
||||
PairSigner(pair, id)
|
||||
}
|
||||
}
|
||||
impl Signer<SeraiConfig> for PairSigner {
|
||||
fn account_id(&self) -> &<SeraiConfig as SubxtConfig>::AccountId {
|
||||
&self.1
|
||||
}
|
||||
fn address(&self) -> <SeraiConfig as SubxtConfig>::Address {
|
||||
self.1.into()
|
||||
}
|
||||
fn sign(&self, payload: &[u8]) -> <SeraiConfig as SubxtConfig>::Signature {
|
||||
self.0.sign(payload)
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
use ::scale::Encode;
|
||||
use scale_info::{MetaType, TypeInfo, Registry, PortableRegistry};
|
||||
use scale_value::{Composite, ValueDef, Value, scale};
|
||||
use subxt::ext::scale_value::{Composite, ValueDef, Value, scale};
|
||||
|
||||
pub(crate) fn scale_value<V: Encode + TypeInfo + 'static>(value: V) -> Value {
|
||||
let mut registry = Registry::new();
|
||||
1
substrate/serai/client/src/tests/coins/bitcoin.rs
Normal file
1
substrate/serai/client/src/tests/coins/bitcoin.rs
Normal file
@@ -0,0 +1 @@
|
||||
// TODO: Test the address back and forth
|
||||
5
substrate/serai/client/src/tests/coins/mod.rs
Normal file
5
substrate/serai/client/src/tests/coins/mod.rs
Normal file
@@ -0,0 +1,5 @@
|
||||
#[cfg(feature = "bitcoin")]
|
||||
mod bitcoin;
|
||||
|
||||
#[cfg(feature = "monero")]
|
||||
mod monero;
|
||||
1
substrate/serai/client/src/tests/coins/monero.rs
Normal file
1
substrate/serai/client/src/tests/coins/monero.rs
Normal file
@@ -0,0 +1 @@
|
||||
// TODO: Test the address back and forth
|
||||
2
substrate/serai/client/src/tests/mod.rs
Normal file
2
substrate/serai/client/src/tests/mod.rs
Normal file
@@ -0,0 +1,2 @@
|
||||
#[cfg(feature = "coins")]
|
||||
mod coins;
|
||||
@@ -2,21 +2,19 @@ use core::time::Duration;
|
||||
|
||||
use rand_core::{RngCore, OsRng};
|
||||
|
||||
use sp_core::Pair;
|
||||
use serai_runtime::in_instructions::{Batch, Update};
|
||||
|
||||
use tokio::time::sleep;
|
||||
|
||||
use subxt::tx::{BaseExtrinsicParamsBuilder, PairSigner};
|
||||
use sp_core::Pair;
|
||||
use subxt::{config::extrinsic_params::BaseExtrinsicParamsBuilder};
|
||||
|
||||
use serai_client::{
|
||||
primitives::{
|
||||
BITCOIN, BlockNumber, BlockHash, SeraiAddress, Amount, WithAmount, Balance, Data,
|
||||
ExternalAddress, insecure_pair_from_name,
|
||||
},
|
||||
in_instructions::primitives::InInstruction,
|
||||
in_instructions::primitives::{InInstruction, Batch, Update},
|
||||
tokens::{primitives::OutInstruction, TokensEvent},
|
||||
Serai,
|
||||
PairSigner, Serai,
|
||||
};
|
||||
|
||||
mod runner;
|
||||
@@ -27,7 +25,7 @@ serai_test!(
|
||||
let coin = BITCOIN;
|
||||
let mut id = BlockHash([0; 32]);
|
||||
OsRng.fill_bytes(&mut id.0);
|
||||
let block_number = BlockNumber(u32::try_from(OsRng.next_u64() >> 32).unwrap());
|
||||
let block_number = BlockNumber(OsRng.next_u64());
|
||||
|
||||
let pair = insecure_pair_from_name("Alice");
|
||||
let public = pair.public();
|
||||
|
||||
@@ -5,8 +5,11 @@ use lazy_static::lazy_static;
|
||||
|
||||
use tokio::{sync::Mutex, time::sleep};
|
||||
|
||||
use serai_runtime::in_instructions::Update;
|
||||
use serai_client::{primitives::Coin, in_instructions::InInstructionsEvent, Serai};
|
||||
use serai_client::{
|
||||
primitives::Coin,
|
||||
in_instructions::{primitives::Updates, InInstructionsEvent},
|
||||
Serai,
|
||||
};
|
||||
|
||||
use jsonrpsee_server::RpcModule;
|
||||
|
||||
@@ -17,7 +20,7 @@ lazy_static! {
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
pub async fn provide_updates(updates: Vec<Option<Update>>) -> [u8; 32] {
|
||||
pub async fn provide_updates(updates: Updates) -> [u8; 32] {
|
||||
let done = Arc::new(Mutex::new(false));
|
||||
let done_clone = done.clone();
|
||||
let updates_clone = updates.clone();
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
use rand_core::{RngCore, OsRng};
|
||||
|
||||
use serai_runtime::in_instructions::{Batch, Update};
|
||||
|
||||
use serai_client::{
|
||||
primitives::{BITCOIN, BlockNumber, BlockHash, SeraiAddress, Amount, WithAmount, Balance},
|
||||
tokens::TokensEvent,
|
||||
in_instructions::{primitives::InInstruction, InInstructionsEvent},
|
||||
in_instructions::{
|
||||
primitives::{InInstruction, Batch, Update},
|
||||
InInstructionsEvent,
|
||||
},
|
||||
Serai,
|
||||
};
|
||||
|
||||
@@ -17,7 +18,7 @@ serai_test!(
|
||||
let coin = BITCOIN;
|
||||
let mut id = BlockHash([0; 32]);
|
||||
OsRng.fill_bytes(&mut id.0);
|
||||
let block_number = BlockNumber(u32::try_from(OsRng.next_u64() >> 32).unwrap());
|
||||
let block_number = BlockNumber(OsRng.next_u64());
|
||||
|
||||
let mut address = SeraiAddress::new([0; 32]);
|
||||
OsRng.fill_bytes(&mut address.0);
|
||||
|
||||
@@ -12,6 +12,8 @@ all-features = true
|
||||
rustdoc-args = ["--cfg", "docsrs"]
|
||||
|
||||
[dependencies]
|
||||
zeroize = { version = "^1.5", features = ["derive"], optional = true }
|
||||
|
||||
scale = { package = "parity-scale-codec", version = "3", default-features = false, features = ["derive"] }
|
||||
scale-info = { version = "2", default-features = false, features = ["derive"] }
|
||||
|
||||
@@ -21,5 +23,5 @@ sp-core = { git = "https://github.com/serai-dex/substrate", default-features = f
|
||||
sp-runtime = { git = "https://github.com/serai-dex/substrate", default-features = false }
|
||||
|
||||
[features]
|
||||
std = ["scale/std", "scale-info/std", "serde", "sp-core/std", "sp-runtime/std"]
|
||||
std = ["zeroize", "scale/std", "scale-info/std", "serde", "sp-core/std", "sp-runtime/std"]
|
||||
default = ["std"]
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
#[cfg(feature = "std")]
|
||||
use zeroize::Zeroize;
|
||||
|
||||
use scale::{Encode, Decode, MaxEncodedLen};
|
||||
use scale_info::TypeInfo;
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
use serde::{Serialize, Deserialize};
|
||||
|
||||
@@ -14,7 +18,7 @@ pub type PublicKey = Public;
|
||||
#[derive(
|
||||
Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug, Encode, Decode, MaxEncodedLen, TypeInfo,
|
||||
)]
|
||||
#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
|
||||
#[cfg_attr(feature = "std", derive(Zeroize, Serialize, Deserialize))]
|
||||
pub struct SeraiAddress(pub [u8; 32]);
|
||||
impl SeraiAddress {
|
||||
pub fn new(key: [u8; 32]) -> SeraiAddress {
|
||||
|
||||
@@ -3,6 +3,9 @@ use core::{
|
||||
fmt::Debug,
|
||||
};
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
use zeroize::Zeroize;
|
||||
|
||||
use scale::{Encode, Decode, MaxEncodedLen};
|
||||
use scale_info::TypeInfo;
|
||||
#[cfg(feature = "std")]
|
||||
@@ -18,7 +21,7 @@ pub type SubstrateAmount = u64;
|
||||
#[derive(
|
||||
Clone, Copy, PartialEq, Eq, PartialOrd, Debug, Encode, Decode, MaxEncodedLen, TypeInfo,
|
||||
)]
|
||||
#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
|
||||
#[cfg_attr(feature = "std", derive(Zeroize, Serialize, Deserialize))]
|
||||
pub struct Amount(pub SubstrateAmount);
|
||||
|
||||
impl Add for Amount {
|
||||
@@ -44,7 +47,7 @@ impl Mul for Amount {
|
||||
}
|
||||
|
||||
#[derive(Clone, PartialEq, Eq, Debug, Encode, Decode, MaxEncodedLen, TypeInfo)]
|
||||
#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
|
||||
#[cfg_attr(feature = "std", derive(Zeroize, Serialize, Deserialize))]
|
||||
pub struct WithAmount<
|
||||
T: Clone + PartialEq + Eq + Debug + Encode + Decode + MaxEncodedLen + TypeInfo,
|
||||
> {
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
use core::ops::{Add, Sub, Mul};
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
use zeroize::Zeroize;
|
||||
|
||||
use scale::{Encode, Decode, MaxEncodedLen};
|
||||
use scale_info::TypeInfo;
|
||||
#[cfg(feature = "std")]
|
||||
@@ -9,7 +12,7 @@ use crate::{Coin, Amount};
|
||||
|
||||
/// The type used for balances (a Coin and Balance).
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Debug, Encode, Decode, MaxEncodedLen, TypeInfo)]
|
||||
#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
|
||||
#[cfg_attr(feature = "std", derive(Zeroize, Serialize, Deserialize))]
|
||||
pub struct Balance {
|
||||
pub coin: Coin,
|
||||
pub amount: Amount,
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
#[cfg(feature = "std")]
|
||||
use zeroize::Zeroize;
|
||||
|
||||
use scale::{Encode, Decode, MaxEncodedLen};
|
||||
use scale_info::TypeInfo;
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
use serde::{Serialize, Deserialize};
|
||||
|
||||
@@ -10,10 +14,10 @@ use sp_core::H256;
|
||||
#[derive(
|
||||
Clone, Copy, Default, PartialEq, Eq, Hash, Debug, Encode, Decode, MaxEncodedLen, TypeInfo,
|
||||
)]
|
||||
#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
|
||||
pub struct BlockNumber(pub u32);
|
||||
impl From<u32> for BlockNumber {
|
||||
fn from(number: u32) -> BlockNumber {
|
||||
#[cfg_attr(feature = "std", derive(Zeroize, Serialize, Deserialize))]
|
||||
pub struct BlockNumber(pub u64);
|
||||
impl From<u64> for BlockNumber {
|
||||
fn from(number: u64) -> BlockNumber {
|
||||
BlockNumber(number)
|
||||
}
|
||||
}
|
||||
@@ -24,7 +28,7 @@ impl From<u32> for BlockNumber {
|
||||
// This would require the processor to maintain a mapping of 32-byte IDs to actual hashes, which
|
||||
// would be fine
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, Encode, Decode, MaxEncodedLen, TypeInfo)]
|
||||
#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
|
||||
#[cfg_attr(feature = "std", derive(Zeroize, Serialize, Deserialize))]
|
||||
pub struct BlockHash(pub [u8; 32]);
|
||||
|
||||
impl AsRef<[u8]> for BlockHash {
|
||||
|
||||
@@ -1,11 +1,15 @@
|
||||
#[cfg(feature = "std")]
|
||||
use zeroize::Zeroize;
|
||||
|
||||
use scale::{Encode, Decode, MaxEncodedLen};
|
||||
use scale_info::TypeInfo;
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
use serde::{Serialize, Deserialize};
|
||||
|
||||
/// The type used to identify coins.
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Debug, Encode, Decode, MaxEncodedLen, TypeInfo)]
|
||||
#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
|
||||
#[cfg_attr(feature = "std", derive(Zeroize, Serialize, Deserialize))]
|
||||
pub struct Coin(pub u32);
|
||||
impl From<u32> for Coin {
|
||||
fn from(coin: u32) -> Coin {
|
||||
|
||||
@@ -2,6 +2,9 @@
|
||||
#![cfg_attr(docsrs, feature(doc_auto_cfg))]
|
||||
#![cfg_attr(not(feature = "std"), no_std)]
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
use zeroize::Zeroize;
|
||||
|
||||
use scale::{Encode, Decode, MaxEncodedLen};
|
||||
use scale_info::TypeInfo;
|
||||
#[cfg(feature = "std")]
|
||||
@@ -31,6 +34,14 @@ pub const MAX_ADDRESS_LEN: u32 = 74;
|
||||
#[derive(Clone, PartialEq, Eq, Debug, Encode, Decode, MaxEncodedLen, TypeInfo)]
|
||||
#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
|
||||
pub struct ExternalAddress(BoundedVec<u8, ConstU32<{ MAX_ADDRESS_LEN }>>);
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
impl Zeroize for ExternalAddress {
|
||||
fn zeroize(&mut self) {
|
||||
self.0.as_mut().zeroize()
|
||||
}
|
||||
}
|
||||
|
||||
impl ExternalAddress {
|
||||
#[cfg(feature = "std")]
|
||||
pub fn new(address: Vec<u8>) -> Result<ExternalAddress, &'static str> {
|
||||
@@ -58,6 +69,14 @@ pub const MAX_DATA_LEN: u32 = 512;
|
||||
#[derive(Clone, PartialEq, Eq, Debug, Encode, Decode, MaxEncodedLen, TypeInfo)]
|
||||
#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
|
||||
pub struct Data(BoundedVec<u8, ConstU32<{ MAX_DATA_LEN }>>);
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
impl Zeroize for Data {
|
||||
fn zeroize(&mut self) {
|
||||
self.0.as_mut().zeroize()
|
||||
}
|
||||
}
|
||||
|
||||
impl Data {
|
||||
#[cfg(feature = "std")]
|
||||
pub fn new(data: Vec<u8>) -> Result<Data, &'static str> {
|
||||
|
||||
@@ -11,6 +11,8 @@ all-features = true
|
||||
rustdoc-args = ["--cfg", "docsrs"]
|
||||
|
||||
[dependencies]
|
||||
zeroize = { version = "^1.5", features = ["derive"], optional = true }
|
||||
|
||||
scale = { package = "parity-scale-codec", version = "3", default-features = false, features = ["derive"] }
|
||||
scale-info = { version = "2", default-features = false, features = ["derive"] }
|
||||
|
||||
@@ -22,5 +24,5 @@ serai-primitives = { path = "../../serai/primitives", default-features = false }
|
||||
sp-runtime = { git = "https://github.com/serai-dex/substrate", default-features = false }
|
||||
|
||||
[features]
|
||||
std = ["scale/std", "scale-info/std", "serde", "sp-runtime/std", "serai-primitives/std"]
|
||||
std = ["zeroize", "scale/std", "scale-info/std", "serde", "sp-runtime/std", "serai-primitives/std"]
|
||||
default = ["std"]
|
||||
|
||||
@@ -2,6 +2,9 @@
|
||||
#![cfg_attr(docsrs, feature(doc_auto_cfg))]
|
||||
#![cfg_attr(not(feature = "std"), no_std)]
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
use zeroize::Zeroize;
|
||||
|
||||
use scale::{Encode, Decode, MaxEncodedLen};
|
||||
use scale_info::TypeInfo;
|
||||
|
||||
@@ -13,14 +16,14 @@ use serai_primitives::{SeraiAddress, ExternalAddress, Data, pallet_address};
|
||||
pub const ADDRESS: SeraiAddress = pallet_address(b"Tokens");
|
||||
|
||||
#[derive(Clone, PartialEq, Eq, Debug, Encode, Decode, MaxEncodedLen, TypeInfo)]
|
||||
#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
|
||||
#[cfg_attr(feature = "std", derive(Zeroize, Serialize, Deserialize))]
|
||||
pub struct OutInstruction {
|
||||
pub address: ExternalAddress,
|
||||
pub data: Option<Data>,
|
||||
}
|
||||
|
||||
#[derive(Clone, PartialEq, Eq, Debug, Encode, Decode, MaxEncodedLen, TypeInfo)]
|
||||
#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
|
||||
#[cfg_attr(feature = "std", derive(Zeroize, Serialize, Deserialize))]
|
||||
pub enum Destination {
|
||||
Native(SeraiAddress),
|
||||
External(OutInstruction),
|
||||
|
||||
@@ -9,7 +9,8 @@ pub mod pallet {
|
||||
use frame_support::pallet_prelude::*;
|
||||
|
||||
use serai_primitives::*;
|
||||
use validator_sets_primitives::*;
|
||||
pub use validator_sets_primitives as primitives;
|
||||
use primitives::*;
|
||||
|
||||
#[pallet::config]
|
||||
pub trait Config: frame_system::Config + TypeInfo {
|
||||
@@ -101,7 +102,7 @@ pub mod pallet {
|
||||
}
|
||||
|
||||
ValidatorSets::<T>::set(
|
||||
ValidatorSetInstance(Session(0), ValidatorSetIndex(0)),
|
||||
ValidatorSetInstance { session: Session(0), index: ValidatorSetIndex(0) },
|
||||
Some(ValidatorSet {
|
||||
bond: self.bond,
|
||||
coins: BoundedVec::try_from(self.coins.clone()).unwrap(),
|
||||
@@ -160,7 +161,7 @@ pub mod pallet {
|
||||
let session: Session = Session(0);
|
||||
|
||||
// Confirm a key hasn't been set for this set instance
|
||||
let instance = ValidatorSetInstance(session, index);
|
||||
let instance = ValidatorSetInstance { session, index };
|
||||
if Keys::<T>::get((instance, coin)).is_some() {
|
||||
Err(Error::<T>::AlreadyGeneratedKeys)?;
|
||||
}
|
||||
|
||||
@@ -12,11 +12,13 @@ all-features = true
|
||||
rustdoc-args = ["--cfg", "docsrs"]
|
||||
|
||||
[dependencies]
|
||||
scale = { package = "parity-scale-codec", version = "3", default-features = false, features = ["derive"] }
|
||||
zeroize = { version = "^1.5", features = ["derive"], optional = true }
|
||||
|
||||
scale = { package = "parity-scale-codec", version = "3", default-features = false, features = ["derive", "max-encoded-len"] }
|
||||
scale-info = { version = "2", default-features = false, features = ["derive"] }
|
||||
|
||||
serde = { version = "1", features = ["derive"], optional = true }
|
||||
|
||||
[features]
|
||||
std = ["scale/std", "scale-info/std", "serde"]
|
||||
std = ["zeroize", "scale/std", "scale-info/std", "serde"]
|
||||
default = ["std"]
|
||||
|
||||
@@ -1,21 +1,28 @@
|
||||
#![cfg_attr(not(feature = "std"), no_std)]
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
use zeroize::Zeroize;
|
||||
|
||||
use scale::{Encode, Decode, MaxEncodedLen};
|
||||
use scale_info::TypeInfo;
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
use serde::{Serialize, Deserialize};
|
||||
|
||||
/// The type used to identify a specific session of validators.
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Debug, Encode, Decode, TypeInfo, MaxEncodedLen)]
|
||||
#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, Encode, Decode, TypeInfo, MaxEncodedLen)]
|
||||
#[cfg_attr(feature = "std", derive(Zeroize, Serialize, Deserialize))]
|
||||
pub struct Session(pub u32);
|
||||
|
||||
/// The type used to identify a validator set.
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Debug, Encode, Decode, TypeInfo, MaxEncodedLen)]
|
||||
#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, Encode, Decode, TypeInfo, MaxEncodedLen)]
|
||||
#[cfg_attr(feature = "std", derive(Zeroize, Serialize, Deserialize))]
|
||||
pub struct ValidatorSetIndex(pub u16);
|
||||
|
||||
/// The type used to identify a specific validator set during a specific session.
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Debug, Encode, Decode, TypeInfo, MaxEncodedLen)]
|
||||
#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
|
||||
pub struct ValidatorSetInstance(pub Session, pub ValidatorSetIndex);
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, Encode, Decode, TypeInfo, MaxEncodedLen)]
|
||||
#[cfg_attr(feature = "std", derive(Zeroize, Serialize, Deserialize))]
|
||||
pub struct ValidatorSetInstance {
|
||||
pub session: Session,
|
||||
pub index: ValidatorSetIndex,
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user