Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

15 changes: 12 additions & 3 deletions ethexe/cli/src/commands/tx.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,9 @@ use clap::{Parser, Subcommand};
use ethexe_common::{
Address, BlockHeader, SimpleBlockData,
gear_core::{ids::prelude::CodeIdExt, limited::LimitedVec, rpc::ReplyInfo},
injected::{AddressedInjectedTransaction, InjectedTransaction, MAX_INJECTED_TX_PAYLOAD_SIZE},
injected::{
AddressedInjectedTransaction, InjectedTransaction, MAX_INJECTED_TX_PAYLOAD_SIZE, Receipt,
},
};
use ethexe_ethereum::{Ethereum, EthereumBuilder, mirror::ClaimInfo, router::CodeValidationResult};
use ethexe_rpc::{InjectedClient, ProgramClient};
Expand Down Expand Up @@ -1126,12 +1128,19 @@ impl TxCommand {
|| "failed to send injected transaction to Vara.eth RPC",
)?;

let promise = subscription
let receipt = subscription
.next()
.await
.ok_or_else(|| anyhow!("no promise received from subscription"))?
.with_context(|| "failed to receive transaction promise")?
.into_data();
.data()
.clone();
let promise = match receipt {
Receipt::Promise(promise) => promise,
Receipt::Error(err) => {
return Err(anyhow!("injected transaction failed: {err}"));
}
};
let ReplyInfo {
payload,
value,
Expand Down
8 changes: 4 additions & 4 deletions ethexe/common/src/db.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ use crate::{
Schedule, SimpleBlockData, ValidatorsVec,
events::BlockEvent,
gear::StateTransition,
injected::{InjectedTransaction, Promise, SignedCompactPromise, SignedInjectedTransaction},
injected::{InjectedTransaction, Promise, SignedInjectedTransaction, SignedTxReceipt},
};
use alloc::{
collections::{BTreeSet, VecDeque},
Expand Down Expand Up @@ -121,8 +121,8 @@ pub trait InjectedStorageRO {
/// Returns the promise by its transaction hash.
fn promise(&self, hash: HashOf<InjectedTransaction>) -> Option<Promise>;

/// Returns the compact promise by its transaction hash.
fn compact_promise(&self, hash: HashOf<InjectedTransaction>) -> Option<SignedCompactPromise>;
/// Returns the receipt by its transaction hash.
fn receipt(&self, hash: HashOf<InjectedTransaction>) -> Option<SignedTxReceipt>;
}

#[auto_impl::auto_impl(&)]
Expand All @@ -131,7 +131,7 @@ pub trait InjectedStorageRW: InjectedStorageRO {

fn set_promise(&self, promise: &Promise);

fn set_compact_promise(&self, promise: &SignedCompactPromise);
fn set_receipt(&self, receipt: &SignedTxReceipt);
}

#[derive(Debug, Clone, Default, Encode, Decode, TypeInfo, PartialEq, Eq, Hash)]
Expand Down
241 changes: 190 additions & 51 deletions ethexe/common/src/injected.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ use alloc::string::{String, ToString};
use core::hash::Hash;
use gear_core::{limited::LimitedVec, rpc::ReplyInfo};
use gprimitives::{ActorId, H256, MessageId};
use gsigner::{PrivateKey, secp256k1::signature::SignResult};
use gsigner::Signature;
use parity_scale_codec::{Decode, Encode, MaxEncodedLen};
use scale_info::TypeInfo;
use sha3::{Digest, Keccak256};
Expand Down Expand Up @@ -167,13 +167,6 @@ impl ToDigest for Promise {
}
}

/// A signed wrapper on top of [`CompactPromise`].
///
/// [`SignedCompactPromise`] is a lightweight version of [`SignedPromise`], that is
/// needed to reduce the amount of data transferred in network between validators.
#[derive(Debug, Clone, PartialEq, Eq, Encode, Decode, derive_more::Deref, derive_more::From)]
pub struct SignedCompactPromise(SignedMessage<CompactPromise>);

/// The hashes of [`Promise`] parts.
#[derive(Debug, Clone, Encode, Decode, PartialEq, Eq)]
pub struct CompactPromise {
Expand All @@ -193,36 +186,179 @@ impl ToDigest for CompactPromise {
}
}

impl SignedCompactPromise {
/// Create the [`SignedCompactPromise`] from private key and hashes.
pub fn create(private_key: PrivateKey, promise_hashes: CompactPromise) -> SignResult<Self> {
SignedMessage::create(private_key, promise_hashes).map(SignedCompactPromise)
mod sealed {
pub trait Sealed {}

impl Sealed for super::Promise {}
impl Sealed for super::CompactPromise {}
}

pub trait PromiseKind: sealed::Sealed {
fn tx_hash(&self) -> HashOf<InjectedTransaction>;
}

impl PromiseKind for Promise {
fn tx_hash(&self) -> HashOf<InjectedTransaction> {
self.tx_hash
}
}

pub fn create_from_promise(private_key: PrivateKey, promise: &Promise) -> SignResult<Self> {
Self::create(private_key, promise.to_compact())
impl PromiseKind for CompactPromise {
fn tx_hash(&self) -> HashOf<InjectedTransaction> {
self.tx_hash
}
}

/// Receipt for [InjectedTransaction].
///
/// This type generic over promise type in purpose to support both
/// [CompactPromise] and [Promise].
///
/// [CompactPromise] generic uses only for transport purposes. End user
/// always receives the full version.
///
/// **Important**: `Receipt<CompactPromise>` and `Receipt<Promise>` have the same
/// digest. So it helps to reuses the producer's signature to construct the full
/// version from compact.
#[derive(
Debug, Clone, PartialEq, Eq, Encode, Decode, derive_more::IsVariant, derive_more::Unwrap,
)]
#[cfg_attr(feature = "std", derive(serde::Serialize, serde::Deserialize))]
pub enum Receipt<P> {
Promise(P),
/// No promise, transaction wasn't executed.
Error(TransactionError),
}

/// Create the [`SignedCompactPromise`] from a valid [`SignedPromise`].
///
/// # Panics
/// Panics if the digest of [`Promise`] and [`CompactPromise`] ever diverge.
/// This must hold by construction; tests enforce the invariant.
pub fn from_signed_promise(signed_promise: &SignedPromise) -> Self {
let compact = signed_promise.data().to_compact();
let (signature, address) = (*signed_promise.signature(), signed_promise.address());

SignedMessage::try_from_parts(compact, signature, address)
.expect("SignedPromise and CompactPromise must have identical digest")
.into()
impl<P: PromiseKind> Receipt<P> {
pub fn tx_hash(&self) -> HashOf<InjectedTransaction> {
match self {
Self::Promise(promise) => promise.tx_hash(),
Self::Error(err) => err.tx_hash,
}
}
}

impl<P: ToDigest> ToDigest for Receipt<P> {
fn update_hasher(&self, hasher: &mut sha3::Keccak256) {
match self {
Self::Promise(promise) => {
hasher.update([0]);
hasher.update(promise.to_digest().0);
}
Self::Error(err) => {
hasher.update([1]);
hasher.update(err.to_digest().0);
}
}
}
}

/// Tries to restore the [SignedPromise] with provided [Promise] body.
pub fn restore(&self, promise: Promise) -> Result<SignedPromise, &'static str> {
SignedMessage::try_from_parts(promise, *self.0.signature(), self.0.address())
/// Signed [Receipt] with a [Promise] generic.
/// End RPC user always receives this object.
#[derive(Debug, Clone, PartialEq, Eq, Encode, Decode, derive_more::From, derive_more::Deref)]
#[cfg_attr(feature = "std", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "std", serde(transparent))]
pub struct SignedTxReceipt(SignedMessage<Receipt<Promise>>);

/// Signed [Receipt] with a [CompactPromise] generic.
/// It is used as a lightweight transfer type
#[derive(Debug, Clone, PartialEq, Eq, Encode, Decode, derive_more::Deref, derive_more::From)]
pub struct SignedCompactTxReceipt(SignedMessage<Receipt<CompactPromise>>);

/// The result of [upgrade](SignedCompactTxReceipt::upgrade) function.
/// [Ready](Self::Ready) means that receipt contains an error and was upgraded
/// to full version.
/// [Pending](Self::Pending) means that receipt contains a promise and requires the
/// full promise body to restore receipt.
#[derive(Debug, PartialEq, Eq, derive_more::From)]
pub enum UpgradedReceipt {
Pending(UnfilledPromiseReceipt),
Ready(SignedTxReceipt),
}

impl SignedCompactTxReceipt {
/// Upgrades the compact receipt to its full version ([SignedTxReceipt]).
pub fn upgrade(self) -> UpgradedReceipt {
let (receipt, signature, address) = self.0.into_parts_full();

match receipt {
Receipt::Promise(compact) => {
UpgradedReceipt::Pending(UnfilledPromiseReceipt(compact, signature, address))
}
Receipt::Error(error) => UpgradedReceipt::Ready(unsafe {
SignedMessage::from_parts_unchecked(Receipt::Error(error), signature, address)
.into()
}),
}
}
}
/// Encoding and decoding of `LimitedVec<u8, N>` as hex string.

/// Intermediate type between receipt's states [SignedCompactTxReceipt] and [SignedTxReceipt].
/// Use method [try_fill_with](Self::try_fill_with) to build the [SignedTxReceipt].
#[derive(Debug, Clone, PartialEq, Eq, derive_more::Deref)]
pub struct UnfilledPromiseReceipt(#[deref] CompactPromise, Signature, Address);

/// The result of [try_fill_with](UnfilledPromiseReceipt::try_fill_with) function.
/// [Filled](Self::Filled) means the successful result.
/// [HashesMismatch](Self::HashesMismatch) means that raw promise body and stored compact are not the same promise.
pub enum TryFillPromiseResult {
Filled(SignedTxReceipt),
HashesMismatch(UnfilledPromiseReceipt),
}

impl UnfilledPromiseReceipt {
pub fn try_fill_with(self, promise: Promise) -> TryFillPromiseResult {
if self.0 != promise.to_compact() {
return TryFillPromiseResult::HashesMismatch(self);
}
let Self(.., signature, address) = self;
TryFillPromiseResult::Filled(unsafe {
SignedMessage::from_parts_unchecked(Receipt::Promise(promise), signature, address)
.into()
})
}
}

/// Represents the reason why [InjectedTransaction] was not included.
#[derive(Debug, Clone, PartialEq, Eq, Encode, Decode, derive_more::Display)]
#[cfg_attr(feature = "std", derive(serde::Deserialize, serde::Serialize))]
#[display("Injected transaction wasn't executed: tx_hash={tx_hash}, reason={reason}")]
pub struct TransactionError {
pub tx_hash: HashOf<InjectedTransaction>,
pub reason: TransactionErrorReason,
}

impl ToDigest for TransactionError {
fn update_hasher(&self, hasher: &mut sha3::Keccak256) {
let Self { tx_hash, reason } = self;
hasher.update(tx_hash.inner().0);
hasher.update([reason.variant_index()]);
}
}

/// Reason why transaction was not executed in chain.
#[repr(u8)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Encode, Decode, derive_more::Display)]
#[cfg_attr(feature = "std", derive(serde::Deserialize, serde::Serialize))]
pub enum TransactionErrorReason {
/// Transaction is outdated and can not be included.
#[display("Transaction is outdated")]
Outdated = 1,

// Important: Keep it in the end of enum.
// In future we will support non zero value injected txs.
#[display("Transaction's value must be zero")]
NonZeroValue = 2,
}

impl TransactionErrorReason {
pub fn variant_index(&self) -> u8 {
unsafe { (self as *const TransactionErrorReason as *const u8).read() }
}
}

/// Encoding and decoding of [LimitedVec<u8, N>] as hex string.
#[cfg(feature = "std")]
mod serde_hex {
pub fn serialize<S, const N: usize>(
Expand Down Expand Up @@ -300,34 +436,37 @@ mod tests {
}

#[test]
fn signatures_equal_for_promise_and_compact_promise() {
let private_key = PrivateKey::random();
fn tx_receipt_has_the_same_hash_for_promise() {
let pk = PrivateKey::random();
let promise = Promise::mock(());
let compact_promise = promise.to_compact();

let signed_promise = SignedPromise::create(private_key.clone(), promise.clone()).unwrap();
let compact_signed_promise =
SignedCompactPromise::create_from_promise(private_key, &promise).unwrap();

assert_eq!(signed_promise.address(), compact_signed_promise.address());
let receipt_promise = Receipt::Promise(promise);
let receipt_compact_promise = Receipt::Promise(compact_promise);
assert_eq!(
signed_promise.signature().clone(),
compact_signed_promise.signature().clone()
receipt_promise.to_digest(),
receipt_compact_promise.to_digest()
);
}

#[test]
fn compact_signed_promise_correctly_builds_from_signed_promise() {
let private_key = PrivateKey::random();
let promise = Promise::mock(());

let signed_promise = SignedPromise::create(private_key.clone(), promise).unwrap();

let compact_signed_promise = SignedCompactPromise::from_signed_promise(&signed_promise);
let signed_receipt = SignedMessage::create(pk.clone(), receipt_promise).unwrap();
let signed_compact_receipt = SignedMessage::create(pk, receipt_compact_promise).unwrap();

assert_eq!(signed_promise.address(), compact_signed_promise.address());
assert_eq!(
signed_promise.signature().clone(),
compact_signed_promise.signature().clone()
*signed_receipt.signature(),
*signed_compact_receipt.signature()
);
assert_eq!(signed_receipt.address(), signed_compact_receipt.address());
}

#[test]
fn tx_receipt_has_the_same_hash_for_error() {
let error = TransactionError {
tx_hash: unsafe { HashOf::new(H256::random()) },
reason: TransactionErrorReason::Outdated,
};
let receipt1 = Receipt::<Promise>::Error(error.clone());
let receipt2 = Receipt::<CompactPromise>::Error(error);

assert_eq!(receipt1.to_digest(), receipt2.to_digest());
}
}
6 changes: 2 additions & 4 deletions ethexe/consensus/src/announces.rs
Original file line number Diff line number Diff line change
Expand Up @@ -714,17 +714,15 @@ pub fn accept_announce(db: &impl DBAnnouncesExt, announce: Announce) -> Result<A
let tx_checker = TxValidityChecker::new_for_announce(db, block, announce.parent)?;

for tx in announce.injected_transactions.iter() {
let validity_status = tx_checker.check_tx_validity(tx)?;

match validity_status {
match tx_checker.check_tx_validity(tx)? {
TxValidity::Valid => {
db.set_injected_transaction(tx.clone());
}

validity => {
tracing::trace!(
announce = ?announce.to_hash(),
"announce contains invalid transition with status {validity_status:?}, rejecting announce."
"announce contains invalid transition with status {validity:?}, rejecting announce."
);

return Ok(AnnounceStatus::Rejected {
Expand Down
Loading
Loading