From 220f7ed6d58d1514719a1e6472ece6190d052bf5 Mon Sep 17 00:00:00 2001 From: David Craven Date: Tue, 17 Sep 2024 11:53:46 +0200 Subject: [PATCH] Redesign primitives. --- Cargo.lock | 2 - primitives/Cargo.toml | 3 - primitives/src/gmp.rs | 414 +++++++++++++++++++++++----------------- primitives/src/lib.rs | 24 +-- primitives/src/shard.rs | 27 ++- primitives/src/task.rs | 197 ++----------------- 6 files changed, 290 insertions(+), 377 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 707719f307..958cfee676 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -19235,8 +19235,6 @@ dependencies = [ name = "time-primitives" version = "0.1.0" dependencies = [ - "alloy-primitives 0.8.0", - "alloy-sol-types 0.8.0", "anyhow", "async-trait", "futures", diff --git a/primitives/Cargo.toml b/primitives/Cargo.toml index a52024753f..8821dc5447 100644 --- a/primitives/Cargo.toml +++ b/primitives/Cargo.toml @@ -18,9 +18,6 @@ serde = { workspace = true, features = [ "alloc" ] } scale-codec.workspace = true scale-decode.workspace = true scale-info.workspace = true - -alloy-primitives = { version = "0.8", default-features = false } -alloy-sol-types = { version = "0.8", default-features = false } sha3 = { version = "0.10", default-features = false } polkadot-sdk = { workspace = true, features = [ diff --git a/primitives/src/gmp.rs b/primitives/src/gmp.rs index eed8e6a480..24821c15c4 100644 --- a/primitives/src/gmp.rs +++ b/primitives/src/gmp.rs @@ -1,209 +1,283 @@ -use crate::{Function, Msg, NetworkId, TssPublicKey, TssSignature}; +use crate::{NetworkId, ShardId, TaskId, TssPublicKey}; +use scale_codec::{Decode, Encode}; +use scale_decode::DecodeAsType; +use scale_info::{prelude::vec::Vec, TypeInfo}; +#[cfg(feature = "std")] +use serde::{Deserialize, Serialize}; -use alloy_primitives::private::Vec; -use alloy_primitives::{Address, U256}; -use alloy_sol_types::{sol, Eip712Domain, SolCall, SolStruct}; +pub type Address = [u8; 32]; +pub type Gateway = Address; +pub type MessageId = [u8; 32]; +pub type Hash = [u8; 32]; -const EIP712_NAME: &str = "Analog Gateway Contract"; -const EIP712_VERSION: &str = "0.1.0"; - -pub type Eip712Bytes = [u8; 66]; -pub type Eip712Hash = [u8; 32]; +const GMP_VERSION: &str = "Analog GMP v2"; +#[derive(Debug, Clone, Decode, Encode, TypeInfo, PartialEq)] pub struct GmpParams { - pub network_id: NetworkId, - pub gateway_contract: Address, - pub tss_public_key: TssPublicKey, + pub network: NetworkId, + pub gateway: Gateway, + pub signer: TssPublicKey, } impl GmpParams { - pub fn eip712_domain_separator(&self) -> Eip712Domain { - Eip712Domain { - name: Some(EIP712_NAME.into()), - version: Some(EIP712_VERSION.into()), - chain_id: Some(U256::from(self.network_id)), - verifying_contract: Some(self.gateway_contract), - salt: None, - } - } - - fn to_eip712_bytes(&self, hash: Eip712Hash) -> Eip712Bytes { - let mut digest_input = [0u8; 2 + 32 + 32]; - digest_input[0] = 0x19; - digest_input[1] = 0x01; - digest_input[2..34].copy_from_slice(&self.eip712_domain_separator().hash_struct()[..]); - digest_input[34..66].copy_from_slice(&hash[..]); - digest_input + pub fn hash(&self, payload: &[u8]) -> Hash { + use sha3::Digest; + let mut hasher = sha3::Keccak256::new(); + hasher.update(GMP_VERSION); + hasher.update(&self.network.to_be_bytes()); + hasher.update(&self.gateway); + hasher.update(&self.signer); + hasher.update(payload); + hasher.finalize().into() } } -sol! { - #[derive(Debug, Default, PartialEq, Eq)] - struct TssKey { - uint8 yParity; - uint256 xCoord; - } +#[cfg_attr(feature = "std", derive(Serialize, Deserialize))] +#[derive(Debug, Clone, Default, Decode, DecodeAsType, Encode, TypeInfo, PartialEq)] +pub struct GmpMessage { + pub src_network: NetworkId, + pub dest_network: NetworkId, + pub src: Address, + pub dest: Address, + pub nonce: u64, + pub gas_limit: u128, + pub bytes: Vec, +} - #[derive(Debug, PartialEq, Eq)] - struct UpdateKeysMessage { - TssKey[] revoke; - TssKey[] register; - } +impl GmpMessage { + const HEADER_LEN: usize = 86; - #[derive(Debug, PartialEq, Eq)] - struct GmpMessage { - bytes32 source; - uint16 srcNetwork; - address dest; - uint16 destNetwork; - uint256 gasLimit; - uint256 salt; - bytes data; + pub fn encoded_len(&self) -> usize { + Self::HEADER_LEN + self.bytes.len() } - #[derive(Debug, PartialEq, Eq)] - struct Signature { - uint256 xCoord; - uint256 e; - uint256 s; + fn encode_header(&self) -> [u8; 86] { + let mut hdr = [0; Self::HEADER_LEN]; + hdr[..2].copy_from_slice(&self.src_network.to_be_bytes()); + hdr[2..4].copy_from_slice(&self.dest_network.to_be_bytes()); + hdr[4..36].copy_from_slice(&self.src); + hdr[36..68].copy_from_slice(&self.dest); + hdr[68..76].copy_from_slice(&self.nonce.to_be_bytes()); + hdr[76..82].copy_from_slice(&self.gas_limit.to_be_bytes()); + hdr[82..86].copy_from_slice(&(self.bytes.len() as u32).to_be_bytes()); + hdr } - interface IGateway { - event GmpExecuted( - bytes32 indexed id, - bytes32 indexed source, - address indexed dest, - uint256 status, - bytes32 result - ); - - event KeySetChanged( - bytes32 indexed id, - TssKey[] revoked, - TssKey[] registered - ); - - event GmpCreated( - bytes32 indexed id, - bytes32 indexed sender, - address indexed recipient, - uint16 network, - uint256 gasLimit, - uint256 salt, - bytes data - ); - - constructor(uint16 networkId, address proxy) payable; - function execute(Signature memory signature, GmpMessage memory message) external returns (uint8 status, bytes32 result); - function updateKeys(Signature memory signature, UpdateKeysMessage memory message) external; - function deposit() public payable; + pub fn encode_to(&self, buf: &mut Vec) { + buf.extend_from_slice(&self.encode_header()); + buf.extend_from_slice(&self.bytes); } -} -impl From for TssKey { - fn from(bytes: TssPublicKey) -> Self { - Self { - yParity: if bytes[0] % 2 == 0 { 0 } else { 1 }, - xCoord: U256::from_be_slice(&bytes[1..]), - } + pub fn message_id(&self) -> MessageId { + use sha3::Digest; + let mut hasher = sha3::Keccak256::new(); + hasher.update(&self.encode_header()); + hasher.update(&self.bytes); + hasher.finalize().into() } } -#[derive(Debug, Clone, PartialEq, Eq)] -pub enum Message { - UpdateKeys(UpdateKeysMessage), - Gmp(GmpMessage), +#[cfg_attr(feature = "std", derive(Serialize, Deserialize))] +#[derive(Debug, Clone, Decode, Encode, TypeInfo, PartialEq)] +pub enum GatewayOp { + SendMessage(GmpMessage), + RegisterShard( + ShardId, + #[cfg_attr(feature = "std", serde(with = "crate::shard::serde_tss_public_key"))] + TssPublicKey, + ), + UnregisterShard( + ShardId, + #[cfg_attr(feature = "std", serde(with = "crate::shard::serde_tss_public_key"))] + TssPublicKey, + ), } -impl Message { - pub fn update_keys( - revoke: impl IntoIterator, - register: impl IntoIterator, - ) -> Message { - Self::UpdateKeys(UpdateKeysMessage { - revoke: revoke.into_iter().map(TssKey::from).collect(), - register: register.into_iter().map(TssKey::from).collect(), - }) - } - - pub fn gmp(msg: Msg) -> Message { - Self::Gmp(GmpMessage { - source: msg.source.into(), - srcNetwork: msg.source_network, - dest: Address(msg.dest.into()), - destNetwork: msg.dest_network, - gasLimit: U256::from(msg.gas_limit), - salt: U256::from_be_bytes(msg.salt), - data: msg.data.into(), - }) +impl GatewayOp { + pub fn encoded_len(&self) -> usize { + 1 + match self { + Self::SendMessage(msg) => msg.encoded_len(), + _ => 8 + 33, + } } - fn payload(self, signature: Signature) -> Vec { + pub fn encode_to(&self, buf: &mut Vec) { match self { - Self::UpdateKeys(message) => { - IGateway::updateKeysCall { message, signature }.abi_encode() + Self::SendMessage(msg) => { + buf.push(0); + msg.encode_to(buf); + }, + Self::RegisterShard(shard, pubkey) => { + buf.push(1); + buf.extend_from_slice(&shard.to_be_bytes()); + buf.extend_from_slice(pubkey); + }, + Self::UnregisterShard(shard, pubkey) => { + buf.push(2); + buf.extend_from_slice(&shard.to_be_bytes()); + buf.extend_from_slice(pubkey); }, - Self::Gmp(message) => IGateway::executeCall { message, signature }.abi_encode(), } } +} - fn eip712_hash_struct(&self) -> [u8; 32] { - match self { - Self::UpdateKeys(msg) => msg.eip712_hash_struct().into(), - Self::Gmp(msg) => msg.eip712_hash_struct().into(), - } - } +#[cfg_attr(feature = "std", derive(Serialize, Deserialize))] +#[derive(Debug, Clone, Decode, Encode, TypeInfo, PartialEq)] +pub struct GatewayMessage { + pub task_id: TaskId, + pub ops: Vec, +} - pub fn to_eip712_bytes(&self, params: &GmpParams) -> Eip712Bytes { - let hash = self.eip712_hash_struct(); - params.to_eip712_bytes(hash) +impl GatewayMessage { + pub fn new(task_id: TaskId, ops: Vec) -> Self { + Self { task_id, ops } } - /// Converts `Message` into `Function::EvmCall` - pub fn into_evm_call(self, params: &GmpParams, signature: TssSignature) -> Function { - let signature = Signature { - xCoord: TssKey::from(params.tss_public_key).xCoord, - e: U256::from_be_slice(&signature[0..32]), - s: U256::from_be_slice(&signature[32..64]), - }; - let gas_limit = if let Self::Gmp(GmpMessage { gasLimit, .. }) = &self { - let gas_limit = u64::try_from(*gasLimit).unwrap_or(u64::MAX).saturating_add(100_000); - Some(gas_limit.min(29_900_000)) - } else { - None - }; - let payload = self.payload(signature); - Function::EvmCall { - address: params.gateway_contract.into(), - input: payload, - amount: 0u128, - gas_limit, + pub fn encode(&self) -> Vec { + let mut buf = vec![]; + buf.extend_from_slice(&self.task_id.to_be_bytes()); + for op in &self.ops { + op.encode_to(&mut buf); } + buf } } -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_payload() { - let msg = Msg { - source_network: 42, - source: [0; 32], - dest_network: 69, - dest: [0; 20], - gas_limit: 0, - salt: [0; 32], - data: vec![], - }; - let params = GmpParams { - network_id: msg.dest_network, - gateway_contract: [0; 20].into(), - tss_public_key: [0; 33], - }; - let expected_bytes = "19013e3afdf794f679fcbf97eba49dbe6b67cec6c7d029f1ad9a5e1a8ffefa8db2724ed044f24764343e77b5677d43585d5d6f1b7618eeddf59280858c68350af1cd"; - let bytes = Message::gmp(msg).to_eip712_bytes(¶ms); - assert_eq!(hex::encode(bytes), expected_bytes); +#[cfg_attr(feature = "std", derive(Serialize, Deserialize))] +#[derive(Debug, Clone, Decode, DecodeAsType, Encode, TypeInfo, PartialEq)] +pub enum GmpEvent { + MessageReceived(GmpMessage), + MessageExecuted(MessageId), +} + +#[cfg(feature = "std")] +use crate::TssSignature; +#[cfg(feature = "std")] +use anyhow::Result; +#[cfg(feature = "std")] +use futures::Stream; +#[cfg(feature = "std")] +use std::num::NonZeroU64; +#[cfg(feature = "std")] +use std::ops::Range; +#[cfg(feature = "std")] +use std::path::PathBuf; +#[cfg(feature = "std")] +use std::pin::Pin; + +#[cfg(feature = "std")] +pub struct ConnectorParams { + pub network_id: NetworkId, + pub blockchain: String, + pub network: String, + pub url: String, + pub keyfile: PathBuf, +} + +#[cfg(feature = "std")] +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct Network { + pub network_id: NetworkId, + pub gateway: Gateway, + pub relative_gas_price: (u128, u128), + pub gas_limit: u64, + pub base_fee: u128, +} + +#[cfg(feature = "std")] +#[async_trait::async_trait] +pub trait IChain { + /// Formats an address into a string. + fn format_address(&self, address: Address) -> String; + /// Parses an address from a string. + fn parse_address(&self, address: &str) -> Result
; + /// Formats a balance into a string. + fn format_balance(&self, balance: u128) -> String { + balance.to_string() } + /// Parses a balance from a string. + fn parse_balance(&self, balance: &str) -> Result { + Ok(balance.parse().map_err(|_| anyhow::anyhow!("expected unsigned integer"))?) + } + /// Network identifier. + fn network_id(&self) -> NetworkId; + /// Human readable connector account identifier. + fn address(&self) -> Address; + /// Queries the account balance. + async fn balance(&self, address: Address) -> Result; +} + +#[cfg(feature = "std")] +#[async_trait::async_trait] +pub trait IConnector: IChain { + /// Creates a new connector. + async fn new(params: ConnectorParams) -> Result + where + Self: Sized; + /// Reads gmp messages from the target chain. + async fn read_events( + &self, + gateway: Gateway, + from_block: Option, + to_block: u64, + ) -> Result>; + /// Submits a gmp message to the target chain. + async fn submit_commands( + &self, + gateway: Gateway, + msg: Vec, + signer: TssPublicKey, + sig: TssSignature, + ) -> Result<(), String>; + /// Stream of finalized block indexes. + fn block_stream(&self) -> Pin + Send + '_>>; +} + +#[cfg(feature = "std")] +#[async_trait::async_trait] +pub trait IConnectorAdmin: IChain { + /// Creates a new connector. + async fn new( + params: ConnectorParams, + gateway: PathBuf, + proxy: PathBuf, + tester: PathBuf, + ) -> Result + where + Self: Sized; + + /// Deploys the gateway contract. + async fn deploy_gateway(&self) -> Result<(Address, u64)>; + /// Redeploys the gateway contract. + async fn redeploy_gateway(&self, gateway: Address) -> Result<()>; + /// Returns the gateway admin. + async fn admin(&self, gateway: Address) -> Result
; + /// Sets the gateway admin. + async fn set_admin(&self, gateway: Address, admin: Address) -> Result<()>; + /// Returns the registered shard keys. + async fn shards(&self, gateway: Address) -> Result>; + /// Sets the registered shard keys. Overwrites any other keys. + async fn set_shards(&self, gateway: Address, keys: &[TssPublicKey]) -> Result<()>; + /// Returns the gateway routing table. + async fn networks(&self, gateway: Address) -> Result>; + /// Updates an entry in the gateway routing table. + async fn set_network(&self, gateway: Address, network: Network) -> Result<()>; + /// Uses a faucet to fund the account when possible. + async fn faucet(&self) -> Result<()>; + /// Transfers an amount to an account. + async fn transfer(&self, address: Address, amount: u128) -> Result<()>; + /// Deploys a test contract. + async fn deploy_test(&self, gateway: Address) -> Result<(Address, u64)>; + /// Estimates the message cost. + async fn estimate_message_cost( + &self, + gateway: Address, + dest: NetworkId, + msg_size: usize, + ) -> Result; + /// Sends a message using the test contract. + async fn send_message(&self, contract: Address, msg: GmpMessage) -> Result<()>; + /// Receives messages from test contract. + async fn recv_messages(&self, contract: Address, blocks: Range) + -> Result>; } diff --git a/primitives/src/lib.rs b/primitives/src/lib.rs index 64407f4d67..fdf75a71b1 100644 --- a/primitives/src/lib.rs +++ b/primitives/src/lib.rs @@ -111,6 +111,7 @@ sp_api::decl_runtime_apis! { pub trait NetworksApi { fn get_network(network_id: NetworkId) -> Option<(ChainName, ChainNetwork)>; + fn get_gateway(network: NetworkId) -> Option; } pub trait ShardsApi { @@ -122,15 +123,11 @@ sp_api::decl_runtime_apis! { } pub trait TasksApi { - fn get_shard_tasks(shard_id: ShardId) -> Vec; + fn get_shard_tasks(shard_id: ShardId) -> Vec; fn get_task(task_id: TaskId) -> Option; - fn get_task_signature(task_id: TaskId) -> Option; fn get_task_signer(task_id: TaskId) -> Option; - fn get_task_hash(task_id: TaskId) -> Option<[u8; 32]>; - fn get_task_phase(task_id: TaskId) -> TaskPhase; fn get_task_result(task_id: TaskId) -> Option; fn get_task_shard(task_id: TaskId) -> Option; - fn get_gateway(network: NetworkId) -> Option<[u8; 20]>; } pub trait SubmitTransactionApi{ @@ -223,21 +220,13 @@ pub trait Runtime: Clone + Send + Sync + 'static { shard_id: ShardId, ) -> Result>; - async fn get_shard_tasks( - &self, - block: BlockHash, - shard_id: ShardId, - ) -> Result>; + async fn get_shard_tasks(&self, block: BlockHash, shard_id: ShardId) -> Result>; async fn get_task(&self, block: BlockHash, task_id: TaskId) -> Result>; - async fn get_task_signature(&self, task_id: TaskId) -> Result>; - async fn get_task_signer(&self, task_id: TaskId) -> Result>; - async fn get_task_hash(&self, task_id: TaskId) -> Result>; - - async fn get_gateway(&self, network: NetworkId) -> Result>; + async fn get_gateway(&self, network: NetworkId) -> Result>; async fn submit_register_member( &self, @@ -259,10 +248,5 @@ pub trait Runtime: Clone + Send + Sync + 'static { async fn submit_online(&self, shard_id: ShardId) -> Result<()>; - async fn submit_task_signature(&self, task_id: TaskId, signature: TssSignature) -> Result<()>; - - async fn submit_task_hash(&self, task_id: TaskId, hash: Result<[u8; 32], String>) - -> Result<()>; - async fn submit_task_result(&self, task_id: TaskId, status: TaskResult) -> Result<()>; } diff --git a/primitives/src/shard.rs b/primitives/src/shard.rs index 0646a2dcae..6e27922748 100644 --- a/primitives/src/shard.rs +++ b/primitives/src/shard.rs @@ -1,11 +1,12 @@ #[cfg(feature = "std")] +use crate::task::TaskId; +#[cfg(feature = "std")] use crate::BlockNumber; #[cfg(feature = "std")] use futures::channel::oneshot; #[cfg(feature = "std")] use serde::{Deserialize, Serialize}; -use crate::TaskExecution; use scale_codec::{Decode, Encode}; use scale_info::prelude::string::String; use scale_info::prelude::vec::Vec; @@ -19,6 +20,28 @@ pub type ShardId = u64; pub type ProofOfKnowledge = [u8; 65]; pub type Commitment = Vec; +#[cfg(feature = "std")] +pub mod serde_tss_public_key { + use super::TssPublicKey; + use serde::de::Error; + use serde::{Deserialize, Deserializer, Serialize, Serializer}; + + pub fn serialize(t: &TssPublicKey, ser: S) -> Result + where + S: Serializer, + { + t[..].serialize(ser) + } + + pub fn deserialize<'de, D>(de: D) -> Result + where + D: Deserializer<'de>, + { + let bytes = >::deserialize(de)?; + TssPublicKey::try_from(bytes).map_err(|_| D::Error::custom("invalid public key length")) + } +} + #[derive(Debug, Clone, Eq, PartialEq, Encode, Decode, TypeInfo)] pub enum MemberStatus { Added, @@ -66,7 +89,7 @@ impl Default for ShardStatus { #[cfg(feature = "std")] pub struct TssSigningRequest { - pub request_id: TaskExecution, + pub task_id: TaskId, pub shard_id: ShardId, pub block_number: BlockNumber, pub data: Vec, diff --git a/primitives/src/task.rs b/primitives/src/task.rs index dd9ee31ac4..75f11f57d0 100644 --- a/primitives/src/task.rs +++ b/primitives/src/task.rs @@ -1,68 +1,38 @@ -use crate::{AccountId, Balance, IGateway, NetworkId, ShardId, TssSignature}; +use crate::{GatewayOp, GmpEvent, NetworkId, ShardId, TssSignature}; use scale_codec::{Decode, Encode}; use scale_decode::DecodeAsType; -use scale_info::{ - prelude::{string::String, vec::Vec}, - TypeInfo, -}; +use scale_info::{prelude::vec::Vec, TypeInfo}; #[cfg(feature = "std")] use serde::{Deserialize, Serialize}; -use polkadot_sdk::sp_runtime::Percent; - pub type TaskId = u64; pub type TaskIndex = u64; #[cfg_attr(feature = "std", derive(Serialize, Deserialize))] #[derive(Debug, Clone, Decode, Encode, TypeInfo, PartialEq)] pub enum Function { - // sign - RegisterShard { shard_id: ShardId }, - UnregisterShard { shard_id: ShardId }, - SendMessage { msg: Msg }, - // write - EvmDeploy { bytecode: Vec }, - EvmCall { address: [u8; 20], input: Vec, amount: u128, gas_limit: Option }, - // read - EvmViewCall { address: [u8; 20], input: Vec }, - EvmTxReceipt { tx: [u8; 32] }, - ReadMessages { batch_size: core::num::NonZeroU64 }, + ReadGatewayEvents { batch_size: core::num::NonZeroU64 }, + SignPayload { payload: Vec }, + SubmitGatewayMessage { ops: Vec }, } #[cfg(feature = "std")] impl std::fmt::Display for Function { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { match self { - Function::RegisterShard { shard_id: _ } => write!(f, "RegisterShard"), - Function::UnregisterShard { shard_id: _ } => write!(f, "UnregisterShard"), - Function::ReadMessages { batch_size } => write!(f, "ReadMessages({batch_size})"), - Function::SendMessage { msg: _ } => write!(f, "SendMessage"), - Function::EvmDeploy { bytecode: _ } => write!(f, "EvmDeploy"), - Function::EvmCall { - address: _, - input: _, - amount: _, - gas_limit: _, - } => write!(f, "EvmCall"), - Function::EvmViewCall { address: _, input: _ } => write!(f, "EvmViewCall"), - Function::EvmTxReceipt { tx: _ } => write!(f, "EvmTxReceipt"), + Function::ReadGatewayEvents { batch_size } => { + write!(f, "ReadGatewayEvents({batch_size})") + }, + Function::SubmitGatewayMessage { ops: _ } => write!(f, "SubmitGatewayMessage"), + Function::SignPayload { payload } => { + let len = payload.len(); + write!(f, "SignPayload({len})") + }, } } } impl Function { - pub fn initial_phase(&self) -> TaskPhase { - match self { - Self::RegisterShard { .. } - | Self::UnregisterShard { .. } - | Self::SendMessage { .. } => TaskPhase::Sign, - Self::EvmDeploy { .. } | Self::EvmCall { .. } => TaskPhase::Write, - Self::EvmViewCall { .. } | Self::EvmTxReceipt { .. } | Self::ReadMessages { .. } => { - TaskPhase::Read - }, - } - } - pub fn get_input_length(&self) -> u32 { self.encoded_size() as _ } @@ -71,153 +41,20 @@ impl Function { #[derive(Debug, Clone, Decode, DecodeAsType, Encode, TypeInfo, PartialEq)] pub struct TaskResult { pub shard_id: ShardId, - pub payload: Payload, + pub payload: Vec, pub signature: TssSignature, } -#[cfg_attr(feature = "std", derive(Serialize, Deserialize))] -#[derive(Debug, Clone, Decode, DecodeAsType, Encode, TypeInfo, PartialEq)] -pub enum Payload { - Hashed([u8; 32]), - Error(String), - Gmp(Vec), -} - -impl Payload { - pub fn bytes(&self, task_id: TaskId) -> Vec { - (task_id, self).encode() - } - - pub fn get_input_length(&self) -> u32 { - self.encoded_size() as _ - } -} - -#[cfg_attr(feature = "std", derive(Serialize, Deserialize))] -#[derive(Debug, Clone, Default, Decode, DecodeAsType, Encode, TypeInfo, PartialEq)] -pub struct Msg { - pub source_network: NetworkId, - pub source: [u8; 32], - pub dest_network: NetworkId, - pub dest: [u8; 20], - pub gas_limit: u128, - pub salt: [u8; 32], - pub data: Vec, -} - -impl Msg { - #[must_use] - pub fn from_event(event: IGateway::GmpCreated, source_network: u16) -> Self { - Self { - source_network, - source: event.sender.0, - dest_network: event.network, - dest: event.recipient.0 .0, - gas_limit: u128::try_from(event.gasLimit).unwrap_or(u128::MAX), - salt: event.salt.to_be_bytes(), - data: event.data.into(), - } - } -} - #[cfg_attr(feature = "std", derive(Serialize, Deserialize))] #[derive(Debug, Clone, Decode, Encode, TypeInfo, PartialEq)] pub struct TaskDescriptor { - pub owner: Option, pub network: NetworkId, pub function: Function, pub start: u64, - pub shard_size: u16, -} - -#[derive(Debug, Clone, Decode, Encode, TypeInfo, PartialEq)] -pub struct TaskDescriptorParams { - pub network: NetworkId, - pub start: u64, - pub function: Function, - pub funds: Balance, - pub shard_size: u16, } -impl TaskDescriptorParams { - pub fn new(network: NetworkId, function: Function, shard_size: u16) -> Self { - Self { - network, - start: 0, - function, - funds: 0, - shard_size, - } +impl TaskDescriptor { + pub fn new(network: NetworkId, function: Function) -> Self { + Self { network, function, start: 0 } } } - -#[cfg_attr(feature = "std", derive(Serialize, Deserialize))] -#[derive(Debug, Clone, Copy, Decode, Encode, TypeInfo, PartialEq, Eq, PartialOrd, Ord, Hash)] -pub enum TaskPhase { - Sign, - Write, - Read, -} - -#[cfg(feature = "std")] -impl std::fmt::Display for TaskPhase { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - match self { - TaskPhase::Sign => write!(f, "Sign"), - TaskPhase::Write => write!(f, "Write"), - TaskPhase::Read => write!(f, "Read"), - } - } -} - -impl Default for TaskPhase { - fn default() -> Self { - Self::Read - } -} - -#[cfg_attr(feature = "std", derive(Serialize, Deserialize))] -#[derive(Clone, Copy, Debug, Encode, Decode, TypeInfo, PartialEq, Eq, PartialOrd, Ord, Hash)] -pub struct TaskExecution { - pub task_id: TaskId, - pub phase: TaskPhase, -} - -impl TaskExecution { - pub fn new(task_id: TaskId, phase: TaskPhase) -> Self { - Self { task_id, phase } - } -} - -#[cfg(feature = "std")] -impl std::fmt::Display for TaskExecution { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - write!(f, "{}-{}", self.task_id, self.phase) - } -} - -#[derive(Debug, Clone, Decode, Encode, TypeInfo, PartialEq)] -pub struct DepreciationRate { - pub blocks: BlockNumber, - pub percent: Percent, -} - -#[derive(Debug, Clone, Decode, Encode, TypeInfo, PartialEq)] -/// Struct representing a task's reward configuration -/// Stored at task creation -pub struct RewardConfig { - /// For each shard member - pub read_task_reward: Balance, - /// For the signer - pub write_task_reward: Balance, - /// For each shard member - pub send_message_reward: Balance, - /// Depreciation rate for all rewards - pub depreciation_rate: DepreciationRate, -} - -#[derive(Debug, Clone, Decode, Encode, TypeInfo, PartialEq, Eq, PartialOrd, Ord)] -pub enum TaskFunder { - //Account(AccountId), - Treasury, -}