Skip to content

Commit

Permalink
[feature] #1675: use type instead of wrapper struct for versioned ite…
Browse files Browse the repository at this point in the history
…ms (#1665)

* use type instead of wrapper struct for inner versioned items

Signed-off-by: Marin Veršić <marin.versic101@gmail.com>

* rename unwrap methods on versioned structures

Signed-off-by: Marin Veršić <marin.versic101@gmail.com>

Co-authored-by: Aleksandr Petrosyan <a-p-petrosyan@yandex.ru>
  • Loading branch information
mversic and appetrosyan committed Dec 6, 2021
1 parent aad012a commit cd16272
Show file tree
Hide file tree
Showing 25 changed files with 222 additions and 457 deletions.
23 changes: 9 additions & 14 deletions client/src/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down Expand Up @@ -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| {
Expand All @@ -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: {}, {}",
Expand Down Expand Up @@ -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;
}
Expand All @@ -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 {
Expand Down
87 changes: 40 additions & 47 deletions core/src/block.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}

Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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.
Expand All @@ -382,47 +382,46 @@ impl VersionedValidBlock {
is_instruction_allowed: &IsInstructionAllowedBoxed<W>,
is_query_allowed: &IsQueryAllowedBoxed<W>,
) -> 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> {
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<VersionedValidBlock> {
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<Item = &'_ SignatureOf<VersionedValidBlock>> + '_ {
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<W: WorldTrait>(&self, wsv: &WorldStateView<W>) -> 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
Expand All @@ -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
Expand Down Expand Up @@ -510,7 +505,7 @@ impl ValidBlock {
.collect(),
}
.validate(wsv, is_instruction_allowed, is_query_allowed)
.into_inner_v1()
.into_v1()
}
}

Expand Down Expand Up @@ -583,7 +578,7 @@ impl ValidBlock {

impl From<&VersionedValidBlock> for Vec<Event> {
fn from(block: &VersionedValidBlock) -> Self {
block.as_inner_v1().into()
block.as_v1().into()
}
}

Expand Down Expand Up @@ -630,41 +625,41 @@ impl From<&ValidBlock> for Vec<Event> {
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> {
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<Item = &'_ SignatureOf<Self>> + '_ {
self.as_inner_v1()
self.as_v1()
.verified_signatures()
.map(SignatureOf::transmute_ref)
}
Expand Down Expand Up @@ -724,14 +719,14 @@ impl From<CommittedBlock> for ValidBlock {
impl From<VersionedCommittedBlock> 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<Event> {
#[inline]
fn from(block: &VersionedCommittedBlock) -> Self {
block.as_inner_v1().into()
block.as_v1().into()
}
}

Expand All @@ -744,9 +739,7 @@ impl From<&CommittedBlock> for Vec<Event> {
.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()
Expand Down
20 changes: 10 additions & 10 deletions core/src/block_sync.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
}
}
}
Expand Down Expand Up @@ -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`.
Expand Down
4 changes: 2 additions & 2 deletions core/src/event.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down Expand Up @@ -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(())
Expand Down
8 changes: 4 additions & 4 deletions core/src/queue.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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);
}
Expand Down
Loading

0 comments on commit cd16272

Please sign in to comment.