From cd1627222451ff9dadc2729222b99cecc614eecf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marin=20Ver=C5=A1i=C4=87?= Date: Mon, 6 Dec 2021 15:44:57 +0100 Subject: [PATCH] [feature] #1675: use type instead of wrapper struct for versioned items (#1665) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * use type instead of wrapper struct for inner versioned items Signed-off-by: Marin Veršić * rename unwrap methods on versioned structures Signed-off-by: Marin Veršić Co-authored-by: Aleksandr Petrosyan --- client/src/client.rs | 23 ++- core/src/block.rs | 87 +++++------ core/src/block_sync.rs | 20 +-- core/src/event.rs | 4 +- core/src/queue.rs | 8 +- core/src/smartcontracts/isi/query.rs | 8 +- core/src/sumeragi/mod.rs | 34 ++--- core/src/torii/mod.rs | 4 +- core/src/torii/tests.rs | 4 +- core/src/tx.rs | 42 +++-- core/src/wsv.rs | 23 ++- core/test_network/tests/sumeragi_with_mock.rs | 2 +- data_model/src/events.rs | 24 ++- data_model/src/query.rs | 12 +- data_model/src/transaction.rs | 143 +++++++----------- version/derive/src/lib.rs | 124 +-------------- version/derive/tests/as_version.rs | 39 ----- version/derive/tests/json.rs | 14 +- version/derive/tests/scale.rs | 14 +- .../tests/ui/fail_invalid_range_equal.stderr | 8 - .../tests/ui/fail_invalid_range_less.stderr | 8 - ...ned.rs => ok_declare_several_versioned.rs} | 10 +- .../derive/tests/ui/ok_declare_versioned.rs | 8 +- .../tests/ui/ok_declare_versioned_json.rs | 8 +- .../tests/ui/ok_declare_versioned_scale.rs | 8 +- 25 files changed, 222 insertions(+), 457 deletions(-) delete mode 100644 version/derive/tests/as_version.rs rename version/derive/tests/ui/{ok_declare_several_vesrioned.rs => ok_declare_several_versioned.rs} (76%) diff --git a/client/src/client.rs b/client/src/client.rs index 232aa419355..b339da59ca9 100644 --- a/client/src/client.rs +++ b/client/src/client.rs @@ -329,10 +329,8 @@ impl Client { std::str::from_utf8(response.body()).unwrap_or(""), )); } - let QueryResult(result) = VersionedQueryResult::decode_versioned(response.body())? - .into_v1() - .ok_or_else(|| eyre!("Expected query result V1"))? - .into(); + let result = VersionedQueryResult::decode_versioned(response.body())?; + let VersionedQueryResult::V1(QueryResult(result)) = result; R::Output::try_from(result) .map_err(Into::into) .wrap_err("Unexpected type") @@ -385,11 +383,9 @@ impl Client { self.headers.clone(), )?; if response.status() == StatusCode::OK { - let pending_transactions: PendingTransactions = - VersionedPendingTransactions::decode_versioned(response.body())? - .into_v1() - .ok_or_else(|| eyre!("Expected pending transaction message version 1."))? - .into(); + let pending_transactions = + VersionedPendingTransactions::decode_versioned(response.body())?; + let VersionedPendingTransactions::V1(pending_transactions) = pending_transactions; let transaction = pending_transactions .into_iter() .find(|pending_transaction| { @@ -400,7 +396,7 @@ impl Client { if transaction.is_some() { return Ok(transaction); } - thread::sleep(retry_in) + thread::sleep(retry_in); } else { return Err(eyre!( "Failed to make query request with HTTP status: {}, {}", @@ -544,10 +540,9 @@ impl EventIterator { ))?; loop { match stream.read_message() { - Ok(WebSocketMessage::Binary(this_message)) => { + Ok(WebSocketMessage::Binary(message)) => { if let EventSocketMessage::SubscriptionAccepted = - VersionedEventSocketMessage::decode_versioned(&this_message)? - .into_inner_v1() + VersionedEventSocketMessage::decode_versioned(&message)?.into_v1() { break; } @@ -573,7 +568,7 @@ impl Iterator for EventIterator { Ok(WebSocketMessage::Binary(message)) => { let event_socket_message = match VersionedEventSocketMessage::decode_versioned(&message) { - Ok(event_socket_message) => event_socket_message.into_inner_v1(), + Ok(event_socket_message) => event_socket_message.into_v1(), Err(err) => return Some(Err(err.into())), }; let event = match event_socket_message { diff --git a/core/src/block.rs b/core/src/block.rs index 9c0f06a5f6b..b4e93660d88 100644 --- a/core/src/block.rs +++ b/core/src/block.rs @@ -60,7 +60,7 @@ impl Chain { /// Push latest block. pub fn push(&self, block: VersionedCommittedBlock) { - let height = block.as_inner_v1().header.height; + let height = block.as_v1().header.height; self.blocks.insert(height, block); } @@ -163,7 +163,7 @@ declare_versioned_with_scale!(VersionedPendingBlock 1..2, Debug, Clone, iroha_ma /// Transaction data is permanently recorded in files called blocks. Blocks are organized into /// a linear sequence over time (also known as the block chain). /// Blocks lifecycle starts from "Pending" state which is represented by `PendingBlock` struct. -#[version_with_scale(n = 1, versioned = "VersionedPendingBlock", derive = "Debug, Clone")] +#[version_with_scale(n = 1, versioned = "VersionedPendingBlock")] #[derive(Clone, Debug, Io, Encode, Decode)] pub struct PendingBlock { /// Unix time (in milliseconds) of block forming by a peer. @@ -303,8 +303,8 @@ impl ChainedBlock { Ok(tx) => txs.push(tx), Err(tx) => { iroha_logger::warn!( - reason = %tx.as_inner_v1().rejection_reason, - caused_by = ?tx.as_inner_v1().rejection_reason.source(), + reason = %tx.as_v1().rejection_reason, + caused_by = ?tx.as_v1().rejection_reason.source(), "Transaction validation failed", ); rejected.push(tx) @@ -340,39 +340,39 @@ impl ChainedBlock { declare_versioned_with_scale!(VersionedValidBlock 1..2, Debug, Clone, iroha_macro::FromVariant, IntoSchema); impl VersionedValidBlock { - /// Same as [`as_v1`](`VersionedValidBlock::as_v1()`) but also does conversion + /// Converts from `&VersionedValidBlock` to V1 reference #[inline] - pub const fn as_inner_v1(&self) -> &ValidBlock { + pub const fn as_v1(&self) -> &ValidBlock { match self { - Self::V1(v1) => &v1.0, + Self::V1(v1) => v1, } } - /// Same as [`as_inner_v1`](`VersionedValidBlock::as_inner_v1()`) but returns mutable reference + /// Converts from `&mut VersionedValidBlock` to V1 mutable reference #[inline] - pub fn as_mut_inner_v1(&mut self) -> &mut ValidBlock { + pub fn as_mut_v1(&mut self) -> &mut ValidBlock { match self { - Self::V1(v1) => &mut v1.0, + Self::V1(v1) => v1, } } - /// Same as [`into_v1`](`VersionedValidBlock::into_v1()`) but also does conversion + /// Performs the conversion from `VersionedValidBlock` to V1 #[inline] - pub fn into_inner_v1(self) -> ValidBlock { + pub fn into_v1(self) -> ValidBlock { match self { - Self::V1(v1) => v1.0, + Self::V1(v1) => v1, } } /// Returns header of valid block #[inline] pub const fn header(&self) -> &BlockHeader { - &self.as_inner_v1().header + &self.as_v1().header } /// Commit block to the store. pub fn commit(self) -> VersionedCommittedBlock { - self.into_inner_v1().commit().into() + self.into_v1().commit().into() } /// Validate block transactions against current state of the world. @@ -382,47 +382,46 @@ impl VersionedValidBlock { is_instruction_allowed: &IsInstructionAllowedBoxed, is_query_allowed: &IsQueryAllowedBoxed, ) -> VersionedValidBlock { - self.into_inner_v1() + self.into_v1() .revalidate(wsv, is_instruction_allowed, is_query_allowed) .into() } /// Calculate hash of the current block. pub fn hash(&self) -> HashOf { - self.as_inner_v1().hash().transmute() + self.as_v1().hash().transmute() } /// Sign this block and get [`VersionedValidBlock`](`Self`). /// # Errors /// Look at [`ValidBlock`](`ValidBlock`) for more info pub fn sign(self, key_pair: KeyPair) -> Result { - self.into_inner_v1().sign(key_pair).map(Into::into) + self.into_v1().sign(key_pair).map(Into::into) } /// Signatures that are verified with the `hash` of this block as `payload`. pub fn verified_signatures( &'_ self, ) -> impl Iterator> + '_ { - self.as_inner_v1() + self.as_v1() .verified_signatures() .map(SignatureOf::transmute_ref) } /// Checks if there are no transactions in this block. pub fn is_empty(&self) -> bool { - self.as_inner_v1().is_empty() + self.as_v1().is_empty() } /// Checks if block has transactions that are already in blockchain. pub fn has_committed_transactions(&self, wsv: &WorldStateView) -> bool { - self.as_inner_v1().has_committed_transactions(wsv) + self.as_v1().has_committed_transactions(wsv) } /// # Errors /// Asserts specific instruction number of instruction in transaction constraint pub fn check_instruction_len(&self, max_instruction_len: u64) -> Result<()> { - self.as_inner_v1() - .check_instruction_len(max_instruction_len) + self.as_v1().check_instruction_len(max_instruction_len) } /// Returns true if block can be send for discussion @@ -444,11 +443,7 @@ impl VersionedValidBlock { } /// After full validation `ChainedBlock` can transform into `ValidBlock`. -#[version_with_scale( - n = 1, - versioned = "VersionedValidBlock", - derive = "Debug, Clone, iroha_schema::IntoSchema" -)] +#[version_with_scale(n = 1, versioned = "VersionedValidBlock")] #[derive(Clone, Debug, Io, Encode, Decode, IntoSchema)] pub struct ValidBlock { /// Header @@ -510,7 +505,7 @@ impl ValidBlock { .collect(), } .validate(wsv, is_instruction_allowed, is_query_allowed) - .into_inner_v1() + .into_v1() } } @@ -583,7 +578,7 @@ impl ValidBlock { impl From<&VersionedValidBlock> for Vec { fn from(block: &VersionedValidBlock) -> Self { - block.as_inner_v1().into() + block.as_v1().into() } } @@ -630,41 +625,41 @@ impl From<&ValidBlock> for Vec { declare_versioned_with_scale!(VersionedCommittedBlock 1..2, Debug, Clone, iroha_macro::FromVariant, IntoSchema); impl VersionedCommittedBlock { - /// Same as [`as_v1`](`VersionedCommittedBlock::as_v1()`) but also does conversion - pub const fn as_inner_v1(&self) -> &CommittedBlock { + /// Converts from `&VersionedCommittedBlock` to V1 reference + pub const fn as_v1(&self) -> &CommittedBlock { match self { - Self::V1(v1) => &v1.0, + Self::V1(v1) => v1, } } - /// Same as [`as_inner_v1`](`VersionedCommittedBlock::as_inner_v1()`) but returns mutable reference - pub fn as_mut_inner_v1(&mut self) -> &mut CommittedBlock { + /// Converts from `&mut VersionedCommittedBlock` to V1 mutable reference + pub fn as_mut_v1(&mut self) -> &mut CommittedBlock { match self { - Self::V1(v1) => &mut v1.0, + Self::V1(v1) => v1, } } - /// Same as [`into_v1`](`VersionedCommittedBlock::into_v1()`) but also does conversion - pub fn into_inner_v1(self) -> CommittedBlock { + /// Performs the conversion from `VersionedCommittedBlock` to V1 + pub fn into_v1(self) -> CommittedBlock { match self { - Self::V1(v1) => v1.into(), + Self::V1(v1) => v1, } } /// Calculate hash of the current block. /// `VersionedCommitedBlock` should have the same hash as `VersionedCommitedBlock`. pub fn hash(&self) -> HashOf { - self.as_inner_v1().hash().transmute() + self.as_v1().hash().transmute() } /// Returns header of valid block pub const fn header(&self) -> &BlockHeader { - &self.as_inner_v1().header + &self.as_v1().header } /// Signatures that are verified with the `hash` of this block as `payload`. pub fn verified_signatures(&'_ self) -> impl Iterator> + '_ { - self.as_inner_v1() + self.as_v1() .verified_signatures() .map(SignatureOf::transmute_ref) } @@ -724,14 +719,14 @@ impl From for ValidBlock { impl From for VersionedValidBlock { #[inline] fn from(block: VersionedCommittedBlock) -> Self { - ValidBlock::from(block.into_inner_v1()).into() + ValidBlock::from(block.into_v1()).into() } } impl From<&VersionedCommittedBlock> for Vec { #[inline] fn from(block: &VersionedCommittedBlock) -> Self { - block.as_inner_v1().into() + block.as_v1().into() } } @@ -744,9 +739,7 @@ impl From<&CommittedBlock> for Vec { .map(|transaction| { PipelineEvent::new( PipelineEntityType::Transaction, - PipelineStatus::Rejected( - transaction.as_inner_v1().rejection_reason.clone().into(), - ), + PipelineStatus::Rejected(transaction.as_v1().rejection_reason.clone().into()), transaction.hash().into(), ) .into() diff --git a/core/src/block_sync.rs b/core/src/block_sync.rs index e55aaa45932..39c1a6a1e08 100644 --- a/core/src/block_sync.rs +++ b/core/src/block_sync.rs @@ -221,24 +221,24 @@ pub mod message { declare_versioned_with_scale!(VersionedMessage 1..2, Debug, Clone, iroha_macro::FromVariant, iroha_actor::Message); impl VersionedMessage { - /// Same as [`as_v1`](`VersionedMessage::as_v1()`) but also does conversion - pub const fn as_inner_v1(&self) -> &Message { + /// Converts from `&VersionedMessage` to V1 reference + pub const fn as_v1(&self) -> &Message { match self { - Self::V1(v1) => &v1.0, + Self::V1(v1) => v1, } } - /// Same as [`as_inner_v1`](`VersionedMessage::as_inner_v1()`) but returns mutable reference - pub fn as_mut_inner_v1(&mut self) -> &mut Message { + /// Converts from `&mut VersionedMessage` to V1 mutable reference + pub fn as_mut_v1(&mut self) -> &mut Message { match self { - Self::V1(v1) => &mut v1.0, + Self::V1(v1) => v1, } } - /// Same as [`into_v1`](`VersionedMessage::into_v1()`) but also does conversion - pub fn into_inner_v1(self) -> Message { + /// Performs the conversion from `VersionedMessage` to V1 + pub fn into_v1(self) -> Message { match self { - Self::V1(v1) => v1.0, + Self::V1(v1) => v1, } } } @@ -276,7 +276,7 @@ pub mod message { } /// Message's variants that are used by peers to communicate in the process of consensus. - #[version_with_scale(n = 1, versioned = "VersionedMessage", derive = "Debug, Clone")] + #[version_with_scale(n = 1, versioned = "VersionedMessage")] #[derive(Io, Decode, Encode, Debug, Clone, FromVariant, iroha_actor::Message)] pub enum Message { /// Request for blocks after the block with `Hash` for the peer with `PeerId`. diff --git a/core/src/event.rs b/core/src/event.rs index 81711211f81..9ab190d3937 100644 --- a/core/src/event.rs +++ b/core/src/event.rs @@ -47,7 +47,7 @@ impl Consumer { } let SubscriptionRequest(filter): SubscriptionRequest = VersionedEventSocketMessage::decode_versioned(message.as_bytes())? - .into_inner_v1() + .into_v1() .try_into()?; time::timeout( @@ -93,7 +93,7 @@ impl Consumer { } if let EventSocketMessage::EventReceived = - VersionedEventSocketMessage::decode_versioned(message.as_bytes())?.into_inner_v1() + VersionedEventSocketMessage::decode_versioned(message.as_bytes())?.into_v1() { self.stream.flush().await?; Ok(()) diff --git a/core/src/queue.rs b/core/src/queue.rs index a179e977aac..1e2bd36e967 100644 --- a/core/src/queue.rs +++ b/core/src/queue.rs @@ -131,9 +131,9 @@ impl Queue { // MST case old_tx .get_mut() - .as_mut_inner_v1() + .as_mut_v1() .signatures - .merge(tx.into_inner_v1().signatures); + .merge(tx.into_v1().signatures); return Ok(()); } Entry::Vacant(entry) => entry, @@ -412,7 +412,7 @@ mod tests { .txs .get(&queue.queue.pop().unwrap()) .unwrap() - .as_inner_v1() + .as_v1() .signatures .len(); assert_eq!(signature_count, 2); @@ -632,7 +632,7 @@ mod tests { let mut tx = accepted_tx("alice", "wonderland", 100_000, Some(&alice_key)); assert!(queue.push(tx.clone(), &wsv).is_ok()); // tamper timestamp - tx.as_mut_inner_v1().payload.creation_time += 2 * future_threshold_ms; + tx.as_mut_v1().payload.creation_time += 2 * future_threshold_ms; assert!(matches!(queue.push(tx, &wsv), Err((_, Error::InFuture)))); assert_eq!(queue.txs.len(), 1); } diff --git a/core/src/smartcontracts/isi/query.rs b/core/src/smartcontracts/isi/query.rs index 1c16a3c650e..ef6c4432236 100644 --- a/core/src/smartcontracts/isi/query.rs +++ b/core/src/smartcontracts/isi/query.rs @@ -6,7 +6,7 @@ use eyre::{eyre, Result}; use iroha_crypto::SignatureOf; use iroha_data_model::{prelude::*, query}; use iroha_macro::Io; -use iroha_version::{scale::DecodeVersioned, Version}; +use iroha_version::scale::DecodeVersioned; use parity_scale_codec::{Decode, Encode}; use thiserror::Error; use warp::{ @@ -160,11 +160,7 @@ impl TryFrom<&Bytes> for VerifiedQueryRequest { fn try_from(body: &Bytes) -> Result { let query = VersionedSignedQueryRequest::decode_versioned(body.as_ref()) .map_err(|e| Error::Decode(Box::new(e)))?; - let version = query.version(); - let query: SignedQueryRequest = query - .into_v1() - .ok_or(Error::Version(UnsupportedVersionError { version }))? - .into(); + let VersionedSignedQueryRequest::V1(query) = query; VerifiedQueryRequest::try_from(query) } } diff --git a/core/src/sumeragi/mod.rs b/core/src/sumeragi/mod.rs index 55498498408..f7fe521eb22 100644 --- a/core/src/sumeragi/mod.rs +++ b/core/src/sumeragi/mod.rs @@ -424,8 +424,8 @@ impl Handler self.broker.issue_send(data.into_inner_v1()).await, - BlockSync(data) => self.broker.issue_send(data.into_inner_v1()).await, + SumeragiMessage(data) => self.broker.issue_send(data.into_v1()).await, + BlockSync(data) => self.broker.issue_send(data.into_v1()).await, Health => {} } } @@ -943,24 +943,24 @@ pub mod message { declare_versioned_with_scale!(VersionedMessage 1..2, Debug, Clone, iroha_macro::FromVariant, iroha_actor::Message); impl VersionedMessage { - /// Same as [`as_v1`](`VersionedMessage::as_v1()`) but also does conversion - pub const fn as_inner_v1(&self) -> &Message { + /// Converts from `&VersionedMessage` to V1 reference + pub const fn as_v1(&self) -> &Message { match self { - Self::V1(v1) => &v1.0, + Self::V1(v1) => v1, } } - /// Same as [`as_inner_v1`](`VersionedMessage::as_inner_v1()`) but returns mutable reference - pub fn as_mut_inner_v1(&mut self) -> &mut Message { + /// Converts from `&mut VersionedMessage` to V1 mutable reference + pub fn as_mut_v1(&mut self) -> &mut Message { match self { - Self::V1(v1) => &mut v1.0, + Self::V1(v1) => v1, } } - /// Same as [`into_v1`](`VersionedMessage::into_v1()`) but also does conversion - pub fn into_inner_v1(self) -> Message { + /// Performs the conversion from `VersionedMessage` to V1 + pub fn into_v1(self) -> Message { match self { - Self::V1(v1) => v1.0, + Self::V1(v1) => v1, } } @@ -1001,12 +1001,12 @@ pub mod message { self, sumeragi: &mut Sumeragi, ) -> Result<()> { - self.into_inner_v1().handle(sumeragi).await + self.into_v1().handle(sumeragi).await } } /// Message's variants that are used by peers to communicate in the process of consensus. - #[version_with_scale(n = 1, versioned = "VersionedMessage", derive = "Debug, Clone")] + #[version_with_scale(n = 1, versioned = "VersionedMessage")] #[derive(Io, Decode, Encode, Debug, Clone, FromVariant, iroha_actor::Message)] pub enum Message { /// Is sent by leader to all validating peers, when a new block is created. @@ -1332,7 +1332,7 @@ pub mod message { .votes_for_blocks .entry(block_hash) .or_insert_with(|| self.block.clone()); - entry.as_mut_inner_v1().signatures.extend( + entry.as_mut_v1().signatures.extend( self.block .verified_signatures() .cloned() @@ -1360,7 +1360,7 @@ pub mod message { .map(SignatureOf::transmute) .collect(); let mut block = entry.clone(); - block.as_mut_inner_v1().signatures = signatures; + block.as_mut_v1().signatures = signatures; let block = block.sign(sumeragi.key_pair.clone())?; iroha_logger::info!( @@ -1428,9 +1428,9 @@ pub mod message { && sumeragi.latest_block_hash() == &self.block.header().previous_block_hash { let mut block = self.block.clone(); - block.as_mut_inner_v1().signatures.clear(); + block.as_mut_v1().signatures.clear(); block - .as_mut_inner_v1() + .as_mut_v1() .signatures .extend(valid_signatures.into_iter().map(SignatureOf::transmute)); sumeragi.commit_block(block).await; diff --git a/core/src/torii/mod.rs b/core/src/torii/mod.rs index 6d898657d9f..8a09b95a38a 100644 --- a/core/src/torii/mod.rs +++ b/core/src/torii/mod.rs @@ -315,7 +315,7 @@ async fn handle_instructions( state: ToriiState, transaction: VersionedTransaction, ) -> Result { - let transaction: Transaction = transaction.into_inner_v1(); + let transaction: Transaction = transaction.into_v1(); let transaction = VersionedAcceptedTransaction::from_transaction( transaction, state.iroha_cfg.torii.max_instruction_number, @@ -374,7 +374,7 @@ async fn handle_pending_transactions( .queue .all_transactions(&*state.wsv) .into_iter() - .map(VersionedAcceptedTransaction::into_inner_v1) + .map(VersionedAcceptedTransaction::into_v1) .map(Transaction::from) .paginate(pagination) .collect(), diff --git a/core/src/torii/tests.rs b/core/src/torii/tests.rs index ad70165861d..b521a2f400e 100644 --- a/core/src/torii/tests.rs +++ b/core/src/torii/tests.rs @@ -89,7 +89,7 @@ async fn torii_pagination() { let pagination = Pagination { start, limit }; handle_queries(state.clone(), pagination, query).map(|result| { let Scale(query_result) = result.unwrap(); - if let QueryResult(Value::Vec(domain)) = query_result.into_v1().unwrap().into() { + if let VersionedQueryResult::V1(QueryResult(Value::Vec(domain))) = query_result { domain } else { unreachable!() @@ -216,7 +216,7 @@ impl AssertReady { let response_body = match response.status() { StatusCode::OK => { let response: VersionedQueryResult = response.body().to_vec().try_into().unwrap(); - let QueryResult(value) = response.into_v1().unwrap().into(); + let VersionedQueryResult::V1(QueryResult(value)) = response; format!("{:?}", value) } _ => String::from_utf8(response.body().to_vec()).unwrap_or_default(), diff --git a/core/src/tx.rs b/core/src/tx.rs index 1badbb9f423..bd90cb3f1d7 100644 --- a/core/src/tx.rs +++ b/core/src/tx.rs @@ -23,24 +23,24 @@ use crate::{ declare_versioned_with_scale!(VersionedAcceptedTransaction 1..2, Debug, Clone, iroha_macro::FromVariant); impl VersionedAcceptedTransaction { - /// Same as [`as_v1`](`VersionedAcceptedTransaction::as_v1()`) but also does conversion - pub const fn as_inner_v1(&self) -> &AcceptedTransaction { + /// Converts from `&VersionedAcceptedTransaction` to V1 reference + pub const fn as_v1(&self) -> &AcceptedTransaction { match self { - VersionedAcceptedTransaction::V1(v1) => &v1.0, + VersionedAcceptedTransaction::V1(v1) => v1, } } - /// Same as [`as_inner_v1`](`VersionedAcceptedTransaction::as_inner_v1()`) but returns mutable reference - pub fn as_mut_inner_v1(&mut self) -> &mut AcceptedTransaction { + /// Converts from `&mut VersionedAcceptedTransaction` to V1 mutable reference + pub fn as_mut_v1(&mut self) -> &mut AcceptedTransaction { match self { - VersionedAcceptedTransaction::V1(v1) => &mut v1.0, + VersionedAcceptedTransaction::V1(v1) => v1, } } - /// Same as [`into_v1`](`VersionedAcceptedTransaction::into_v1()`) but also does conversion - pub fn into_inner_v1(self) -> AcceptedTransaction { + /// Performs the conversion from `VersionedAcceptedTransaction` to V1 + pub fn into_v1(self) -> AcceptedTransaction { match self { - VersionedAcceptedTransaction::V1(v1) => v1.0, + VersionedAcceptedTransaction::V1(v1) => v1, } } @@ -57,12 +57,12 @@ impl VersionedAcceptedTransaction { /// Checks if this transaction is waiting longer than specified in `transaction_time_to_live` from `QueueConfiguration` or `time_to_live_ms` of this transaction. /// Meaning that the transaction will be expired as soon as the lesser of the specified TTLs was reached. pub fn is_expired(&self, transaction_time_to_live: Duration) -> bool { - self.as_inner_v1().is_expired(transaction_time_to_live) + self.as_v1().is_expired(transaction_time_to_live) } /// If `true`, this transaction is regarded to have been tampered to have a future timestamp. pub fn is_in_future(&self, threshold: Duration) -> bool { - self.as_inner_v1().is_in_future(threshold) + self.as_v1().is_in_future(threshold) } /// Move transaction lifecycle forward by checking an ability to apply instructions to the @@ -76,7 +76,7 @@ impl VersionedAcceptedTransaction { is_query_allowed: &IsQueryAllowedBoxed, is_genesis: bool, ) -> Result { - self.into_inner_v1() + self.into_v1() .validate(wsv, is_instruction_allowed, is_query_allowed, is_genesis) .map(Into::into) .map_err(Into::into) @@ -89,7 +89,7 @@ impl VersionedAcceptedTransaction { &self, wsv: &WorldStateView, ) -> Result { - self.as_inner_v1().check_signature_condition(wsv) + self.as_v1().check_signature_condition(wsv) } /// Rejects transaction with the `rejection_reason`. @@ -97,7 +97,7 @@ impl VersionedAcceptedTransaction { self, rejection_reason: TransactionRejectionReason, ) -> VersionedRejectedTransaction { - self.into_inner_v1().reject(rejection_reason).into() + self.into_v1().reject(rejection_reason).into() } } @@ -106,16 +106,12 @@ impl Txn for VersionedAcceptedTransaction { #[inline] fn payload(&self) -> &Payload { - &self.as_inner_v1().payload + &self.as_v1().payload } } /// `AcceptedTransaction` represents a transaction accepted by iroha peer. -#[version_with_scale( - n = 1, - versioned = "VersionedAcceptedTransaction", - derive = "Debug, Clone" -)] +#[version_with_scale(n = 1, versioned = "VersionedAcceptedTransaction")] #[derive(Clone, Debug, Io, Encode, Decode)] #[non_exhaustive] pub struct AcceptedTransaction { @@ -320,7 +316,7 @@ impl IsInBlockchain for VersionedRejectedTransaction { impl From for VersionedTransaction { fn from(tx: VersionedAcceptedTransaction) -> Self { - let tx: AcceptedTransaction = tx.into_inner_v1(); + let tx: AcceptedTransaction = tx.into_v1(); let tx: Transaction = tx.into(); tx.into() } @@ -337,7 +333,7 @@ impl From for Transaction { impl From for VersionedAcceptedTransaction { fn from(tx: VersionedValidTransaction) -> Self { - let tx: ValidTransaction = tx.into_inner_v1(); + let tx: ValidTransaction = tx.into_v1(); let tx: AcceptedTransaction = tx.into(); tx.into() } @@ -354,7 +350,7 @@ impl From for AcceptedTransaction { impl From for VersionedAcceptedTransaction { fn from(tx: VersionedRejectedTransaction) -> Self { - let tx: RejectedTransaction = tx.into_inner_v1(); + let tx: RejectedTransaction = tx.into_v1(); let tx: AcceptedTransaction = tx.into(); tx.into() } diff --git a/core/src/wsv.rs b/core/src/wsv.rs index 6216c4feffb..4f1251bb123 100644 --- a/core/src/wsv.rs +++ b/core/src/wsv.rs @@ -158,9 +158,9 @@ impl WorldStateView { #[iroha_futures::telemetry_future] #[log(skip(self, block))] pub async fn apply(&self, block: VersionedCommittedBlock) -> Result<()> { - for tx in &block.as_inner_v1().transactions { + for tx in &block.as_v1().transactions { let account_id = &tx.payload().account_id; - tx.as_inner_v1() + tx.as_v1() .payload .instructions .iter() @@ -172,8 +172,7 @@ impl WorldStateView { // The transaction processing is a long CPU intensive task, so this should be included here. task::yield_now().await; } - - for tx in &block.as_inner_v1().rejected_transactions { + for tx in &block.as_v1().rejected_transactions { self.transactions.insert(tx.hash()); } self.tx_metric_update(); @@ -199,8 +198,8 @@ impl WorldStateView { #[cfg(test)] pub fn transactions_number(&self) -> u64 { self.blocks.iter().fold(0_u64, |acc, block| { - acc + block.as_inner_v1().transactions.len() as u64 - + block.as_inner_v1().rejected_transactions.len() as u64 + acc + block.as_v1().transactions.len() as u64 + + block.as_v1().rejected_transactions.len() as u64 }) } @@ -210,7 +209,7 @@ impl WorldStateView { self.blocks .iter() .next() - .map(|val| val.as_inner_v1().header.timestamp) + .map(|val| val.as_v1().header.timestamp) } /// Update metrics; run when block commits. @@ -220,8 +219,8 @@ impl WorldStateView { .iter() .last() .map(|block| { - block.as_inner_v1().transactions.len() as u64 - + block.as_inner_v1().rejected_transactions.len() as u64 + block.as_v1().transactions.len() as u64 + + block.as_v1().rejected_transactions.len() as u64 }) .unwrap_or_default(); self.metrics.txs.inc_by(last_block_txs_total); @@ -477,14 +476,14 @@ impl WorldStateView { hash: &HashOf, ) -> Option { self.blocks.iter().find_map(|b| { - b.as_inner_v1() + b.as_v1() .rejected_transactions .iter() .find(|e| e.hash() == *hash) .cloned() .map(TransactionValue::RejectedTransaction) .or_else(|| { - b.as_inner_v1() + b.as_v1() .transactions .iter() .find(|e| e.hash() == *hash) @@ -504,7 +503,7 @@ impl WorldStateView { .blocks .iter() .flat_map(|block_entry| { - let block = block_entry.value().as_inner_v1(); + let block = block_entry.value().as_v1(); block .rejected_transactions .iter() diff --git a/core/test_network/tests/sumeragi_with_mock.rs b/core/test_network/tests/sumeragi_with_mock.rs index 08b03ff294f..9ba1d4a159a 100644 --- a/core/test_network/tests/sumeragi_with_mock.rs +++ b/core/test_network/tests/sumeragi_with_mock.rs @@ -216,7 +216,7 @@ pub mod utils { S: Deref> + DerefMut + Send, { let msg = if let SumeragiMessage::BlockCreated(mut block) = msg { - block.block.as_mut_inner_v1().transactions = Vec::new(); + block.block.as_mut_v1().transactions = Vec::new(); SumeragiMessage::BlockCreated(block) } else { msg diff --git a/data_model/src/events.rs b/data_model/src/events.rs index d278357166d..b1abbdf3800 100644 --- a/data_model/src/events.rs +++ b/data_model/src/events.rs @@ -10,35 +10,31 @@ use serde::{Deserialize, Serialize}; declare_versioned_with_scale!(VersionedEventSocketMessage 1..2, Debug, Clone, FromVariant, IntoSchema); impl VersionedEventSocketMessage { - /// The same as [`as_v1`](`VersionedEventSocketMessage::as_v1()`) but also runs into on it - pub const fn as_inner_v1(&self) -> &EventSocketMessage { + /// Converts from `&VersionedEventSocketMessage` to V1 reference + pub const fn as_v1(&self) -> &EventSocketMessage { match self { - Self::V1(v1) => &v1.0, + Self::V1(v1) => v1, } } - /// The same as [`as_v1`](`VersionedEventSocketMessage::as_v1()`) but also runs into on it - pub fn as_mut_inner_v1(&mut self) -> &mut EventSocketMessage { + /// Converts from `&mut VersionedEventSocketMessage` to V1 mutable reference + pub fn as_mut_v1(&mut self) -> &mut EventSocketMessage { match self { - Self::V1(v1) => &mut v1.0, + Self::V1(v1) => v1, } } - /// The same as [`as_v1`](`VersionedEventSocketMessage::as_v1()`) but also runs into on it - pub fn into_inner_v1(self) -> EventSocketMessage { + /// Performs the conversion from `VersionedEventSocketMessage` to V1 + pub fn into_v1(self) -> EventSocketMessage { match self { - Self::V1(v1) => v1.into(), + Self::V1(v1) => v1, } } } /// Message type used for communication over web socket event stream. #[allow(variant_size_differences)] -#[version_with_scale( - n = 1, - versioned = "VersionedEventSocketMessage", - derive = "Debug, Clone, IntoSchema, Deserialize, Serialize" -)] +#[version_with_scale(n = 1, versioned = "VersionedEventSocketMessage")] #[derive(Debug, Clone, IntoSchema, FromVariant, Decode, Encode, Deserialize, Serialize)] pub enum EventSocketMessage { /// Request sent by client to subscribe to events. diff --git a/data_model/src/query.rs b/data_model/src/query.rs index efb3837b529..a38e0beb68d 100644 --- a/data_model/src/query.rs +++ b/data_model/src/query.rs @@ -129,11 +129,7 @@ pub struct QueryRequest { declare_versioned_with_scale!(VersionedSignedQueryRequest 1..2, Debug, Clone, iroha_macro::FromVariant, IntoSchema); /// I/O ready structure to send queries. -#[version_with_scale( - n = 1, - versioned = "VersionedSignedQueryRequest", - derive = "Debug, Clone, iroha_schema::IntoSchema" -)] +#[version_with_scale(n = 1, versioned = "VersionedSignedQueryRequest")] #[derive(Debug, Clone, Io, Decode, Encode, Deserialize, Serialize, IntoSchema)] pub struct SignedQueryRequest { /// Payload @@ -145,11 +141,7 @@ pub struct SignedQueryRequest { declare_versioned_with_scale!(VersionedQueryResult 1..2, Debug, Clone, iroha_macro::FromVariant, Io, IntoSchema); /// Sized container for all possible Query results. -#[version_with_scale( - n = 1, - versioned = "VersionedQueryResult", - derive = "Debug, Clone, iroha_schema::IntoSchema" -)] +#[version_with_scale(n = 1, versioned = "VersionedQueryResult")] #[derive(Debug, Clone, Io, Serialize, Deserialize, Encode, Decode, IntoSchema)] pub struct QueryResult(pub Value); diff --git a/data_model/src/transaction.rs b/data_model/src/transaction.rs index 09aa5194d73..6cb50540bfb 100644 --- a/data_model/src/transaction.rs +++ b/data_model/src/transaction.rs @@ -95,32 +95,33 @@ declare_versioned!( VersionedTransaction 1..2, Debug, Clone, + PartialEq, + Eq, iroha_macro::FromVariant, IntoSchema, - Eq ); impl VersionedTransaction { - /// Same as [`as_v1`](`VersionedTransaction::as_v1()`) but also does conversion - pub const fn as_inner_v1(&self) -> &Transaction { + /// Converts from `&VersionedTransaction` to V1 reference + pub const fn as_v1(&self) -> &Transaction { match self { - Self::V1(v1) => &v1.0, + Self::V1(v1) => v1, } } - /// Same as [`as_inner_v1`](`VersionedTransaction::as_inner_v1()`) but returns mutable reference + /// Converts from `&mut VersionedTransaction` to V1 mutable reference #[inline] - pub fn as_mut_inner_v1(&mut self) -> &mut Transaction { + pub fn as_mut_v1(&mut self) -> &mut Transaction { match self { - Self::V1(v1) => &mut v1.0, + Self::V1(v1) => v1, } } - /// Same as [`into_v1`](`VersionedTransaction::into_v1()`) but also does conversion + /// Performs the conversion from `VersionedTransaction` to V1 #[inline] - pub fn into_inner_v1(self) -> Transaction { + pub fn into_v1(self) -> Transaction { match self { - Self::V1(v1) => v1.0, + Self::V1(v1) => v1, } } @@ -139,7 +140,7 @@ impl VersionedTransaction { /// # Errors /// Fails if signature creation fails pub fn sign(self, key_pair: &KeyPair) -> Result { - self.into_inner_v1().sign(key_pair).map(Into::into) + self.into_v1().sign(key_pair).map(Into::into) } } @@ -149,17 +150,7 @@ impl Txn for VersionedTransaction { #[inline] fn payload(&self) -> &Payload { match self { - Self::V1(v1) => &v1.0.payload, - } - } -} - -impl PartialEq for VersionedTransaction { - fn eq(&self, other: &Self) -> bool { - use VersionedTransaction::*; - - match (self, other) { - (V1(first), V1(second)) => first.0.eq(&second.0), + Self::V1(v1) => &v1.payload, } } } @@ -167,20 +158,18 @@ impl PartialEq for VersionedTransaction { impl From for VersionedTransaction { fn from(transaction: VersionedValidTransaction) -> Self { match transaction { - VersionedValidTransaction::V1(v1) => { - let tx: ValidTransaction = v1.0; - - let signatures = tx + VersionedValidTransaction::V1(transaction) => { + let signatures = transaction .signatures .values() .iter() .cloned() .collect::>(); - let tx = Transaction { - payload: tx.payload, + let transaction = Transaction { + payload: transaction.payload, signatures, }; - tx.into() + transaction.into() } } } @@ -191,11 +180,7 @@ impl From for VersionedTransaction { /// `Iroha` and its' clients use [`Transaction`] to send transactions via network. /// Direct usage in business logic is strongly prohibited. Before any interactions /// `accept`. -#[version( - n = 1, - versioned = "VersionedTransaction", - derive = "Clone, Debug, Io, Eq, PartialEq, iroha_schema::IntoSchema" -)] +#[version(n = 1, versioned = "VersionedTransaction")] #[derive(Clone, Debug, Io, Encode, Decode, Serialize, Deserialize, Eq, PartialEq, IntoSchema)] pub struct Transaction { /// [`Transaction`] payload. @@ -287,24 +272,24 @@ impl Txn for Transaction { declare_versioned_with_scale!(VersionedPendingTransactions 1..2, iroha_macro::FromVariant, Clone, Debug); impl VersionedPendingTransactions { - /// Same as [`as_v1`](`VersionedPendingTransactions::as_v1()`) but also does conversion - pub const fn as_inner_v1(&self) -> &PendingTransactions { + /// Converts from `&VersionedPendingTransactions` to V1 reference + pub const fn as_v1(&self) -> &PendingTransactions { match self { - Self::V1(v1) => &v1.0, + Self::V1(v1) => v1, } } - /// Same as [`as_inner_v1`](`VersionedPendingTransactions::as_inner_v1()`) but returns mutable reference - pub fn as_mut_inner_v1(&mut self) -> &mut PendingTransactions { + /// Converts from `&mut VersionedPendingTransactions` to V1 mutable reference + pub fn as_mut_v1(&mut self) -> &mut PendingTransactions { match self { - Self::V1(v1) => &mut v1.0, + Self::V1(v1) => v1, } } - /// Same as [`into_v1`](`VersionedPendingTransactions::into_v1()`) but also does conversion - pub fn into_inner_v1(self) -> PendingTransactions { + /// Performs the conversion from `VersionedPendingTransactions` to V1 + pub fn into_v1(self) -> PendingTransactions { match self { - Self::V1(v1) => v1.0, + Self::V1(v1) => v1, } } } @@ -328,11 +313,7 @@ impl Reply for VersionedPendingTransactions { } /// Represents a collection of transactions that the peer sends to describe its pending transactions in a queue. -#[version_with_scale( - n = 1, - versioned = "VersionedPendingTransactions", - derive = "Debug, Clone" -)] +#[version_with_scale(n = 1, versioned = "VersionedPendingTransactions")] #[derive(Debug, Clone, Encode, Decode, Deserialize, Serialize, Io, IntoSchema)] pub struct PendingTransactions(pub Vec); @@ -395,25 +376,25 @@ impl PartialOrd for TransactionValue { declare_versioned_with_scale!(VersionedValidTransaction 1..2, Debug, Clone, iroha_macro::FromVariant, IntoSchema); impl VersionedValidTransaction { - /// Same as [`as_v1`](`VersionedValidTransaction::as_v1()`) but also does conversion + /// Converts from `&VersionedValidTransaction` to V1 reference #[inline] - pub const fn as_inner_v1(&self) -> &ValidTransaction { + pub const fn as_v1(&self) -> &ValidTransaction { match self { - Self::V1(v1) => &v1.0, + Self::V1(v1) => v1, } } - /// Same as [`as_inner_v1`](`VersionedValidTransaction::as_inner_v1()`) but returns mutable reference - pub fn as_mut_inner_v1(&mut self) -> &mut ValidTransaction { + /// Converts from `&mut VersionedValidTransaction` to V1 mutable reference + pub fn as_mut_v1(&mut self) -> &mut ValidTransaction { match self { - Self::V1(v1) => &mut v1.0, + Self::V1(v1) => v1, } } - /// Same as [`into_v1`](`VersionedValidTransaction::into_v1()`) but also does conversion - pub fn into_inner_v1(self) -> ValidTransaction { + /// Performs the conversion from `VersionedValidTransaction` to V1 + pub fn into_v1(self) -> ValidTransaction { match self { - Self::V1(v1) => v1.0, + Self::V1(v1) => v1, } } } @@ -423,17 +404,13 @@ impl Txn for VersionedValidTransaction { #[inline] fn payload(&self) -> &Payload { - &self.as_inner_v1().payload + &self.as_v1().payload } } /// `ValidTransaction` represents trustfull Transaction state. -#[version_with_scale( - n = 1, - versioned = "VersionedValidTransaction", - derive = "Debug, Clone, iroha_schema::IntoSchema" -)] -#[derive(Clone, Debug, Io, Encode, Decode, IntoSchema)] +#[version_with_scale(n = 1, versioned = "VersionedValidTransaction")] +#[derive(Clone, Debug, Io, Encode, Decode, iroha_schema::IntoSchema)] pub struct ValidTransaction { /// The [`Transaction`]'s payload. pub payload: Payload, @@ -450,27 +427,27 @@ impl Txn for ValidTransaction { } } -declare_versioned!(VersionedRejectedTransaction 1..2, iroha_macro::FromVariant, Clone, Debug, IntoSchema, Eq); +declare_versioned!(VersionedRejectedTransaction 1..2, Clone, Debug, PartialEq, Eq, iroha_macro::FromVariant, IntoSchema); impl VersionedRejectedTransaction { - /// The same as [`as_v1`](`VersionedRejectedTransaction::as_v1()`) but also runs into on it - pub const fn as_inner_v1(&self) -> &RejectedTransaction { + /// Converts from `&VersionedRejectedTransaction` to V1 reference + pub const fn as_v1(&self) -> &RejectedTransaction { match self { - Self::V1(v1) => &v1.0, + Self::V1(v1) => v1, } } - /// The same as [`as_v1`](`VersionedRejectedTransaction::as_v1()`) but also runs into on it - pub fn as_mut_inner_v1(&mut self) -> &mut RejectedTransaction { + /// Converts from `&mut VersionedRejectedTransaction` to V1 mutable reference + pub fn as_mut_v1(&mut self) -> &mut RejectedTransaction { match self { - Self::V1(v1) => &mut v1.0, + Self::V1(v1) => v1, } } - /// The same as [`as_v1`](`VersionedRejectedTransaction::as_v1()`) but also runs into on it - pub fn into_inner_v1(self) -> RejectedTransaction { + /// Performs the conversion from `VersionedRejectedTransaction` to V1 + pub fn into_v1(self) -> RejectedTransaction { match self { - Self::V1(v1) => v1.into(), + Self::V1(v1) => v1, } } } @@ -481,27 +458,13 @@ impl Txn for VersionedRejectedTransaction { #[inline] fn payload(&self) -> &Payload { match self { - Self::V1(v1) => &v1.0.payload, - } - } -} - -impl PartialEq for VersionedRejectedTransaction { - fn eq(&self, other: &Self) -> bool { - use VersionedRejectedTransaction::*; - - match (self, other) { - (V1(first), V1(second)) => first.0.eq(&second.0), + Self::V1(v1) => &v1.payload, } } } /// [`RejectedTransaction`] represents transaction rejected by some validator at some stage of the pipeline. -#[version( - n = 1, - versioned = "VersionedRejectedTransaction", - derive = "Debug, Clone, PartialEq, Eq, iroha_schema::IntoSchema" -)] +#[version(n = 1, versioned = "VersionedRejectedTransaction")] #[derive(Clone, Debug, Io, Encode, Decode, Serialize, Deserialize, PartialEq, Eq, IntoSchema)] pub struct RejectedTransaction { /// The [`Transaction`]'s payload. diff --git a/version/derive/src/lib.rs b/version/derive/src/lib.rs index c8c2598a37d..25d6c2c8959 100644 --- a/version/derive/src/lib.rs +++ b/version/derive/src/lib.rs @@ -12,7 +12,7 @@ use proc_macro2::{Span, TokenStream as TokenStream2}; use proc_macro_error::{abort, abort_call_site, proc_macro_error, OptionExt, ResultExt}; use quote::{format_ident, quote}; use syn::{ - parse::{Parse, ParseStream, Parser}, + parse::{Parse, ParseStream}, parse_macro_input, punctuated::Punctuated, spanned::Spanned, @@ -24,7 +24,6 @@ const VERSION_NUMBER_ARG_NAME: &str = "n"; const VERSIONED_STRUCT_ARG_NAME: &str = "versioned"; const VERSION_FIELD_NAME: &str = "version"; const CONTENT_FIELD_NAME: &str = "content"; -const DERIVE_FIELD_NAME: &str = "derive"; /// Used to declare that this struct represents a particular version as a part of the versioned container. /// @@ -40,7 +39,7 @@ const DERIVE_FIELD_NAME: &str = "derive"; #[proc_macro_attribute] pub fn version(attr: TokenStream, item: TokenStream) -> TokenStream { let args = parse_macro_input!(attr as AttributeArgs); - impl_version(args, item, true, true).into() + impl_version(args, item).into() } /// See [`version()`] for more information. @@ -48,7 +47,7 @@ pub fn version(attr: TokenStream, item: TokenStream) -> TokenStream { #[proc_macro_attribute] pub fn version_with_scale(attr: TokenStream, item: TokenStream) -> TokenStream { let args = parse_macro_input!(attr as AttributeArgs); - impl_version(args, item, false, true).into() + impl_version(args, item).into() } /// See [`version()`] for more information. @@ -56,7 +55,7 @@ pub fn version_with_scale(attr: TokenStream, item: TokenStream) -> TokenStream { #[proc_macro_attribute] pub fn version_with_json(attr: TokenStream, item: TokenStream) -> TokenStream { let args = parse_macro_input!(attr as AttributeArgs); - impl_version(args, item, true, false).into() + impl_version(args, item).into() } /// Used to generate a versioned container with the given name and given range of supported versions. @@ -111,12 +110,7 @@ pub fn declare_versioned_with_json(input: TokenStream) -> TokenStream { impl_declare_versioned(&args, false, true).into() } -fn impl_version( - args: Vec, - item: TokenStream, - with_json: bool, - with_scale: bool, -) -> TokenStream2 { +fn impl_version(args: Vec, item: TokenStream) -> TokenStream2 { let (item, struct_name) = if let Ok(item_struct) = syn::parse::(item.clone()) { (quote!(#item_struct), item_struct.ident) } else if let Ok(item_enum) = syn::parse::(item) { @@ -142,11 +136,6 @@ fn impl_version( }) .collect(); - let derives = args_map - .get(DERIVE_FIELD_NAME) - .map_or_else(|| Ok(Punctuated::new()), get_derives) - .expect_or_abort("Failed to parse passed derives"); - let version_number = args_map .get(VERSION_NUMBER_ARG_NAME) .expect_or_abort(&format!( @@ -179,59 +168,15 @@ fn impl_version( "Versioned struct name argument should have a string value." ) }; - let wrapper_struct_name = format_ident!("_{}V{}", versioned_struct_name, version_number); - let versioned_struct_name = Ident::new(&versioned_struct_name, Span::call_site()); - let json_derives = if with_json { - quote!(serde::Serialize, serde::Deserialize,) - } else { - quote!() - }; - let scale_derives = if with_scale { - quote!(parity_scale_codec::Encode, parity_scale_codec::Decode,) - } else { - quote!() - }; + let alias_type_name = format_ident!("_{}V{}", versioned_struct_name, version_number); quote!( - /// Autogenerated wrapper struct to link versioned item to its container. - #[derive(#scale_derives #json_derives #derives)] - pub struct #wrapper_struct_name (#struct_name); - - impl From<#wrapper_struct_name> for #struct_name { - fn from(wrapper: #wrapper_struct_name) -> Self { - let #wrapper_struct_name (inner) = wrapper; - inner - } - } - - impl From<#struct_name> for #wrapper_struct_name { - fn from(origin: #struct_name) -> Self { - #wrapper_struct_name (origin) - } - } - - impl From<#struct_name> for #versioned_struct_name { - fn from(origin: #struct_name) -> Self { - let wrapped: #wrapper_struct_name = origin.into(); - wrapped.into() - } - } + /// Autogenerated alias type to link versioned item to its container. + type #alias_type_name = #struct_name; #item ) } -fn get_derives(derive: &Lit) -> syn::Result> { - let lit = if let Lit::Str(lit) = derive { - lit - } else { - return Ok(Punctuated::new()); - }; - let parser = |stream: ParseStream<'_>| -> syn::parse::Result> { - Punctuated::parse_terminated(stream) - }; - parser.parse_str(&lit.value()) -} - struct DeclareVersionedArgs { pub enum_name: Ident, pub range: Range, @@ -259,22 +204,6 @@ impl DeclareVersionedArgs { pub fn version_numbers(&self) -> Vec { self.range.clone().into_iter().collect() } - - pub fn version_method_idents_into(&self) -> Vec { - self.range - .clone() - .into_iter() - .map(|i| Ident::new(&format!("into_v{}", i), Span::call_site())) - .collect() - } - - pub fn version_method_idents_as(&self) -> Vec { - self.range - .clone() - .into_iter() - .map(|i| Ident::new(&format!("as_v{}", i), Span::call_site())) - .collect() - } } impl Parse for DeclareVersionedArgs { @@ -369,40 +298,6 @@ fn impl_json(enum_name: &Ident, version_field_name: &str) -> proc_macro2::TokenS ) } -fn impl_as_from(args: &DeclareVersionedArgs) -> proc_macro2::TokenStream { - let version_idents = args.version_idents(); - let version_struct_idents = args.version_struct_idents(); - let version_method_idents_as = args.version_method_idents_as(); - let version_method_idents_into = args.version_method_idents_into(); - let enum_name = &args.enum_name; - quote!( - impl #enum_name { - #( - /// Returns Some(ref _) if this container has this version. None otherwise. - pub fn #version_method_idents_as (&self) -> Option<& #version_struct_idents> { - use #enum_name::*; - - match self { - #version_idents (content) => Some(content), - _ => None - } - } - )* - #( - /// Returns Some(_) if this container has this version. None otherwise. - pub fn #version_method_idents_into (self) -> Option<#version_struct_idents> { - use #enum_name::*; - - match self { - #version_idents (content) => Some(content), - _ => None - } - } - )* - } - ) -} - //TODO using this cause linters issue FIXME https://jira.hyperledger.org/browse/IR-1048 fn impl_declare_versioned( args: &DeclareVersionedArgs, @@ -463,7 +358,6 @@ fn impl_declare_versioned( } }) .collect(); - let impl_as_from = impl_as_from(args); let derives = &args.derive; quote!( @@ -491,8 +385,6 @@ fn impl_declare_versioned( } } - #impl_as_from - #scale_impl #json_impl diff --git a/version/derive/tests/as_version.rs b/version/derive/tests/as_version.rs deleted file mode 100644 index 92fefe58b53..00000000000 --- a/version/derive/tests/as_version.rs +++ /dev/null @@ -1,39 +0,0 @@ -#[cfg(test)] -mod tests { - #![allow(unused_results)] - - use iroha_version_derive::{declare_versioned, version}; - use parity_scale_codec::{Decode, Encode}; - use serde::{Deserialize, Serialize}; - - declare_versioned!(VersionedMessage 1..3, Debug, Clone, iroha_macro::FromVariant); - - #[version(n = 1, versioned = "VersionedMessage", derive = "Debug, Clone")] - #[derive(Debug, Clone, Decode, Encode, Serialize, Deserialize)] - pub struct Message; - - #[version(n = 2, versioned = "VersionedMessage", derive = "Debug, Clone")] - #[derive(Debug, Clone, Decode, Encode, Serialize, Deserialize)] - pub struct Message2; - - #[test] - fn as_version() -> Result<(), String> { - let versioned_message: VersionedMessage = Message.into(); - let _message: Message = versioned_message - .as_v1() - .ok_or_else(|| "Should be version 1.".to_owned())? - .clone() - .into(); - Ok(()) - } - - #[test] - fn into_version() -> Result<(), String> { - let versioned_message: VersionedMessage = Message.into(); - let _message: Message = versioned_message - .into_v1() - .ok_or_else(|| "Should be version 1.".to_owned())? - .into(); - Ok(()) - } -} diff --git a/version/derive/tests/json.rs b/version/derive/tests/json.rs index 1d9452077eb..2f7ef1ce23c 100644 --- a/version/derive/tests/json.rs +++ b/version/derive/tests/json.rs @@ -21,11 +21,11 @@ mod tests { declare_versioned!(VersionedMessage 1..3, Debug, Clone, iroha_macro::FromVariant); - #[version(n = 1, versioned = "VersionedMessage", derive = "Debug, Clone")] + #[version(n = 1, versioned = "VersionedMessage")] #[derive(Debug, Clone, Decode, Encode, Serialize, Deserialize)] pub struct Message; - #[version(n = 2, versioned = "VersionedMessage", derive = "Debug, Clone")] + #[version(n = 2, versioned = "VersionedMessage")] #[derive(Debug, Clone, Decode, Encode, Serialize, Deserialize)] pub struct Message2; } @@ -37,15 +37,15 @@ mod tests { declare_versioned!(VersionedMessage 1..4, Debug, Clone, iroha_macro::FromVariant); - #[version(n = 1, versioned = "VersionedMessage", derive = "Debug, Clone")] + #[version(n = 1, versioned = "VersionedMessage")] #[derive(Debug, Clone, Decode, Encode, Serialize, Deserialize)] pub struct Message; - #[version(n = 2, versioned = "VersionedMessage", derive = "Debug, Clone")] + #[version(n = 2, versioned = "VersionedMessage")] #[derive(Debug, Clone, Decode, Encode, Serialize, Deserialize)] pub struct Message2; - #[version(n = 3, versioned = "VersionedMessage", derive = "Debug, Clone")] + #[version(n = 3, versioned = "VersionedMessage")] #[derive(Debug, Clone, Decode, Encode, Serialize, Deserialize)] pub struct Message3(pub String); } @@ -62,11 +62,11 @@ mod tests { VersionedMessage::from_versioned_json_str(&json).map_err(|e| e.to_string())?; match decoded_message { VersionedMessage::V1(message) => { - let _: Message = message.into(); + let _: Message = message; Ok(()) } VersionedMessage::V2(message) => { - let _: Message2 = message.into(); + let _: Message2 = message; Err("Should have been message v1.".to_owned()) } } diff --git a/version/derive/tests/scale.rs b/version/derive/tests/scale.rs index be03e0b239d..8f0001b39c1 100644 --- a/version/derive/tests/scale.rs +++ b/version/derive/tests/scale.rs @@ -22,11 +22,11 @@ mod tests { declare_versioned!(VersionedMessage 1..3, Debug, Clone, iroha_macro::FromVariant); - #[version(n = 1, versioned = "VersionedMessage", derive = "Debug, Clone")] + #[version(n = 1, versioned = "VersionedMessage")] #[derive(Debug, Clone, Decode, Encode, Serialize, Deserialize)] pub struct Message; - #[version(n = 2, versioned = "VersionedMessage", derive = "Debug, Clone")] + #[version(n = 2, versioned = "VersionedMessage")] #[derive(Debug, Clone, Decode, Encode, Serialize, Deserialize)] pub struct Message2; } @@ -38,15 +38,15 @@ mod tests { declare_versioned!(VersionedMessage 1..4, Debug, Clone, iroha_macro::FromVariant); - #[version(n = 1, versioned = "VersionedMessage", derive = "Debug, Clone")] + #[version(n = 1, versioned = "VersionedMessage")] #[derive(Debug, Clone, Decode, Encode, Serialize, Deserialize)] pub struct Message; - #[version(n = 2, versioned = "VersionedMessage", derive = "Debug, Clone")] + #[version(n = 2, versioned = "VersionedMessage")] #[derive(Debug, Clone, Decode, Encode, Serialize, Deserialize)] pub struct Message2; - #[version(n = 3, versioned = "VersionedMessage", derive = "Debug, Clone")] + #[version(n = 3, versioned = "VersionedMessage")] #[derive(Debug, Clone, Decode, Encode, Serialize, Deserialize)] pub struct Message3(pub String); } @@ -63,11 +63,11 @@ mod tests { VersionedMessage::decode_versioned(&bytes).map_err(|e| e.to_string())?; match decoded_message { VersionedMessage::V1(message) => { - let _: Message = message.into(); + let _: Message = message; Ok(()) } VersionedMessage::V2(message) => { - let _: Message2 = message.into(); + let _: Message2 = message; Err("Should have been message v1.".to_owned()) } } diff --git a/version/derive/tests/ui/fail_invalid_range_equal.stderr b/version/derive/tests/ui/fail_invalid_range_equal.stderr index 1504936e5fa..1c3e36f92a6 100644 --- a/version/derive/tests/ui/fail_invalid_range_equal.stderr +++ b/version/derive/tests/ui/fail_invalid_range_equal.stderr @@ -5,11 +5,3 @@ error: The end version should be higher then the start version. | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | = note: this error originates in the macro `declare_versioned` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0412]: cannot find type `VersionedMessage` in this scope - --> tests/ui/fail_invalid_range_equal.rs:7:1 - | -7 | #[version(n = 1, versioned = "VersionedMessage")] - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ not found in this scope - | - = note: this error originates in the attribute macro `version` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/version/derive/tests/ui/fail_invalid_range_less.stderr b/version/derive/tests/ui/fail_invalid_range_less.stderr index 5e90bd21d01..2b0959f076e 100644 --- a/version/derive/tests/ui/fail_invalid_range_less.stderr +++ b/version/derive/tests/ui/fail_invalid_range_less.stderr @@ -5,11 +5,3 @@ error: The end version should be higher then the start version. | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | = note: this error originates in the macro `declare_versioned` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0412]: cannot find type `VersionedMessage` in this scope - --> tests/ui/fail_invalid_range_less.rs:7:1 - | -7 | #[version(n = 1, versioned = "VersionedMessage")] - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ not found in this scope - | - = note: this error originates in the attribute macro `version` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/version/derive/tests/ui/ok_declare_several_vesrioned.rs b/version/derive/tests/ui/ok_declare_several_versioned.rs similarity index 76% rename from version/derive/tests/ui/ok_declare_several_vesrioned.rs rename to version/derive/tests/ui/ok_declare_several_versioned.rs index bf2b89532d7..3f9e91c5673 100644 --- a/version/derive/tests/ui/ok_declare_several_vesrioned.rs +++ b/version/derive/tests/ui/ok_declare_several_versioned.rs @@ -3,18 +3,18 @@ use parity_scale_codec::{Decode, Encode}; use serde::{Deserialize, Serialize}; declare_versioned!(VersionedMessage 1..2, Debug, Clone, iroha_macro::FromVariant); -#[version(n = 1, versioned = "VersionedMessage", derive = "Debug, Clone")] +#[version(n = 1, versioned = "VersionedMessage")] #[derive(Debug, Clone, Decode, Encode, Serialize, Deserialize)] -struct Message; +pub struct Message; impl Message { pub fn handle(&self) {} } declare_versioned!(VersionedMessage2 1..2, Debug, Clone, iroha_macro::FromVariant); -#[version(n = 1, versioned = "VersionedMessage2", derive = "Debug, Clone")] +#[version(n = 1, versioned = "VersionedMessage2")] #[derive(Debug, Clone, Decode, Encode, Serialize, Deserialize)] -struct Message2; +pub struct Message2; impl Message2 { pub fn handle(&self) {} @@ -24,14 +24,12 @@ pub fn main() { let versioned_message: VersionedMessage = Message.into(); match versioned_message { VersionedMessage::V1(message) => { - let message: Message = message.into(); message.handle(); } } let versioned_message: VersionedMessage2 = Message2.into(); match versioned_message { VersionedMessage2::V1(message) => { - let message: Message2 = message.into(); message.handle(); } } diff --git a/version/derive/tests/ui/ok_declare_versioned.rs b/version/derive/tests/ui/ok_declare_versioned.rs index ba108cdfe90..669e2acfa79 100644 --- a/version/derive/tests/ui/ok_declare_versioned.rs +++ b/version/derive/tests/ui/ok_declare_versioned.rs @@ -4,17 +4,17 @@ use serde::{Deserialize, Serialize}; declare_versioned!(VersionedMessage 1..3, Debug, Clone, iroha_macro::FromVariant); -#[version(n = 1, versioned = "VersionedMessage", derive = "Debug, Clone")] +#[version(n = 1, versioned = "VersionedMessage")] #[derive(Debug, Clone, Decode, Encode, Serialize, Deserialize)] -struct Message; +pub struct Message; impl Message { pub fn handle(&self) {} } -#[version(n = 2, versioned = "VersionedMessage", derive = "Debug, Clone")] +#[version(n = 2, versioned = "VersionedMessage")] #[derive(Debug, Clone, Decode, Encode, Serialize, Deserialize)] -struct Message2; +pub struct Message2; impl Message2 { pub fn handle(&self) { diff --git a/version/derive/tests/ui/ok_declare_versioned_json.rs b/version/derive/tests/ui/ok_declare_versioned_json.rs index aded3fa0e12..b669f08aef1 100644 --- a/version/derive/tests/ui/ok_declare_versioned_json.rs +++ b/version/derive/tests/ui/ok_declare_versioned_json.rs @@ -3,17 +3,17 @@ use serde::{Deserialize, Serialize}; declare_versioned_with_json!(VersionedMessage 1..3, Debug, Clone, iroha_macro::FromVariant); -#[version_with_json(n = 1, versioned = "VersionedMessage", derive = "Debug, Clone")] +#[version_with_json(n = 1, versioned = "VersionedMessage")] #[derive(Debug, Clone, Serialize, Deserialize)] -struct Message; +pub struct Message; impl Message { pub fn handle(&self) {} } -#[version_with_json(n = 2, versioned = "VersionedMessage", derive = "Debug, Clone")] +#[version_with_json(n = 2, versioned = "VersionedMessage")] #[derive(Debug, Clone, Serialize, Deserialize)] -struct Message2; +pub struct Message2; impl Message2 { pub fn handle(&self) { diff --git a/version/derive/tests/ui/ok_declare_versioned_scale.rs b/version/derive/tests/ui/ok_declare_versioned_scale.rs index fc14abad177..13768460ad4 100644 --- a/version/derive/tests/ui/ok_declare_versioned_scale.rs +++ b/version/derive/tests/ui/ok_declare_versioned_scale.rs @@ -3,17 +3,17 @@ use parity_scale_codec::{Decode, Encode}; declare_versioned_with_scale!(VersionedMessage 1..3, Debug, Clone, iroha_macro::FromVariant); -#[version_with_scale(n = 1, versioned = "VersionedMessage", derive = "Debug, Clone")] +#[version_with_scale(n = 1, versioned = "VersionedMessage")] #[derive(Debug, Clone, Decode, Encode)] -struct Message; +pub struct Message; impl Message { pub fn handle(&self) {} } -#[version_with_scale(n = 2, versioned = "VersionedMessage", derive = "Debug, Clone")] +#[version_with_scale(n = 2, versioned = "VersionedMessage")] #[derive(Debug, Clone, Decode, Encode)] -struct Message2; +pub struct Message2; impl Message2 { pub fn handle(&self) {