Skip to content

Commit

Permalink
aligning
Browse files Browse the repository at this point in the history
  • Loading branch information
Jakub Zajkowski committed Nov 23, 2024
1 parent 843b19e commit f1c8ec0
Show file tree
Hide file tree
Showing 8 changed files with 396 additions and 121 deletions.
16 changes: 8 additions & 8 deletions Cargo.lock

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

52 changes: 31 additions & 21 deletions node/src/types/transaction/meta_transaction/meta_transaction_v1.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,7 @@ const ARGS_MAP_KEY: u16 = 0;
const TARGET_MAP_KEY: u16 = 1;
const ENTRY_POINT_MAP_KEY: u16 = 2;
const SCHEDULING_MAP_KEY: u16 = 3;
const TRANSFERRED_VALUE_MAP_KEY: u16 = 4;
const SEED_MAP_KEY: u16 = 5;
const EXPECTED_NUMBER_OF_FIELDS: usize = 6;
const EXPECTED_NUMBER_OF_FIELDS: usize = 4;

#[derive(Clone, Debug, Serialize, DataSize)]
pub struct MetaTransactionV1 {
Expand All @@ -37,8 +35,6 @@ pub struct MetaTransactionV1 {
approvals: BTreeSet<Approval>,
serialized_length: usize,
payload_hash: Digest,
transferred_value: u64,
seed: Option<[u8; 32]>,
has_valid_hash: Result<(), InvalidTransactionV1>,
#[serde(skip)]
#[data_size(skip)]
Expand All @@ -64,14 +60,6 @@ impl MetaTransactionV1 {
v1.deserialize_field(SCHEDULING_MAP_KEY).map_err(|error| {
InvalidTransaction::V1(InvalidTransactionV1::CouldNotDeserializeField { error })
})?;
let transferred_value =
v1.deserialize_field(TRANSFERRED_VALUE_MAP_KEY)
.map_err(|error| {
InvalidTransaction::V1(InvalidTransactionV1::CouldNotDeserializeField { error })
})?;
let seed = v1.deserialize_field(SEED_MAP_KEY).map_err(|error| {
InvalidTransaction::V1(InvalidTransactionV1::CouldNotDeserializeField { error })
})?;

if v1.number_of_fields() != EXPECTED_NUMBER_OF_FIELDS {
return Err(InvalidTransaction::V1(
Expand Down Expand Up @@ -108,8 +96,6 @@ impl MetaTransactionV1 {
serialized_length,
payload_hash,
approvals,
transferred_value,
seed,
has_valid_hash,
))
}
Expand Down Expand Up @@ -149,8 +135,6 @@ impl MetaTransactionV1 {
serialized_length: usize,
payload_hash: Digest,
approvals: BTreeSet<Approval>,
transferred_value: u64,
seed: Option<[u8; 32]>,
has_valid_hash: Result<(), InvalidTransactionV1>,
) -> Self {
Self {
Expand All @@ -169,8 +153,6 @@ impl MetaTransactionV1 {
serialized_length,
payload_hash,
has_valid_hash,
transferred_value,
seed,
is_verified: OnceCell::new(),
}
}
Expand Down Expand Up @@ -654,12 +636,40 @@ impl MetaTransactionV1 {

/// Returns the seed of the transaction.
pub(crate) fn seed(&self) -> Option<[u8; 32]> {
self.seed
match &self.target {
TransactionTarget::Native => None,
TransactionTarget::Stored {
id: _,
runtime: _,
transferred_value: _,
} => None,
TransactionTarget::Session {
is_install_upgrade: _,
runtime: _,
module_bytes: _,
transferred_value: _,
seed,
} => seed.clone(),
}
}

/// Returns the transferred value of the transaction.
pub fn transferred_value(&self) -> u64 {
self.transferred_value
match &self.target {
TransactionTarget::Native => 0,
TransactionTarget::Stored {
id: _,
runtime: _,
transferred_value,
} => *transferred_value,
TransactionTarget::Session {
is_install_upgrade: _,
runtime: _,
module_bytes: _,
transferred_value,
seed: _,
} => *transferred_value,
}
}
}

Expand Down
17 changes: 7 additions & 10 deletions resources/test/sse_data_schema.json
Original file line number Diff line number Diff line change
Expand Up @@ -898,7 +898,7 @@
],
"properties": {
"Version1": {
"$ref": "#/definitions/TransactionV1"
"$ref": "#/definitions/TransactionV1Json"
}
},
"additionalProperties": false
Expand Down Expand Up @@ -1555,7 +1555,7 @@
"description": "Hex-encoded cryptographic signature, including the algorithm tag prefix.",
"type": "string"
},
"TransactionV1": {
"TransactionV1Json": {
"description": "A unit of work sent by a client to the network, which when executed can cause global state to be altered.",
"type": "object",
"required": [
Expand All @@ -1568,7 +1568,7 @@
"$ref": "#/definitions/TransactionV1Hash"
},
"payload": {
"$ref": "#/definitions/TransactionV1Payload"
"$ref": "#/definitions/TransactionV1PayloadJson"
},
"approvals": {
"type": "array",
Expand All @@ -1577,11 +1577,10 @@
},
"uniqueItems": true
}
},
"additionalProperties": false
}
},
"TransactionV1Payload": {
"description": "A unit of work sent by a client to the network, which when executed can cause global state to be altered.",
"TransactionV1PayloadJson": {
"description": "Internal payload of the transaction. The actual data over which the signing is done.",
"type": "object",
"required": [
"chain_name",
Expand Down Expand Up @@ -1609,9 +1608,7 @@
},
"fields": {
"type": "object",
"additionalProperties": {
"$ref": "#/definitions/Bytes"
}
"additionalProperties": true
}
},
"additionalProperties": false
Expand Down
2 changes: 1 addition & 1 deletion types/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ proptest = { version = "1.0.0", optional = true }
proptest-derive = { version = "0.3.0", optional = true }
rand = { version = "0.8.3", default-features = false, features = ["small_rng"] }
rand_pcg = { version = "0.3.0", optional = true }
schemars = { version = "0.8.16", features = ["preserve_order"], optional = true }
schemars = { version = "0.8.21", features = ["preserve_order"], optional = true }
serde-map-to-array = "1.1.0"
serde = { version = "1", default-features = false, features = ["alloc", "derive"] }
serde_bytes = { version = "0.11.5", default-features = false, features = ["alloc"] }
Expand Down
109 changes: 102 additions & 7 deletions types/src/transaction.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,15 @@ use alloc::{
};
use core::fmt::{self, Debug, Display, Formatter};
#[cfg(any(feature = "std", test))]
use serde::{de, ser, Deserializer, Serializer};
#[cfg(any(feature = "std", test))]
use serde_bytes::ByteBuf;
#[cfg(any(feature = "std", test))]
use std::hash::Hash;
#[cfg(any(feature = "std", test))]
use thiserror::Error;
#[cfg(any(feature = "std", test))]
use transaction_v1::TransactionV1Json;

#[cfg(feature = "json-schema")]
use crate::URef;
Expand Down Expand Up @@ -119,18 +127,17 @@ pub(super) static TRANSACTION: Lazy<Transaction> = Lazy::new(|| {

/// A versioned wrapper for a transaction or deploy.
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
#[cfg_attr(
any(feature = "std", test),
derive(Serialize, Deserialize),
serde(deny_unknown_fields)
)]
#[cfg_attr(feature = "datasize", derive(DataSize))]
#[cfg_attr(feature = "json-schema", derive(JsonSchema))]
#[cfg_attr(feature = "datasize", derive(DataSize))]
pub enum Transaction {
/// A deploy.
Deploy(Deploy),
/// A version 1 transaction.
#[cfg_attr(any(feature = "std", test), serde(rename = "Version1"))]
#[cfg_attr(
feature = "json-schema",
serde(rename = "Version1"),
schemars(with = "TransactionV1Json")
)]
V1(TransactionV1),
}

