Skip to content

Commit

Permalink
Remove Frame trait
Browse files Browse the repository at this point in the history
The `Frame` trait is used solely by a single struct and its only adding
biolerplate to the code without benifits. We could consider re-adding it
in the future if needed.
  • Loading branch information
jbesraa committed Jun 18, 2024
1 parent dc9921b commit 099aa8c
Show file tree
Hide file tree
Showing 25 changed files with 35 additions and 88 deletions.
2 changes: 1 addition & 1 deletion benches/benches/src/sv2/criterion_sv2_benchmark.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use codec_sv2::{Frame, StandardEitherFrame, StandardSv2Frame};
use codec_sv2::{StandardEitherFrame, StandardSv2Frame};
use criterion::{black_box, Criterion};
use roles_logic_sv2::{
handlers::{common::ParseUpstreamCommonMessages, mining::ParseUpstreamMiningMessages},
Expand Down
2 changes: 1 addition & 1 deletion benches/benches/src/sv2/iai_sv2_benchmark.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use codec_sv2::{Frame, StandardEitherFrame, StandardSv2Frame};
use codec_sv2::{StandardEitherFrame, StandardSv2Frame};
use iai::{black_box, main};
use roles_logic_sv2::{
handlers::{common::ParseUpstreamCommonMessages, mining::ParseUpstreamMiningMessages, SendTo_},
Expand Down
2 changes: 1 addition & 1 deletion protocols/v2/codec-sv2/src/decoder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ use framing_sv2::framing2::HandShakeFrame;
#[cfg(feature = "noise_sv2")]
use framing_sv2::header::{NOISE_HEADER_ENCRYPTED_SIZE, NOISE_HEADER_SIZE};
use framing_sv2::{
framing2::{EitherFrame, Frame as F_, Sv2Frame},
framing2::{EitherFrame, Sv2Frame},
header::Header,
};
#[cfg(feature = "noise_sv2")]
Expand Down
2 changes: 1 addition & 1 deletion protocols/v2/codec-sv2/src/encoder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,9 @@ pub use const_sv2::{AEAD_MAC_LEN, SV2_FRAME_CHUNK_SIZE, SV2_FRAME_HEADER_SIZE};
#[cfg(feature = "noise_sv2")]
use core::convert::TryInto;
use core::marker::PhantomData;
use framing_sv2::framing2::Sv2Frame;
#[cfg(feature = "noise_sv2")]
use framing_sv2::framing2::{EitherFrame, HandShakeFrame};
use framing_sv2::framing2::{Frame as F_, Sv2Frame};
#[allow(unused_imports)]
pub use framing_sv2::header::NOISE_HEADER_ENCRYPTED_SIZE;

Expand Down
2 changes: 1 addition & 1 deletion protocols/v2/codec-sv2/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ pub use encoder::NoiseEncoder;

#[cfg(feature = "noise_sv2")]
pub use framing_sv2::framing2::HandShakeFrame;
pub use framing_sv2::framing2::{Frame, Sv2Frame};
pub use framing_sv2::framing2::Sv2Frame;

#[cfg(feature = "noise_sv2")]
pub use noise_sv2::{self, Initiator, NoiseCodec, Responder};
Expand Down
78 changes: 14 additions & 64 deletions protocols/v2/framing-sv2/src/framing2.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
#![allow(dead_code)]
use crate::{
header::{Header, NOISE_HEADER_LEN_OFFSET, NOISE_HEADER_SIZE},
Error,
Expand Down Expand Up @@ -29,51 +30,6 @@ impl<A, B> Sv2Frame<A, B> {
}
}

pub trait Frame<'a, T: Serialize + GetSize>: Sized {
type Buffer: AsMut<[u8]>;
type Deserialized;

/// Write the serialized `Frame` into `dst`.
fn serialize(self, dst: &mut [u8]) -> Result<(), Error>;

/// Get the payload
fn payload(&'a mut self) -> &'a mut [u8];

/// Returns `Some(self.header)` when the frame has a header (`Sv2Frame`), returns `None` where it doesn't (`HandShakeFrame`).
fn get_header(&self) -> Option<crate::header::Header>;

/// Try to build a `Frame` from raw bytes.
/// Checks if the payload has the correct size (as stated in the `Header`).
/// Returns `Self` on success, or the number of the bytes needed to complete the frame
/// as an error. Nothing is assumed or checked about the correctness of the payload.
fn from_bytes(bytes: Self::Buffer) -> Result<Self, isize>;

/// Builds a `Frame` from raw bytes.
/// Does not check if the payload has the correct size (as stated in the `Header`).
/// Nothing is assumed or checked about the correctness of the payload.
fn from_bytes_unchecked(bytes: Self::Buffer) -> Self;

/// Helps to determine if the frame size encoded in a byte array correctly representing the size of the frame.
/// - Returns `0` if the byte slice is of the expected size according to the header.
/// - Returns a negative value if the byte slice is smaller than a Noise Frame header; this value
/// represents how many bytes are missing.
/// - Returns a positive value if the byte slice is longer than expected; this value
/// indicates the surplus of bytes beyond the expected size.
fn size_hint(bytes: &[u8]) -> isize;

/// Returns the size of the `Frame` payload.
fn encoded_length(&self) -> usize;

/// Try to build a `Frame` from a serializable payload.
/// Returns `Some(Self)` if the size of the payload fits in the frame, `None` otherwise.
fn from_message(
message: T,
message_type: u8,
extension_type: u16,
channel_msg: bool,
) -> Option<Self>;
}

/// Abstraction for a SV2 Frame.
#[derive(Debug, Clone)]
pub struct Sv2Frame<T, B> {
Expand All @@ -98,15 +54,12 @@ impl HandShakeFrame {
}
}

impl<'a, T: Serialize + GetSize, B: AsMut<[u8]> + AsRef<[u8]>> Frame<'a, T> for Sv2Frame<T, B> {
type Buffer = B;
type Deserialized = B;

impl<T: Serialize + GetSize, B: AsMut<[u8]> + AsRef<[u8]>> Sv2Frame<T, B> {
/// Write the serialized `Sv2Frame` into `dst`.
/// This operation when called on an already serialized frame is very cheap.
/// When called on a non serialized frame, it is not so cheap (because it serializes it).
#[inline]
fn serialize(self, dst: &mut [u8]) -> Result<(), Error> {
pub fn serialize(self, dst: &mut [u8]) -> Result<(), Error> {
if let Some(mut serialized) = self.serialized {
dst.swap_with_slice(serialized.as_mut());
Ok(())
Expand All @@ -132,7 +85,7 @@ impl<'a, T: Serialize + GetSize, B: AsMut<[u8]> + AsRef<[u8]>> Frame<'a, T> for
/// This function is only intended as a fast way to get a reference to an
/// already serialized payload. If the frame has not yet been
/// serialized, this function should never be used (it will panic).
fn payload(&'a mut self) -> &'a mut [u8] {
pub fn payload(&mut self) -> &mut [u8] {
if let Some(serialized) = self.serialized.as_mut() {
&mut serialized.as_mut()[Header::SIZE..]
} else {
Expand All @@ -142,15 +95,15 @@ impl<'a, T: Serialize + GetSize, B: AsMut<[u8]> + AsRef<[u8]>> Frame<'a, T> for
}

/// `Sv2Frame` always returns `Some(self.header)`.
fn get_header(&self) -> Option<crate::header::Header> {
pub fn get_header(&self) -> Option<crate::header::Header> {
Some(self.header)
}

/// Tries to build a `Sv2Frame` from raw bytes, assuming they represent a serialized `Sv2Frame` frame (`Self.serialized`).
/// Returns a `Sv2Frame` on success, or the number of the bytes needed to complete the frame
/// as an error. `Self.serialized` is `Some`, but nothing is assumed or checked about the correctness of the payload.
#[inline]
fn from_bytes(mut bytes: Self::Buffer) -> Result<Self, isize> {
fn from_bytes(mut bytes: B) -> Result<Self, isize> {
let hint = Self::size_hint(bytes.as_mut());

if hint == 0 {
Expand All @@ -161,7 +114,7 @@ impl<'a, T: Serialize + GetSize, B: AsMut<[u8]> + AsRef<[u8]>> Frame<'a, T> for
}

#[inline]
fn from_bytes_unchecked(mut bytes: Self::Buffer) -> Self {
pub fn from_bytes_unchecked(mut bytes: B) -> Self {
// Unchecked function caller is supposed to already know that the passed bytes are valid
let header = Header::from_bytes(bytes.as_mut()).expect("Invalid header");
Self {
Expand All @@ -179,7 +132,7 @@ impl<'a, T: Serialize + GetSize, B: AsMut<[u8]> + AsRef<[u8]>> Frame<'a, T> for
/// - Returns a positive value if the byte slice is longer than expected; this value
/// indicates the surplus of bytes beyond the expected size.
#[inline]
fn size_hint(bytes: &[u8]) -> isize {
pub fn size_hint(bytes: &[u8]) -> isize {
match Header::from_bytes(bytes) {
Err(_) => {
// Returns how many bytes are missing from the expected frame size
Expand All @@ -200,7 +153,7 @@ impl<'a, T: Serialize + GetSize, B: AsMut<[u8]> + AsRef<[u8]>> Frame<'a, T> for
/// If `Sv2Frame` is serialized, returns the length of `self.serialized`,
/// otherwise, returns the length of `self.payload`.
#[inline]
fn encoded_length(&self) -> usize {
pub fn encoded_length(&self) -> usize {
if let Some(serialized) = self.serialized.as_ref() {
serialized.as_ref().len()
} else if let Some(payload) = self.payload.as_ref() {
Expand All @@ -213,7 +166,7 @@ impl<'a, T: Serialize + GetSize, B: AsMut<[u8]> + AsRef<[u8]>> Frame<'a, T> for

/// Tries to build a `Sv2Frame` from a non-serialized payload.
/// Returns a `Sv2Frame` if the size of the payload fits in the frame, `None` otherwise.
fn from_message(
pub fn from_message(
message: T,
message_type: u8,
extension_type: u16,
Expand All @@ -229,10 +182,7 @@ impl<'a, T: Serialize + GetSize, B: AsMut<[u8]> + AsRef<[u8]>> Frame<'a, T> for
}
}

impl<'a> Frame<'a, Slice> for HandShakeFrame {
type Buffer = Slice;
type Deserialized = &'a mut [u8];

impl HandShakeFrame {
/// Put the Noise Frame payload into `dst`
#[inline]
fn serialize(mut self, dst: &mut [u8]) -> Result<(), Error> {
Expand All @@ -242,7 +192,7 @@ impl<'a> Frame<'a, Slice> for HandShakeFrame {

/// Get the Noise Frame payload
#[inline]
fn payload(&'a mut self) -> &'a mut [u8] {
fn payload(&mut self) -> &mut [u8] {
&mut self.payload[NOISE_HEADER_SIZE..]
}

Expand All @@ -252,12 +202,12 @@ impl<'a> Frame<'a, Slice> for HandShakeFrame {
}

/// Builds a `HandShakeFrame` from raw bytes. Nothing is assumed or checked about the correctness of the payload.
fn from_bytes(bytes: Self::Buffer) -> Result<Self, isize> {
pub fn from_bytes(bytes: Slice) -> Result<Self, isize> {
Ok(Self::from_bytes_unchecked(bytes))
}

#[inline]
fn from_bytes_unchecked(bytes: Self::Buffer) -> Self {
pub fn from_bytes_unchecked(bytes: Slice) -> Self {
Self { payload: bytes }
}

Expand Down
2 changes: 1 addition & 1 deletion protocols/v2/roles-logic-sv2/src/parsers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ use binary_sv2::GetSize;

use binary_sv2::{from_bytes, Deserialize};

use framing_sv2::framing2::{Frame, Sv2Frame};
use framing_sv2::framing2::Sv2Frame;

use const_sv2::{
CHANNEL_BIT_ALLOCATE_MINING_JOB_TOKEN, CHANNEL_BIT_ALLOCATE_MINING_JOB_TOKEN_SUCCESS,
Expand Down
2 changes: 1 addition & 1 deletion protocols/v2/sv2-ffi/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use std::{
fmt::{Display, Formatter},
};

use codec_sv2::{Encoder, Frame, StandardDecoder, StandardSv2Frame};
use codec_sv2::{Encoder, StandardDecoder, StandardSv2Frame};
use common_messages_sv2::{
CSetupConnection, CSetupConnectionError, ChannelEndpointChanged, SetupConnection,
SetupConnectionError, SetupConnectionSuccess,
Expand Down
2 changes: 1 addition & 1 deletion roles/jd-client/src/lib/downstream.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ use roles_logic_sv2::{
};
use tracing::{debug, error, info, warn};

use codec_sv2::{Frame, HandshakeRole, Responder, StandardEitherFrame, StandardSv2Frame};
use codec_sv2::{HandshakeRole, Responder, StandardEitherFrame, StandardSv2Frame};
use key_utils::{Secp256k1PublicKey, Secp256k1SecretKey};

use stratum_common::bitcoin::{consensus::Decodable, TxOut};
Expand Down
1 change: 0 additions & 1 deletion roles/jd-client/src/lib/job_declarator/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ use tokio::task::AbortHandle;
use tracing::{error, info};

use async_recursion::async_recursion;
use codec_sv2::Frame;
use nohash_hasher::BuildNoHashHasher;
use roles_logic_sv2::{
handlers::job_declaration::ParseServerJobDeclarationMessages,
Expand Down
2 changes: 1 addition & 1 deletion roles/jd-client/src/lib/job_declarator/setup_connection.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use async_channel::{Receiver, Sender};
use codec_sv2::{Frame, StandardEitherFrame, StandardSv2Frame};
use codec_sv2::{StandardEitherFrame, StandardSv2Frame};
use roles_logic_sv2::{
common_messages_sv2::{Protocol, SetupConnection},
handlers::common::{ParseUpstreamCommonMessages, SendTo},
Expand Down
2 changes: 1 addition & 1 deletion roles/jd-client/src/lib/template_receiver/mod.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use super::{job_declarator::JobDeclarator, status, PoolChangerTrigger};
use async_channel::{Receiver, Sender};
use codec_sv2::{Frame, HandshakeRole, Initiator, StandardEitherFrame, StandardSv2Frame};
use codec_sv2::{HandshakeRole, Initiator, StandardEitherFrame, StandardSv2Frame};
use error_handling::handle_result;
use key_utils::Secp256k1PublicKey;
use network_helpers_sv2::noise_connection_tokio::Connection;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use async_channel::{Receiver, Sender};
use codec_sv2::{Frame, StandardEitherFrame, StandardSv2Frame};
use codec_sv2::{StandardEitherFrame, StandardSv2Frame};
use roles_logic_sv2::{
common_messages_sv2::{Protocol, SetupConnection},
handlers::common::{ParseUpstreamCommonMessages, SendTo},
Expand Down
2 changes: 1 addition & 1 deletion roles/jd-client/src/lib/upstream_sv2/upstream.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ use super::super::{
};
use async_channel::{Receiver, Sender};
use binary_sv2::{Seq0255, U256};
use codec_sv2::{Frame, HandshakeRole, Initiator};
use codec_sv2::{HandshakeRole, Initiator};
use error_handling::handle_result;
use key_utils::Secp256k1PublicKey;
use network_helpers_sv2::noise_connection_tokio::Connection;
Expand Down
2 changes: 1 addition & 1 deletion roles/jd-server/src/lib/job_declarator/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ pub mod message_handler;
use super::{error::JdsError, mempool::JDsMempool, status, Configuration, EitherFrame, StdFrame};
use async_channel::{Receiver, Sender};
use binary_sv2::{B0255, U256};
use codec_sv2::{Frame, HandshakeRole, Responder};
use codec_sv2::{HandshakeRole, Responder};
use error_handling::handle_result;
use key_utils::{Secp256k1PublicKey, Secp256k1SecretKey, SignatureService};
use network_helpers_sv2::noise_connection_tokio::Connection;
Expand Down
2 changes: 1 addition & 1 deletion roles/mining-proxy/src/lib/downstream_mining.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ use roles_logic_sv2::{
};
use tracing::info;

use codec_sv2::{Frame, StandardEitherFrame, StandardSv2Frame};
use codec_sv2::{StandardEitherFrame, StandardSv2Frame};

pub type Message = MiningDeviceMessages<'static>;
pub type StdFrame = StandardSv2Frame<Message>;
Expand Down
2 changes: 1 addition & 1 deletion roles/mining-proxy/src/lib/upstream_mining.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use roles_logic_sv2::utils::Id;
use super::downstream_mining::{Channel, DownstreamMiningNode, StdFrame as DownstreamFrame};
use async_channel::{Receiver, SendError, Sender};
use async_recursion::async_recursion;
use codec_sv2::{Frame, HandshakeRole, Initiator, StandardEitherFrame, StandardSv2Frame};
use codec_sv2::{HandshakeRole, Initiator, StandardEitherFrame, StandardSv2Frame};
use network_helpers_sv2::noise_connection_tokio::Connection;
use nohash_hasher::BuildNoHashHasher;
use roles_logic_sv2::{
Expand Down
2 changes: 1 addition & 1 deletion roles/pool/src/lib/mining_pool/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use super::{
};
use async_channel::{Receiver, Sender};
use binary_sv2::U256;
use codec_sv2::{Frame, HandshakeRole, Responder, StandardEitherFrame, StandardSv2Frame};
use codec_sv2::{HandshakeRole, Responder, StandardEitherFrame, StandardSv2Frame};
use error_handling::handle_result;
use key_utils::{Secp256k1PublicKey, Secp256k1SecretKey, SignatureService};
use network_helpers_sv2::noise_connection_tokio::Connection;
Expand Down
1 change: 0 additions & 1 deletion roles/pool/src/lib/mining_pool/setup_connection.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ use super::super::{
mining_pool::{EitherFrame, StdFrame},
};
use async_channel::{Receiver, Sender};
use codec_sv2::Frame;
use roles_logic_sv2::{
common_messages_sv2::{
has_requires_std_job, has_version_rolling, has_work_selection, SetupConnection,
Expand Down
2 changes: 1 addition & 1 deletion roles/pool/src/lib/template_receiver/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use super::{
status,
};
use async_channel::{Receiver, Sender};
use codec_sv2::{Frame, HandshakeRole, Initiator};
use codec_sv2::{HandshakeRole, Initiator};
use error_handling::handle_result;
use key_utils::Secp256k1PublicKey;
use network_helpers_sv2::noise_connection_tokio::Connection;
Expand Down
1 change: 0 additions & 1 deletion roles/pool/src/lib/template_receiver/setup_connection.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ use super::super::{
mining_pool::{EitherFrame, StdFrame},
};
use async_channel::{Receiver, Sender};
use codec_sv2::Frame;
use roles_logic_sv2::{
common_messages_sv2::{Protocol, SetupConnection},
errors::Error,
Expand Down
2 changes: 1 addition & 1 deletion roles/test-utils/mining-device/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@ async fn main() {

use async_channel::{Receiver, Sender};
use binary_sv2::u256_from_int;
use codec_sv2::{Frame, Initiator, StandardEitherFrame, StandardSv2Frame};
use codec_sv2::{Initiator, StandardEitherFrame, StandardSv2Frame};
use roles_logic_sv2::{
common_messages_sv2::{Protocol, SetupConnection, SetupConnectionSuccess},
common_properties::{IsMiningUpstream, IsUpstream},
Expand Down
2 changes: 1 addition & 1 deletion roles/translator/src/lib/upstream_sv2/upstream.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ use crate::{
use async_channel::{Receiver, Sender};
use async_std::{net::TcpStream, task};
use binary_sv2::u256_from_int;
use codec_sv2::{Frame, HandshakeRole, Initiator};
use codec_sv2::{HandshakeRole, Initiator};
use error_handling::handle_result;
use key_utils::Secp256k1PublicKey;
use network_helpers_sv2::Connection;
Expand Down
2 changes: 1 addition & 1 deletion utils/message-generator/src/executor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use crate::{
};
use async_channel::{Receiver, Sender};
use binary_sv2::Serialize;
use codec_sv2::{Frame, StandardEitherFrame as EitherFrame, Sv2Frame};
use codec_sv2::{StandardEitherFrame as EitherFrame, Sv2Frame};
use roles_logic_sv2::parsers::{self, AnyMessage};
use std::{collections::HashMap, convert::TryInto, sync::Arc};

Expand Down
2 changes: 1 addition & 1 deletion utils/message-generator/src/parser/frames.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use super::sv2_messages::{message_from_path, ReplaceField};
use codec_sv2::{buffer_sv2::Slice, Frame as _Frame, Sv2Frame};
use codec_sv2::{buffer_sv2::Slice, Sv2Frame};
use roles_logic_sv2::parsers::AnyMessage;
use serde_json::{Map, Value};
use std::{collections::HashMap, convert::TryInto};
Expand Down

0 comments on commit 099aa8c

Please sign in to comment.