Expand Down Expand Up @@ -397,6 +404,94 @@ impl Transaction {
}
}

#[cfg(any(feature = "std", test))]
impl Serialize for Transaction {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
if serializer.is_human_readable() {
TransactionJson::try_from(self.clone())
.map_err(|error| ser::Error::custom(format!("{:?}", error)))?
.serialize(serializer)
} else {
let bytes = self
.to_bytes()
.map_err(|error| ser::Error::custom(format!("{:?}", error)))?;
ByteBuf::from(bytes).serialize(serializer)
}
}
}

#[cfg(any(feature = "std", test))]
impl<'de> Deserialize<'de> for Transaction {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
if deserializer.is_human_readable() {
let json_helper = TransactionJson::deserialize(deserializer)?;
Transaction::try_from(json_helper)
.map_err(|error| de::Error::custom(format!("{:?}", error)))
} else {
let bytes = ByteBuf::deserialize(deserializer)?.into_vec();
bytesrepr::deserialize::<Transaction>(bytes)
.map_err(|error| de::Error::custom(format!("{:?}", error)))
}
}
}

/// A util structure to json-serialize a transaction.
#[cfg(any(feature = "std", test))]
#[derive(Clone, Serialize, Deserialize, PartialEq, Eq)]
#[cfg_attr(feature = "json-schema", derive(JsonSchema))]
#[serde(deny_unknown_fields)]
enum TransactionJson {
/// A deploy.
Deploy(Deploy),
/// A version 1 transaction.
#[serde(rename = "Version1")]
V1(TransactionV1Json),
}

#[cfg(any(feature = "std", test))]
#[derive(Error, Debug)]
enum TransactionJsonError {
#[error("{0}")]
FailedToMap(String),
}

#[cfg(any(feature = "std", test))]
impl TryFrom<TransactionJson> for Transaction {
type Error = TransactionJsonError;
fn try_from(transaction: TransactionJson) -> Result<Self, Self::Error> {
match transaction {
TransactionJson::Deploy(deploy) => Ok(Transaction::Deploy(deploy)),
TransactionJson::V1(v1) => {
TransactionV1::try_from(v1)
.map(Transaction::V1)
.map_err(|error| {
TransactionJsonError::FailedToMap(format!(
"Failed to map TransactionJson::V1 to Transaction::V1, err: {}",
error
))
})
}
}
}
}

#[cfg(any(feature = "std", test))]
impl TryFrom<Transaction> for TransactionJson {
type Error = TransactionJsonError;
fn try_from(transaction: Transaction) -> Result<Self, Self::Error> {
match transaction {
Transaction::Deploy(deploy) => Ok(TransactionJson::Deploy(deploy)),
Transaction::V1(v1) => TransactionV1Json::try_from(v1)
.map(TransactionJson::V1)
.map_err(|error| {
TransactionJsonError::FailedToMap(format!(
"Failed to map Transaction::V1 to TransactionJson::V1, err: {}",
error
))
}),
}
}
}
/// Calculates gas limit.
#[cfg(any(feature = "std", test))]
pub trait GasLimited {
Expand Down
Loading

0 comments on commit f1c8ec0

Please sign in to comment.