From 0afcde241b039c227e2f280a7b8d6e059e4cc924 Mon Sep 17 00:00:00 2001 From: bit-aloo Date: Wed, 11 Mar 2026 19:43:07 +0530 Subject: [PATCH] remove lifetime from binary-sv2 --- .../stratum-translation/src/sv1_to_sv2.rs | 8 +- .../stratum-translation/src/sv2_to_sv1.rs | 10 +- sv1/examples/client_and_server.rs | 64 ++-- sv1/src/error.rs | 18 +- sv1/src/lib.rs | 94 ++--- sv1/src/methods/client_to_server.rs | 32 +- sv1/src/methods/mod.rs | 64 ++-- sv1/src/methods/server_to_client.rs | 34 +- sv1/src/utils.rs | 102 +++--- sv2/binary-sv2/derive_codec/src/lib.rs | 16 +- sv2/binary-sv2/src/codec/decodable.rs | 44 +-- sv2/binary-sv2/src/codec/encodable.rs | 32 +- sv2/binary-sv2/src/codec/impls.rs | 308 ++++++++-------- .../src/datatypes/copy_data_types.rs | 12 +- sv2/binary-sv2/src/datatypes/mod.rs | 10 +- .../datatypes/non_copy_data_types/inner.rs | 133 +++---- .../src/datatypes/non_copy_data_types/mod.rs | 74 ++-- .../non_copy_data_types/seq_inner.rs | 147 ++++---- sv2/binary-sv2/src/lib.rs | 8 +- sv2/binary-sv2/tests/test.rs | 84 ++--- sv2/channels-sv2/src/chain_tip.rs | 10 +- sv2/channels-sv2/src/client/extended.rs | 28 +- sv2/channels-sv2/src/client/group.rs | 16 +- sv2/channels-sv2/src/client/standard.rs | 28 +- sv2/channels-sv2/src/server/extended.rs | 26 +- sv2/channels-sv2/src/server/group.rs | 20 +- sv2/channels-sv2/src/server/jobs/extended.rs | 28 +- sv2/channels-sv2/src/server/jobs/factory.rs | 38 +- sv2/channels-sv2/src/server/jobs/mod.rs | 6 +- sv2/channels-sv2/src/server/jobs/standard.rs | 20 +- sv2/channels-sv2/src/server/standard.rs | 26 +- sv2/channels-sv2/src/target.rs | 4 +- sv2/codec-sv2/src/decoder.rs | 2 +- .../src/extensions_negotiation.rs | 20 +- sv2/handlers-sv2/src/common.rs | 16 +- sv2/handlers-sv2/src/extensions.rs | 16 +- sv2/handlers-sv2/src/job_declaration.rs | 16 +- sv2/handlers-sv2/src/mining.rs | 8 +- sv2/handlers-sv2/src/template_distribution.rs | 16 +- sv2/parsers-sv2/src/lib.rs | 346 +++++++++--------- .../common-messages/src/reconnect.rs | 8 +- .../common-messages/src/setup_connection.rs | 30 +- .../src/allocate_mining_job_token.rs | 14 +- .../job-declaration/src/declare_mining_job.rs | 28 +- .../src/provide_missing_transactions.rs | 12 +- .../job-declaration/src/push_solution.rs | 8 +- sv2/subprotocols/mining/src/close_channel.rs | 6 +- sv2/subprotocols/mining/src/lib.rs | 20 +- sv2/subprotocols/mining/src/new_mining_job.rs | 24 +- sv2/subprotocols/mining/src/open_channel.rs | 50 +-- .../mining/src/set_custom_mining_job.rs | 20 +- .../mining/src/set_extranonce_prefix.rs | 6 +- .../mining/src/set_group_channel.rs | 6 +- .../mining/src/set_new_prev_hash.rs | 6 +- sv2/subprotocols/mining/src/set_target.rs | 6 +- sv2/subprotocols/mining/src/submit_shares.rs | 14 +- sv2/subprotocols/mining/src/update_channel.rs | 12 +- .../template-distribution/src/new_template.rs | 14 +- .../src/request_transaction_data.rs | 14 +- .../src/set_new_prev_hash.rs | 8 +- .../src/submit_solution.rs | 6 +- 61 files changed, 1113 insertions(+), 1183 deletions(-) diff --git a/stratum-core/stratum-translation/src/sv1_to_sv2.rs b/stratum-core/stratum-translation/src/sv1_to_sv2.rs index 767b40cddd..a16fb90d2a 100644 --- a/stratum-core/stratum-translation/src/sv1_to_sv2.rs +++ b/stratum-core/stratum-translation/src/sv1_to_sv2.rs @@ -21,7 +21,7 @@ pub fn build_sv2_open_extended_mining_channel( nominal_hash_rate: f32, max_target: Target, min_extranonce_size: u16, -) -> Result> { +) -> Result { Ok(OpenExtendedMiningChannel { request_id, user_identity: user_identity @@ -48,12 +48,12 @@ pub fn build_sv2_open_extended_mining_channel( /// * `Ok(SubmitSharesExtended)` if the conversion is successful. /// * `Err(())` if any required field is missing or conversion fails. pub fn build_sv2_submit_shares_extended_from_sv1_submit( - submit: &client_to_server::Submit<'_>, + submit: &client_to_server::Submit, channel_id: u32, sequence_number: u32, job_version: u32, version_rolling_mask: Option, -) -> Result> { +) -> Result { let version = match (submit.version_bits.clone(), version_rolling_mask) { (Some(version_bits), Some(rolling_mask)) => { (job_version & !rolling_mask.0) | (version_bits.0 & rolling_mask.0) @@ -85,7 +85,7 @@ mod tests { use super::*; use v1::{client_to_server::Submit, utils::HexU32Be}; - fn submit_template() -> Submit<'static> { + fn submit_template() -> Submit { Submit { user_name: "w".to_string(), job_id: "1".to_string(), diff --git a/stratum-core/stratum-translation/src/sv2_to_sv1.rs b/stratum-core/stratum-translation/src/sv2_to_sv1.rs index 849a834791..d9f8a2ecea 100644 --- a/stratum-core/stratum-translation/src/sv2_to_sv1.rs +++ b/stratum-core/stratum-translation/src/sv2_to_sv1.rs @@ -31,17 +31,17 @@ use v1::{ /// block is found). /// /// # Returns -/// * `Ok(server_to_client::Notify<'static>)` - The constructed SV1 mining.notify message. +/// * `Ok(server_to_client::Notify)` - The constructed SV1 mining.notify message. /// * `Err(StratumTranslationError)` - If BIP141 stripping or serialization fails. /// /// # Errors /// * `FailedToTryToStripBip141` - When BIP141 data stripping fails /// * `FailedToSerializeToB064K` - When serializing stripped data to B064K format fails pub fn build_sv1_notify_from_sv2( - new_prev_hash: SetNewPrevHash<'static>, - new_job: NewExtendedMiningJob<'static>, + new_prev_hash: SetNewPrevHash, + new_job: NewExtendedMiningJob, clean_jobs: bool, -) -> Result> { +) -> Result { let new_job = match try_strip_bip141( new_job.coinbase_tx_prefix.inner_as_ref(), new_job.coinbase_tx_suffix.inner_as_ref(), @@ -99,7 +99,7 @@ pub fn build_sv1_notify_from_sv2( /// # Returns /// * `Ok(json_rpc::Message)` - The constructed SV1 mining.set_difficulty message. pub fn build_sv1_set_difficulty_from_sv2_set_target( - set_target: SetTarget<'_>, + set_target: SetTarget, ) -> Result { build_sv1_set_difficulty_from_sv2_target(Target::from_le_bytes( set_target diff --git a/sv1/examples/client_and_server.rs b/sv1/examples/client_and_server.rs index 45b1dd2351..b41bc4e8ff 100644 --- a/sv1/examples/client_and_server.rs +++ b/sv1/examples/client_and_server.rs @@ -22,16 +22,16 @@ use sv1_api::{ ClientStatus, IsClient, IsServer, Message, }; -fn new_extranonce<'a>() -> Extranonce<'a> { +fn new_extranonce() -> Extranonce { extranonce_from_hex("08000002") } -fn extranonce_from_hex<'a>(hex: &str) -> Extranonce<'a> { +fn extranonce_from_hex(hex: &str) -> Extranonce { let data = utils::decode_hex(hex).unwrap(); Extranonce::try_from(data).expect("Failed to convert hex to U256") } -fn merklenode_from_hex<'a>(hex: &str) -> MerkleNode<'a> { +fn merklenode_from_hex(hex: &str) -> MerkleNode { let data = utils::decode_hex(hex).unwrap(); let len = data.len(); if hex.len() >= 64 { @@ -46,7 +46,7 @@ fn merklenode_from_hex<'a>(hex: &str) -> MerkleNode<'a> { } } -fn prevhash_from_hex<'a>(hex: &str) -> PrevHash<'a> { +fn prevhash_from_hex(hex: &str) -> PrevHash { let data = utils::decode_hex(hex).unwrap(); let len = data.len(); if hex.len() >= 64 { @@ -72,9 +72,9 @@ fn new_version_rolling_min() -> HexU32Be { HexU32Be(0x00000000) } -struct Server<'a> { +struct Server { authorized_names: Vec, - extranonce1: Extranonce<'a>, + extranonce1: Extranonce, extranonce2_size: usize, version_rolling_mask: Option, version_rolling_min_bit: Option, @@ -98,8 +98,8 @@ fn server_pool_listen(listener: TcpListener) { } } -impl Server<'_> { - pub fn new(stream: TcpStream) -> Arc>> { +impl Server { + pub fn new(stream: TcpStream) -> Arc> { let (sender_incoming, receiver_incoming) = mpsc::channel::(); let (sender_outgoing, receiver_outgoing) = mpsc::channel::(); @@ -184,7 +184,7 @@ impl Server<'_> { fn handle_message( &mut self, _message: json_rpc::Message, - ) -> Result, Error<'static>> { + ) -> Result, Error> { Ok(None) } @@ -194,7 +194,7 @@ impl Server<'_> { } } -impl<'a> IsServer<'a> for Server<'a> { +impl IsServer for Server { fn handle_configure( &mut self, _client_id: Option, @@ -253,13 +253,13 @@ impl<'a> IsServer<'a> for Server<'a> { fn set_extranonce1( &mut self, _client_id: Option, - extranonce1: Option>, - ) -> Extranonce<'a> { + extranonce1: Option, + ) -> Extranonce { self.extranonce1 = extranonce1.unwrap_or_else(new_extranonce); self.extranonce1.clone() } - fn extranonce1(&self, _client_id: Option) -> Extranonce<'a> { + fn extranonce1(&self, _client_id: Option) -> Extranonce { self.extranonce1.clone() } @@ -289,7 +289,7 @@ impl<'a> IsServer<'a> for Server<'a> { self.version_rolling_min_bit = mask } - fn notify(&mut self, _client_id: Option) -> Result> { + fn notify(&mut self, _client_id: Option) -> Result { let hex = "ffff"; Ok(server_to_client::Notify { job_id: "ciao".to_string(), @@ -306,22 +306,22 @@ impl<'a> IsServer<'a> for Server<'a> { } } -struct Client<'a> { +struct Client { client_id: u32, - extranonce1: Extranonce<'a>, + extranonce1: Extranonce, extranonce2_size: usize, version_rolling_mask: Option, version_rolling_min_bit: Option, status: ClientStatus, - last_notify: Option>, + last_notify: Option, sented_authorize_request: Vec<(u64, String)>, // (id, user_name) authorized: Vec, receiver_incoming: Receiver, sender_outgoing: Sender, } -impl Client<'static> { - pub fn new(client_id: u32, socket: SocketAddr) -> Arc>> { +impl Client { + pub fn new(client_id: u32, socket: SocketAddr) -> Arc> { loop { thread::sleep(Duration::from_secs(1)); match TcpStream::connect(socket) { @@ -450,12 +450,12 @@ impl Client<'static> { } } -impl<'a> IsClient<'a> for Client<'a> { +impl IsClient for Client { fn handle_set_difficulty( &mut self, _server_id: Option, _conf: &mut server_to_client::SetDifficulty, - ) -> Result<(), Error<'a>> { + ) -> Result<(), Error> { Ok(()) } @@ -463,7 +463,7 @@ impl<'a> IsClient<'a> for Client<'a> { &mut self, _server_id: Option, _conf: &mut server_to_client::SetExtranonce, - ) -> Result<(), Error<'a>> { + ) -> Result<(), Error> { Ok(()) } @@ -471,15 +471,15 @@ impl<'a> IsClient<'a> for Client<'a> { &mut self, _server_id: Option, _conf: &mut server_to_client::SetVersionMask, - ) -> Result<(), Error<'a>> { + ) -> Result<(), Error> { Ok(()) } fn handle_notify( &mut self, _server_id: Option, - notify: server_to_client::Notify<'a>, - ) -> Result<(), Error<'a>> { + notify: server_to_client::Notify, + ) -> Result<(), Error> { self.last_notify = Some(notify); Ok(()) } @@ -488,23 +488,23 @@ impl<'a> IsClient<'a> for Client<'a> { &mut self, _server_id: Option, _conf: &mut server_to_client::Configure, - ) -> Result<(), Error<'a>> { + ) -> Result<(), Error> { Ok(()) } fn handle_subscribe( &mut self, _server_id: Option, - _subscribe: &server_to_client::Subscribe<'a>, - ) -> Result<(), Error<'a>> { + _subscribe: &server_to_client::Subscribe, + ) -> Result<(), Error> { Ok(()) } - fn set_extranonce1(&mut self, _server_id: Option, extranonce1: Extranonce<'a>) { + fn set_extranonce1(&mut self, _server_id: Option, extranonce1: Extranonce) { self.extranonce1 = extranonce1; } - fn extranonce1(&self, _server_id: Option) -> Extranonce<'a> { + fn extranonce1(&self, _server_id: Option) -> Extranonce { self.extranonce1.clone() } @@ -592,13 +592,13 @@ impl<'a> IsClient<'a> for Client<'a> { &mut self, _server_id: Option, message: Message, - ) -> Result, Error<'a>> { + ) -> Result, Error> { println!("{message:?}"); Ok(None) } } -fn initialize_client(client: Arc>>) { +fn initialize_client(client: Arc>) { loop { { let mut client_ = client.lock().unwrap(); diff --git a/sv1/src/error.rs b/sv1/src/error.rs index b37ed0d778..b6bab0ff95 100644 --- a/sv1/src/error.rs +++ b/sv1/src/error.rs @@ -5,7 +5,7 @@ use crate::{ #[derive(Debug)] #[non_exhaustive] -pub enum Error<'a> { +pub enum Error { BadBytesConvert(binary_sv2::Error), BTCHashError(bitcoin_hashes::Error), /// Errors on bad hex decode/encode. @@ -22,11 +22,11 @@ pub enum Error<'a> { /// Errors if the client receives an invalid message that was intended to be sent from the /// client to the server, NOT from the server to the client. #[allow(clippy::upper_case_acronyms)] - InvalidReceiver(Box>), + InvalidReceiver(Box), /// Errors if server receives and invalid `mining.submit` from the client. InvalidSubmission, /// Errors encountered during conversion between valid `json_rpc` messages and SV1 messages. - Method(Box>), + Method(Box), /// Errors if action is attempted that requires the client to be authorized, but it is /// unauthorized. The client username is given in the error message. UnauthorizedClient(String), @@ -37,7 +37,7 @@ pub enum Error<'a> { UnexpectedMessage(String), } -impl std::fmt::Display for Error<'_> { +impl std::fmt::Display for Error { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { match self { Error::BadBytesConvert(ref e) => write!( @@ -80,25 +80,25 @@ impl std::fmt::Display for Error<'_> { } } -impl From for Error<'_> { +impl From for Error { fn from(e: bitcoin_hashes::Error) -> Self { Error::BTCHashError(e) } } -impl From for Error<'_> { +impl From for Error { fn from(e: std::convert::Infallible) -> Self { Error::Infallible(e) } } -impl<'a> From> for Error<'a> { - fn from(inner: MethodError<'a>) -> Self { +impl From for Error { + fn from(inner: MethodError) -> Self { Error::Method(Box::new(inner)) } } -impl From for Error<'_> { +impl From for Error { fn from(inner: binary_sv2::Error) -> Self { Error::BadBytesConvert(inner) } diff --git a/sv1/src/lib.rs b/sv1/src/lib.rs index a786946a5b..8f87eadf2d 100644 --- a/sv1/src/lib.rs +++ b/sv1/src/lib.rs @@ -57,14 +57,14 @@ use utils::{Extranonce, HexU32Be}; /// TODO: Should update to accommodate miner requesting a difficulty change /// /// A stratum v1 server represent a single connection with a client -pub trait IsServer<'a> { +pub trait IsServer { /// handle the received message and return a response if the message is a request or /// notification. fn handle_message( &mut self, client_id: Option, msg: json_rpc::Message, - ) -> Result, Error<'a>> + ) -> Result, Error> where Self: std::marker::Sized, { @@ -89,7 +89,7 @@ pub trait IsServer<'a> { &mut self, client_id: Option, msg: json_rpc::Message, - ) -> Result, Error<'a>> + ) -> Result, Error> where Self: std::marker::Sized, { @@ -203,7 +203,7 @@ pub trait IsServer<'a> { fn handle_submit( &self, client_id: Option, - request: &client_to_server::Submit<'a>, + request: &client_to_server::Submit, ) -> bool; /// Indicates to the server that the client supports the mining.set_extranonce method. @@ -217,10 +217,10 @@ pub trait IsServer<'a> { fn set_extranonce1( &mut self, client_id: Option, - extranonce1: Option>, - ) -> Extranonce<'a>; + extranonce1: Option, + ) -> Extranonce; - fn extranonce1(&self, client_id: Option) -> Extranonce<'a>; + fn extranonce1(&self, client_id: Option) -> Extranonce; /// Set extranonce2_size to extranonce2_size if provided. If not create a new one and set it. fn set_extranonce2_size( @@ -240,9 +240,9 @@ pub trait IsServer<'a> { fn update_extranonce( &mut self, client_id: Option, - extra_nonce1: Extranonce<'a>, + extra_nonce1: Extranonce, extra_nonce2_size: usize, - ) -> Result> { + ) -> Result { self.set_extranonce1(client_id, Some(extra_nonce1.clone())); self.set_extranonce2_size(client_id, Some(extra_nonce2_size)); @@ -255,19 +255,19 @@ pub trait IsServer<'a> { // {"params":["00003000"], "id":null, "method": "mining.set_version_mask"} // fn update_version_rolling_mask - fn notify(&mut self, client_id: Option) -> Result>; + fn notify(&mut self, client_id: Option) -> Result; fn handle_set_difficulty( &mut self, _client_id: Option, value: f64, - ) -> Result> { + ) -> Result { let set_difficulty = server_to_client::SetDifficulty { value }; Ok(set_difficulty.into()) } } -pub trait IsClient<'a> { +pub trait IsClient { /// Deserialize a [raw json_rpc message][a] into a [stratum v1 message][b] and handle the /// result. /// @@ -277,11 +277,11 @@ pub trait IsClient<'a> { &mut self, server_id: Option, msg: json_rpc::Message, - ) -> Result, Error<'a>> + ) -> Result, Error> where Self: std::marker::Sized, { - let method: Result, MethodError<'a>> = msg.try_into(); + let method: Result = msg.try_into(); match method { Ok(m) => match m { @@ -300,8 +300,8 @@ pub trait IsClient<'a> { fn update_response( &mut self, server_id: Option, - response: methods::Server2ClientResponse<'a>, - ) -> Result, Error<'a>> { + response: methods::Server2ClientResponse, + ) -> Result { match &response { methods::Server2ClientResponse::GeneralResponse(general) => { let is_authorize = self.id_is_authorize(server_id, &general.id); @@ -325,8 +325,8 @@ pub trait IsClient<'a> { fn handle_request( &mut self, server_id: Option, - request: methods::Server2Client<'a>, - ) -> Result, Error<'a>> + request: methods::Server2Client, + ) -> Result, Error> where Self: std::marker::Sized, { @@ -353,8 +353,8 @@ pub trait IsClient<'a> { fn handle_response( &mut self, server_id: Option, - response: methods::Server2ClientResponse<'a>, - ) -> Result, Error<'a>> + response: methods::Server2ClientResponse, + ) -> Result, Error> where Self: std::marker::Sized, { @@ -405,7 +405,7 @@ pub trait IsClient<'a> { &mut self, server_id: Option, message: Message, - ) -> Result, Error<'a>>; + ) -> Result, Error>; /// Check if the client sent an Authorize request with the given id, if so it return the /// authorized name @@ -417,42 +417,42 @@ pub trait IsClient<'a> { fn handle_notify( &mut self, server_id: Option, - notify: server_to_client::Notify<'a>, - ) -> Result<(), Error<'a>>; + notify: server_to_client::Notify, + ) -> Result<(), Error>; fn handle_configure( &mut self, server_id: Option, conf: &mut server_to_client::Configure, - ) -> Result<(), Error<'a>>; + ) -> Result<(), Error>; fn handle_set_difficulty( &mut self, server_id: Option, m: &mut server_to_client::SetDifficulty, - ) -> Result<(), Error<'a>>; + ) -> Result<(), Error>; fn handle_set_extranonce( &mut self, server_id: Option, m: &mut server_to_client::SetExtranonce, - ) -> Result<(), Error<'a>>; + ) -> Result<(), Error>; fn handle_set_version_mask( &mut self, server_id: Option, m: &mut server_to_client::SetVersionMask, - ) -> Result<(), Error<'a>>; + ) -> Result<(), Error>; fn handle_subscribe( &mut self, server_id: Option, - subscribe: &server_to_client::Subscribe<'a>, - ) -> Result<(), Error<'a>>; + subscribe: &server_to_client::Subscribe, + ) -> Result<(), Error>; - fn set_extranonce1(&mut self, server_id: Option, extranonce1: Extranonce<'a>); + fn set_extranonce1(&mut self, server_id: Option, extranonce1: Extranonce); - fn extranonce1(&self, server_id: Option) -> Extranonce<'a>; + fn extranonce1(&self, server_id: Option) -> Extranonce; fn set_extranonce2_size(&mut self, server_id: Option, extra_nonce2_size: usize); @@ -472,7 +472,7 @@ pub trait IsClient<'a> { fn status(&self, server_id: Option) -> ClientStatus; - fn last_notify(&self, server_id: Option) -> Option>; + fn last_notify(&self, server_id: Option) -> Option; /// Check if the given user_name has been authorized by the server #[allow(clippy::ptr_arg)] @@ -500,8 +500,8 @@ pub trait IsClient<'a> { &mut self, server_id: Option, id: u64, - extranonce1: Option>, - ) -> Result> { + extranonce1: Option, + ) -> Result { match self.status(server_id) { ClientStatus::Init => Err(Error::IncorrectClientStatus("mining.subscribe".to_string())), _ => Ok(client_to_server::Subscribe { @@ -519,7 +519,7 @@ pub trait IsClient<'a> { id: u64, name: String, password: String, - ) -> Result> { + ) -> Result { match self.status(server_id) { ClientStatus::Init => Err(Error::IncorrectClientStatus("mining.authorize".to_string())), _ => Ok(client_to_server::Authorize { id, name, password }.into()), @@ -532,11 +532,11 @@ pub trait IsClient<'a> { server_id: Option, id: u64, user_name: String, - extra_nonce2: Extranonce<'a>, + extra_nonce2: Extranonce, time: i64, nonce: i64, version_bits: Option, - ) -> Result> { + ) -> Result { match self.status(server_id) { ClientStatus::Init => Err(Error::IncorrectClientStatus("mining.submit".to_string())), _ => { @@ -577,16 +577,16 @@ mod tests { use std::collections::HashSet; // A minimal implementation of IsServer trait for testing - struct TestServer<'a> { + struct TestServer { authorized_users: HashSet, - extranonce1: Extranonce<'a>, + extranonce1: Extranonce, extranonce2_size: usize, version_rolling_mask: Option, version_rolling_min_bit: Option, } - impl<'a> TestServer<'a> { - fn new(extranonce1: Extranonce<'a>, extranonce2_size: usize) -> Self { + impl TestServer { + fn new(extranonce1: Extranonce, extranonce2_size: usize) -> Self { Self { authorized_users: HashSet::new(), extranonce1, @@ -597,7 +597,7 @@ mod tests { } } - impl<'a> IsServer<'a> for TestServer<'a> { + impl IsServer for TestServer { fn handle_configure( &mut self, _client_id: Option, @@ -622,7 +622,7 @@ mod tests { true } - fn notify(&mut self, _client_id: Option) -> Result> { + fn notify(&mut self, _client_id: Option) -> Result { Ok(json_rpc::Message::StandardRequest( json_rpc::StandardRequest { id: 1, @@ -635,7 +635,7 @@ mod tests { fn handle_submit( &self, _client_id: Option, - _request: &client_to_server::Submit<'a>, + _request: &client_to_server::Submit, ) -> bool { true } @@ -653,15 +653,15 @@ mod tests { fn set_extranonce1( &mut self, _client_id: Option, - extranonce1: Option>, - ) -> Extranonce<'a> { + extranonce1: Option, + ) -> Extranonce { if let Some(extranonce1) = extranonce1 { self.extranonce1 = extranonce1; } self.extranonce1.clone() } - fn extranonce1(&self, _client_id: Option) -> Extranonce<'a> { + fn extranonce1(&self, _client_id: Option) -> Extranonce { self.extranonce1.clone() } diff --git a/sv1/src/methods/client_to_server.rs b/sv1/src/methods/client_to_server.rs index 381ee82e2e..a81d7e35d6 100644 --- a/sv1/src/methods/client_to_server.rs +++ b/sv1/src/methods/client_to_server.rs @@ -126,10 +126,10 @@ pub struct ExtranonceSubscribe(); /// Server response is result: true for accepted, false for rejected (or you may get an error with /// more details). #[derive(Debug, Clone, PartialEq, Eq)] -pub struct Submit<'a> { +pub struct Submit { pub user_name: String, // root pub job_id: String, // 6 - pub extra_nonce2: Extranonce<'a>, // "8a.." + pub extra_nonce2: Extranonce, // "8a.." pub time: HexU32Be, //string pub nonce: HexU32Be, pub version_bits: Option, @@ -138,7 +138,7 @@ pub struct Submit<'a> { //"{"params": ["spotbtc1.m30s40x16", "2", "147a3f0000000000", "6436eddf", "41d5deb0", "00000000"], //"{"params": "id": 2196, "method": "mining.submit"}" -impl fmt::Display for Submit<'_> { +impl fmt::Display for Submit { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!( f, @@ -154,7 +154,7 @@ impl fmt::Display for Submit<'_> { } } -impl Submit<'_> { +impl Submit { pub fn respond(self, is_ok: bool) -> Response { // infallibel let result = serde_json::to_value(is_ok).unwrap(); @@ -166,7 +166,7 @@ impl Submit<'_> { } } -impl From> for Message { +impl From for Message { fn from(submit: Submit) -> Self { let ex: String = submit.extra_nonce2.0.inner_as_ref().to_hex(); let mut params: Vec = vec![ @@ -188,7 +188,7 @@ impl From> for Message { } } -impl TryFrom for Submit<'_> { +impl TryFrom for Submit { type Error = ParsingMethodError; #[allow(clippy::many_single_char_names)] @@ -249,7 +249,7 @@ impl TryFrom for Submit<'_> { } #[cfg(test)] -impl Arbitrary for Submit<'static> { +impl Arbitrary for Submit { fn arbitrary(g: &mut Gen) -> Self { let mut extra = Vec::::arbitrary(g); extra.resize(32, 0); @@ -273,7 +273,7 @@ impl Arbitrary for Submit<'static> { #[cfg(test)] #[quickcheck_macros::quickcheck] -fn submit_from_to_json_rpc(submit: Submit<'static>) -> bool { +fn submit_from_to_json_rpc(submit: Submit) -> bool { let message = Into::::into(submit.clone()); println!("\nMESSAGE: {message:?}\n"); let request = match message { @@ -293,13 +293,13 @@ fn submit_from_to_json_rpc(submit: Submit<'static>) -> bool { /// /// [a]: crate::methods::server_to_client::Notify #[derive(Debug, Clone)] -pub struct Subscribe<'a> { +pub struct Subscribe { pub id: u64, pub agent_signature: String, - pub extranonce1: Option>, + pub extranonce1: Option, } -impl fmt::Display for Subscribe<'_> { +impl fmt::Display for Subscribe { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!( f, @@ -309,11 +309,11 @@ impl fmt::Display for Subscribe<'_> { } } -impl<'a> Subscribe<'a> { +impl Subscribe { pub fn respond( self, subscriptions: Vec<(String, String)>, - extra_nonce1: Extranonce<'a>, + extra_nonce1: Extranonce, extra_nonce2_size: usize, ) -> Response { let response = crate::server_to_client::Subscribe { @@ -329,8 +329,8 @@ impl<'a> Subscribe<'a> { } } -impl<'a> TryFrom> for Message { - type Error = Error<'a>; +impl TryFrom for Message { + type Error = Error; fn try_from(subscribe: Subscribe) -> Result { let params = match (subscribe.agent_signature, subscribe.extranonce1) { @@ -345,7 +345,7 @@ impl<'a> TryFrom> for Message { } } -impl TryFrom for Subscribe<'_> { +impl TryFrom for Subscribe { type Error = ParsingMethodError; fn try_from(msg: StandardRequest) -> Result { diff --git a/sv1/src/methods/mod.rs b/sv1/src/methods/mod.rs index a91978b481..44165467c0 100644 --- a/sv1/src/methods/mod.rs +++ b/sv1/src/methods/mod.rs @@ -9,7 +9,7 @@ use crate::json_rpc::{Message, Response}; /// Errors encountered during conversion between valid json_rpc messages and Sv1 messages. #[derive(Debug, Clone)] -pub enum MethodError<'a> { +pub enum MethodError { /// If the json_rpc message call a method not defined by Sv1. It contains the called method MethodNotFound(String), /// If the json_rpc Response co"ntain an error in this case the error should just be reported @@ -18,7 +18,7 @@ pub enum MethodError<'a> { ParsingMethodError((ParsingMethodError, Message)), // Method can not be serialized // SerializeError(Box), - UnexpectedMethod(Method<'a>), + UnexpectedMethod(Method), // json_rpc message is not a request NotARequest, } @@ -57,7 +57,7 @@ pub enum ParsingMethodError { Todo, } -impl From> for ParsingMethodError { +impl From for ParsingMethodError { fn from(inner: Error) -> Self { match inner { Error::HexError(e) => ParsingMethodError::HexError(Box::new(e)), @@ -71,7 +71,7 @@ impl From> for ParsingMethodError { } impl ParsingMethodError { - pub fn as_method_error(self, msg: Message) -> MethodError<'static> { + pub fn as_method_error(self, msg: Message) -> MethodError { MethodError::ParsingMethodError((self, msg)) } } @@ -107,31 +107,31 @@ impl ParsingMethodError { } #[derive(Debug, Clone)] -pub enum Method<'a> { - Client2Server(Client2Server<'a>), - Server2Client(Server2Client<'a>), - Server2ClientResponse(Server2ClientResponse<'a>), +pub enum Method { + Client2Server(Client2Server), + Server2Client(Server2Client), + Server2ClientResponse(Server2ClientResponse), ErrorMessage(Message), } #[derive(Debug, Clone)] -pub enum Client2Server<'a> { +pub enum Client2Server { SuggestDifficulty(), - Subscribe(client_to_server::Subscribe<'a>), + Subscribe(client_to_server::Subscribe), Authorize(client_to_server::Authorize), ExtranonceSubscribe(client_to_server::ExtranonceSubscribe), - Submit(client_to_server::Submit<'a>), + Submit(client_to_server::Submit), Configure(client_to_server::Configure), } -impl<'a> From> for Method<'a> { - fn from(a: Client2Server<'a>) -> Self { +impl From for Method { + fn from(a: Client2Server) -> Self { Method::Client2Server(a) } } -impl<'a> TryFrom for Client2Server<'a> { - type Error = MethodError<'a>; +impl TryFrom for Client2Server { + type Error = MethodError; fn try_from(msg: Message) -> Result { let method: Method = msg.try_into()?; @@ -145,21 +145,21 @@ impl<'a> TryFrom for Client2Server<'a> { } #[derive(Debug, Clone)] -pub enum Server2Client<'a> { - Notify(server_to_client::Notify<'a>), +pub enum Server2Client { + Notify(server_to_client::Notify), SetDifficulty(server_to_client::SetDifficulty), - SetExtranonce(server_to_client::SetExtranonce<'a>), + SetExtranonce(server_to_client::SetExtranonce), SetVersionMask(server_to_client::SetVersionMask), } -impl<'a> From> for Method<'a> { - fn from(a: Server2Client<'a>) -> Self { +impl From for Method { + fn from(a: Server2Client) -> Self { Method::Server2Client(a) } } -impl<'a> TryFrom for Server2Client<'a> { - type Error = MethodError<'a>; +impl TryFrom for Server2Client { + type Error = MethodError; fn try_from(msg: Message) -> Result { let method: Method = msg.try_into()?; @@ -173,23 +173,23 @@ impl<'a> TryFrom for Server2Client<'a> { } #[derive(Debug, Clone)] -pub enum Server2ClientResponse<'a> { +pub enum Server2ClientResponse { Configure(server_to_client::Configure), - Subscribe(server_to_client::Subscribe<'a>), + Subscribe(server_to_client::Subscribe), GeneralResponse(server_to_client::GeneralResponse), Authorize(server_to_client::Authorize), Submit(server_to_client::Submit), SetDifficulty(server_to_client::SetDifficulty), } -impl<'a> From> for Method<'a> { - fn from(a: Server2ClientResponse<'a>) -> Self { +impl From for Method { + fn from(a: Server2ClientResponse) -> Self { Method::Server2ClientResponse(a) } } -impl<'a> TryFrom for Server2ClientResponse<'a> { - type Error = MethodError<'a>; +impl TryFrom for Server2ClientResponse { + type Error = MethodError; fn try_from(msg: Message) -> Result { let method: Method = msg.try_into()?; @@ -202,10 +202,10 @@ impl<'a> TryFrom for Server2ClientResponse<'a> { } } -impl<'a> TryFrom for Method<'a> { - type Error = MethodError<'a>; +impl TryFrom for Method { + type Error = MethodError; - fn try_from(msg: Message) -> Result> { + fn try_from(msg: Message) -> Result { match &msg { Message::StandardRequest(request) => match &request.method[..] { "mining.suggest_difficulty" => { @@ -285,7 +285,7 @@ impl<'a> TryFrom for Method<'a> { } } -impl TryFrom for Server2ClientResponse<'_> { +impl TryFrom for Server2ClientResponse { type Error = ParsingMethodError; fn try_from(msg: Response) -> Result { diff --git a/sv1/src/methods/server_to_client.rs b/sv1/src/methods/server_to_client.rs index fb2c527a03..c6dde41ce0 100644 --- a/sv1/src/methods/server_to_client.rs +++ b/sv1/src/methods/server_to_client.rs @@ -38,19 +38,19 @@ use crate::{ /// If false, they can still use the current job, but should move to the new one after exhausting /// the current nonce range. #[derive(Debug, Clone)] -pub struct Notify<'a> { +pub struct Notify { pub job_id: String, - pub prev_hash: PrevHash<'a>, + pub prev_hash: PrevHash, pub coin_base1: HexBytes, pub coin_base2: HexBytes, - pub merkle_branch: Vec>, + pub merkle_branch: Vec, pub version: HexU32Be, pub bits: HexU32Be, pub time: HexU32Be, pub clean_jobs: bool, } -impl<'a> fmt::Display for Notify<'a> { +impl fmt::Display for Notify { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!( f, @@ -82,7 +82,7 @@ impl<'a> fmt::Display for Notify<'a> { } } -impl From> for Message { +impl From for Message { fn from(notify: Notify) -> Self { let prev_hash: Value = notify.prev_hash.into(); let coin_base1: Value = notify.coin_base1.into(); @@ -114,7 +114,7 @@ impl From> for Message { } } -impl TryFrom for Notify<'_> { +impl TryFrom for Notify { type Error = ParsingMethodError; #[allow(clippy::many_single_char_names)] @@ -232,12 +232,12 @@ impl TryFrom for SetDifficulty { /// check if it is a Notification or a StandardRequest this implementation assume that it is a /// Notification #[derive(Debug, Clone)] -pub struct SetExtranonce<'a> { - pub extra_nonce1: Extranonce<'a>, +pub struct SetExtranonce { + pub extra_nonce1: Extranonce, pub extra_nonce2_size: usize, } -impl fmt::Display for SetExtranonce<'_> { +impl fmt::Display for SetExtranonce { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!( f, @@ -247,7 +247,7 @@ impl fmt::Display for SetExtranonce<'_> { } } -impl From> for Message { +impl From for Message { fn from(se: SetExtranonce) -> Self { let extra_nonce1: Value = se.extra_nonce1.into(); let extra_nonce2_size: Value = se.extra_nonce2_size.into(); @@ -258,7 +258,7 @@ impl From> for Message { } } -impl TryFrom for SetExtranonce<'_> { +impl TryFrom for SetExtranonce { type Error = ParsingMethodError; fn try_from(msg: Notification) -> Result { @@ -435,14 +435,14 @@ impl Submit { /// /// ExtraNonce2_size. - The number of bytes that the miner users for its ExtraNonce2 counter. #[derive(Debug, Clone)] -pub struct Subscribe<'a> { +pub struct Subscribe { pub id: u64, - pub extra_nonce1: Extranonce<'a>, + pub extra_nonce1: Extranonce, pub extra_nonce2_size: usize, pub subscriptions: Vec<(String, String)>, } -impl fmt::Display for Subscribe<'_> { +impl fmt::Display for Subscribe { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!( f, @@ -452,7 +452,7 @@ impl fmt::Display for Subscribe<'_> { } } -impl From> for Message { +impl From for Message { fn from(su: Subscribe) -> Self { let extra_nonce1: Value = su.extra_nonce1.into(); let extra_nonce2_size: Value = su.extra_nonce2_size.into(); @@ -470,7 +470,7 @@ impl From> for Message { } } -impl TryFrom<&Response> for Subscribe<'_> { +impl TryFrom<&Response> for Subscribe { type Error = ParsingMethodError; fn try_from(msg: &Response) -> Result { @@ -716,7 +716,7 @@ impl VersionRollingParams { pub fn new( version_rolling_mask: HexU32Be, version_rolling_min_bit_count: HexU32Be, - ) -> Result> { + ) -> Result { // 0x1FFFE000 should be configured let negotiated_mask = HexU32Be(version_rolling_mask.clone() & 0x1FFFE000); diff --git a/sv1/src/utils.rs b/sv1/src/utils.rs index 10539767ea..190901b255 100644 --- a/sv1/src/utils.rs +++ b/sv1/src/utils.rs @@ -11,15 +11,15 @@ use std::{convert::TryFrom, mem::size_of, ops::BitAnd}; /// that are represented as hex strings in JSON. /// Extranonce must be less than or equal to 32 bytes. #[derive(Clone, Debug, PartialEq, Eq)] -pub struct Extranonce<'a>(pub B032<'a>); +pub struct Extranonce(pub B032); -impl fmt::Display for Extranonce<'_> { +impl fmt::Display for Extranonce { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_str(&self.0.inner_as_ref().to_hex()) } } -impl Extranonce<'_> { +impl Extranonce { pub fn len(&self) -> usize { self.0.inner_as_ref().len() } @@ -28,28 +28,28 @@ impl Extranonce<'_> { } } -impl<'a> TryFrom> for Extranonce<'a> { - type Error = Error<'a>; - fn try_from(value: Vec) -> Result> { +impl TryFrom> for Extranonce { + type Error = Error; + fn try_from(value: Vec) -> Result { Ok(Extranonce(B032::try_from(value)?)) } } -impl<'a> From> for Vec { - fn from(v: Extranonce<'a>) -> Self { +impl From for Vec { + fn from(v: Extranonce) -> Self { v.0.to_vec() } } -impl<'a> From> for Value { - fn from(eb: Extranonce<'a>) -> Self { +impl From for Value { + fn from(eb: Extranonce) -> Self { Into::::into(eb).into() } } /// fix for error on odd-length hex sequences /// FIXME: find a nicer solution -fn hex_decode(s: &str) -> Result, Error<'static>> { +fn hex_decode(s: &str) -> Result, Error> { if s.len() % 2 != 0 { Vec::::from_hex(&format!("0{s}")).map_err(Error::HexError) } else { @@ -57,16 +57,16 @@ fn hex_decode(s: &str) -> Result, Error<'static>> { } } -impl<'a> TryFrom<&str> for Extranonce<'a> { - type Error = error::Error<'a>; +impl TryFrom<&str> for Extranonce { + type Error = error::Error; - fn try_from(value: &str) -> Result> { + fn try_from(value: &str) -> Result { Ok(Extranonce(B032::try_from(hex_decode(value)?)?)) } } -impl<'a> From> for String { - fn from(bytes: Extranonce<'a>) -> String { +impl From for String { + fn from(bytes: Extranonce) -> String { bytes.0.inner_as_ref().to_hex() } } @@ -79,8 +79,8 @@ impl BitAnd for HexU32Be { } } -impl<'a> From> for Extranonce<'a> { - fn from(b: B032<'a>) -> Self { +impl From for Extranonce { + fn from(b: B032) -> Self { Extranonce(b) } } @@ -108,9 +108,9 @@ impl From for Value { } impl TryFrom<&str> for HexU32Be { - type Error = Error<'static>; + type Error = Error; - fn try_from(value: &str) -> Result> { + fn try_from(value: &str) -> Result { let expected_len = 8; if value.len() > expected_len { return Err(Error::InvalidHexLen(value.to_string())); @@ -169,9 +169,9 @@ impl<'de> Deserialize<'de> for HexU32Be { /// PrevHash in Stratum V1 has brain-damaged serialization as it swaps bytes of every u32 word /// into big endian. Therefore, we need a special type for it #[derive(Clone, Debug, PartialEq, Eq)] -pub struct PrevHash<'a>(pub U256<'a>); +pub struct PrevHash(pub U256); -impl fmt::Display for PrevHash<'_> { +impl fmt::Display for PrevHash { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { // Reuse the Stratum V1 serialization logic let s = String::from(self.clone()); @@ -179,16 +179,16 @@ impl fmt::Display for PrevHash<'_> { } } -impl<'a> From> for Vec { - fn from(p_hash: PrevHash<'a>) -> Self { +impl From for Vec { + fn from(p_hash: PrevHash) -> Self { p_hash.0.to_vec() } } -impl<'a> TryFrom<&str> for PrevHash<'a> { - type Error = Error<'a>; +impl TryFrom<&str> for PrevHash { + type Error = Error; - fn try_from(value: &str) -> Result> { + fn try_from(value: &str) -> Result { // Reorder PrevHash will be stored via this cursor // let mut prev_hash_cursor = std::io::Cursor::new([0_u8; 32]); let mut prev_hash_arr = [0_u8; 32]; @@ -217,7 +217,7 @@ impl<'a> TryFrom<&str> for PrevHash<'a> { } } -impl From> for Value { +impl From for Value { fn from(ph: PrevHash) -> Self { Into::::into(ph).into() } @@ -225,7 +225,7 @@ impl From> for Value { /// Helper Serializer that peforms the reverse process of converting the prev hash into stratum V1 /// ordering -impl From> for String { +impl From for String { fn from(v: PrevHash) -> Self { let mut prev_hash_stratum_cursor = std::io::Cursor::new(Vec::new()); // swap every u32 from little endian to big endian @@ -240,80 +240,80 @@ impl From> for String { } // / Referencing the internal part of hex bytes -impl AsRef<[u8]> for PrevHash<'_> { +impl AsRef<[u8]> for PrevHash { fn as_ref(&self) -> &[u8] { self.0.inner_as_ref() } } /// Referencing the internal part of hex bytes -impl<'a> AsRef> for PrevHash<'a> { - fn as_ref(&self) -> &U256<'a> { +impl AsRef for PrevHash { + fn as_ref(&self) -> &U256 { &self.0 } } /// Referencing the internal part of hex bytes -impl AsRef<[u8]> for Extranonce<'_> { +impl AsRef<[u8]> for Extranonce { fn as_ref(&self) -> &[u8] { self.0.inner_as_ref() } } #[derive(Clone, Debug, PartialEq, Eq)] -pub struct MerkleNode<'a>(pub U256<'a>); +pub struct MerkleNode(pub U256); -impl fmt::Display for MerkleNode<'_> { +impl fmt::Display for MerkleNode { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", self.0.inner_as_ref().to_hex()) } } -impl MerkleNode<'_> { +impl MerkleNode { pub fn is_empty(&self) -> bool { self.0.inner_as_ref().is_empty() } } -impl<'a> TryFrom> for MerkleNode<'a> { - type Error = Error<'a>; +impl TryFrom> for MerkleNode { + type Error = Error; - fn try_from(value: Vec) -> Result> { + fn try_from(value: Vec) -> Result { let merkle = U256::try_from(value).map_err(error::Error::from)?; Ok(MerkleNode(merkle)) } } -impl<'a> From> for Vec { - fn from(v: MerkleNode<'a>) -> Self { +impl From for Vec { + fn from(v: MerkleNode) -> Self { v.0.to_vec() } } -impl<'a> From> for Value { - fn from(eb: MerkleNode<'a>) -> Self { +impl From for Value { + fn from(eb: MerkleNode) -> Self { Into::::into(eb).into() } } /// Referencing the internal part of hex bytes -impl AsRef<[u8]> for MerkleNode<'_> { +impl AsRef<[u8]> for MerkleNode { fn as_ref(&self) -> &[u8] { self.0.inner_as_ref() } } -impl<'a> TryFrom<&str> for MerkleNode<'a> { - type Error = Error<'a>; +impl TryFrom<&str> for MerkleNode { + type Error = Error; - fn try_from(value: &str) -> Result> { + fn try_from(value: &str) -> Result { let merkle = U256::try_from(hex_decode(value)?).map_err(error::Error::from)?; Ok(MerkleNode(merkle)) } } -impl<'a> From> for String { - fn from(bytes: MerkleNode<'a>) -> String { +impl From for String { + fn from(bytes: MerkleNode) -> String { bytes.0.inner_as_ref().to_hex() } } @@ -365,9 +365,9 @@ impl AsRef> for HexBytes { } impl TryFrom<&str> for HexBytes { - type Error = Error<'static>; + type Error = Error; - fn try_from(value: &str) -> Result> { + fn try_from(value: &str) -> Result { Ok(HexBytes(hex_decode(value)?)) } } diff --git a/sv2/binary-sv2/derive_codec/src/lib.rs b/sv2/binary-sv2/derive_codec/src/lib.rs index f997c55f30..17c057ab1e 100644 --- a/sv2/binary-sv2/derive_codec/src/lib.rs +++ b/sv2/binary-sv2/derive_codec/src/lib.rs @@ -636,7 +636,7 @@ pub fn decodable(item: TokenStream) -> TokenStream { let impl_generics = if !parsed_struct.generics.is_empty() { parsed_struct.clone().generics } else { - "<'decoder>".to_string() + "".to_string() }; let result = format!( @@ -645,7 +645,7 @@ pub fn decodable(item: TokenStream) -> TokenStream { use super::binary_sv2::{{decodable::DecodableField, decodable::FieldMarker, Decodable, Error, SizeHint}}; use super::*; - impl{} Decodable<'decoder> for {}{} {{ + impl{} Decodable for {}{} {{ fn get_structure({}: &[u8]) -> Result, Error> {{ let mut fields = Vec::new(); let mut {} = 0; @@ -653,7 +653,7 @@ pub fn decodable(item: TokenStream) -> TokenStream { Ok(fields) }} - fn from_decoded_fields(mut {}: Vec>) -> Result {{ + fn from_decoded_fields(mut {}: Vec) -> Result {{ Ok(Self {{ {} }}) @@ -710,11 +710,7 @@ pub fn decodable(item: TokenStream) -> TokenStream { } fn get_static_generics(gen: &str) -> &str { - if gen.is_empty() { - gen - } else { - "<'static>" - } + gen } /// Derives the `Encodable` trait, generating implementations for serializing a struct into an @@ -820,7 +816,7 @@ pub fn encodable(item: TokenStream) -> TokenStream { let impl_generics = if !parsed_struct.generics.is_empty() { parsed_struct.clone().generics } else { - "<'decoder>".to_string() + "".to_string() }; let get_size = if is_already_sized { @@ -848,7 +844,7 @@ pub fn encodable(item: TokenStream) -> TokenStream { extern crate alloc; use alloc::vec::Vec; - impl{} From<{}{}> for super::binary_sv2::EncodableField<'decoder> {{ + impl{} From<{}{}> for super::binary_sv2::EncodableField {{ fn from(v: {}{}) -> Self {{ let mut fields: Vec = Vec::new(); {} diff --git a/sv2/binary-sv2/src/codec/decodable.rs b/sv2/binary-sv2/src/codec/decodable.rs index 81d928cf2a..0a7d6af84a 100644 --- a/sv2/binary-sv2/src/codec/decodable.rs +++ b/sv2/binary-sv2/src/codec/decodable.rs @@ -12,7 +12,7 @@ use std::io::{Cursor, Read}; /// /// Defines the process of reconstructing a type from a sequence of bytes. It handles both simple /// and nested or complex data structures. -pub trait Decodable<'a>: Sized { +pub trait Decodable: Sized { /// Defines the expected structure of a type based on binary data. /// /// Returns a vector of [`FieldMarker`]s, each representing a component of the structure. @@ -23,14 +23,14 @@ pub trait Decodable<'a>: Sized { /// /// After the data has been split into fields, this method combines those fields /// back into the original type, handling nested structures or composite fields. - fn from_decoded_fields(data: Vec>) -> Result; + fn from_decoded_fields(data: Vec) -> Result; /// Decodes the type from raw bytes. /// /// Orchestrates the decoding process, calling `get_structure` to break down /// the raw data, decoding each field, and then using `from_decoded_fields` to reassemble /// the fields into the original type. - fn from_bytes(data: &'a mut [u8]) -> Result { + fn from_bytes(data: &mut [u8]) -> Result { let structure = Self::get_structure(data)?; let mut fields = Vec::new(); let mut tail = data; @@ -116,21 +116,21 @@ pub trait GetMarker { // Represents a list of decode-able primitive data types. // #[derive(Debug)] -pub enum DecodablePrimitive<'a> { +pub enum DecodablePrimitive { U8(u8), U16(u16), Bool(bool), U24(U24), - U256(U256<'a>), - Signature(Signature<'a>), + U256(U256), + Signature(Signature), U32(u32), - U32AsRef(U32AsRef<'a>), + U32AsRef(U32AsRef), F32(f32), U64(u64), - B032(B032<'a>), - B0255(B0255<'a>), - B064K(B064K<'a>), - B016M(B016M<'a>), + B032(B032), + B0255(B0255), + B064K(B064K), + B016M(B016M), } /// Recursive enum representing a Decode-able field. @@ -141,12 +141,12 @@ pub enum DecodablePrimitive<'a> { /// or a struct, which may itself contain multiple decoded fields. This type encapsulates that /// distinction. #[derive(Debug)] -pub enum DecodableField<'a> { +pub enum DecodableField { /// Primitive field. - Primitive(DecodablePrimitive<'a>), + Primitive(DecodablePrimitive), /// Structured field, allowing for nested data structures. - Struct(Vec>), + Struct(Vec), } impl SizeHint for PrimitiveMarker { @@ -233,8 +233,8 @@ impl TryFrom> for FieldMarker { } } -impl<'a> From> for Vec> { - fn from(v: DecodableField<'a>) -> Self { +impl From for Vec { + fn from(v: DecodableField) -> Self { match v { DecodableField::Primitive(p) => vec![DecodableField::Primitive(p)], DecodableField::Struct(ps) => ps, @@ -246,7 +246,7 @@ impl PrimitiveMarker { // Decodes a primitive value from a byte slice at the given offset, returning the corresponding // `DecodablePrimitive`. The specific decoding logic depends on the type of the primitive (e.g., // `u8`, `u16`, etc.). - fn decode<'a>(&self, data: &'a mut [u8], offset: usize) -> DecodablePrimitive<'a> { + fn decode(&self, data: &mut [u8], offset: usize) -> DecodablePrimitive { match self { Self::U8 => DecodablePrimitive::U8(u8::from_bytes_unchecked(&mut data[offset..])), Self::U16 => DecodablePrimitive::U16(u16::from_bytes_unchecked(&mut data[offset..])), @@ -280,7 +280,7 @@ impl PrimitiveMarker { // where the data is not immediately available as a slice but must be read incrementally. #[allow(clippy::wrong_self_convention)] #[cfg(not(feature = "no_std"))] - fn from_reader<'a>(&self, reader: &mut impl Read) -> Result, Error> { + fn from_reader(&self, reader: &mut impl Read) -> Result { match self { Self::U8 => Ok(DecodablePrimitive::U8(u8::from_reader_(reader)?)), Self::U16 => Ok(DecodablePrimitive::U16(u16::from_reader_(reader)?)), @@ -304,7 +304,7 @@ impl PrimitiveMarker { } } -impl GetSize for DecodablePrimitive<'_> { +impl GetSize for DecodablePrimitive { fn get_size(&self) -> usize { match self { DecodablePrimitive::U8(v) => v.get_size(), @@ -330,7 +330,7 @@ impl FieldMarker { // Depending on whether the field is primitive or structured, this method decodes the // corresponding data. If the field is a structure, it recursively decodes each nested field // and returns the resulting `DecodableField`. - pub(crate) fn decode<'a>(&self, data: &'a mut [u8]) -> Result, Error> { + pub(crate) fn decode(&self, data: &mut [u8]) -> Result { match self { Self::Primitive(p) => Ok(DecodableField::Primitive(p.decode(data, 0))), Self::Struct(ps) => { @@ -350,10 +350,10 @@ impl FieldMarker { #[allow(clippy::wrong_self_convention)] #[cfg(not(feature = "no_std"))] #[allow(clippy::wrong_self_convention)] - pub(crate) fn from_reader<'a>( + pub(crate) fn from_reader( &self, reader: &mut impl Read, - ) -> Result, Error> { + ) -> Result { match self { Self::Primitive(p) => Ok(DecodableField::Primitive(p.from_reader(reader)?)), Self::Struct(ps) => { diff --git a/sv2/binary-sv2/src/codec/encodable.rs b/sv2/binary-sv2/src/codec/encodable.rs index eb2bc003af..1c7a4ac029 100644 --- a/sv2/binary-sv2/src/codec/encodable.rs +++ b/sv2/binary-sv2/src/codec/encodable.rs @@ -46,7 +46,7 @@ pub trait Encodable { fn to_writer(self, dst: &mut impl Write) -> Result<(), E>; } -impl<'a, T: Into>> Encodable for T { +impl> Encodable for T { #[allow(clippy::wrong_self_convention)] fn to_bytes(self, dst: &mut [u8]) -> Result { let encoded_field = self.into(); @@ -67,7 +67,7 @@ impl<'a, T: Into>> Encodable for T { /// that can be encoded into a byte representation. Each variant holds a specific /// type, and encoding logic is provided through the `encode` method. #[derive(Debug)] -pub enum EncodablePrimitive<'a> { +pub enum EncodablePrimitive { /// U8 Primitive, representing a byte U8(u8), /// Owned U8 Primitive, representing an owned byte @@ -79,28 +79,28 @@ pub enum EncodablePrimitive<'a> { /// U24 Primitive, representing a U24 type U24(U24), /// U256 Primitive, representing a U256 type - U256(U256<'a>), + U256(U256), /// Signature Primitive, representing a Signature type - Signature(Signature<'a>), + Signature(Signature), /// U32 Primitive, representing a u32 type U32(u32), /// U32AsRef Primitive, representing a U32AsRef type - U32AsRef(U32AsRef<'a>), + U32AsRef(U32AsRef), /// F32 Primitive, representing a f32 type F32(f32), /// U64 Primitive, representing a u64 type U64(u64), /// B032 Primitive, representing a B032 type - B032(B032<'a>), + B032(B032), /// B0255 Primitive, representing a B0255 type - B0255(B0255<'a>), + B0255(B0255), /// B064K Primitive, representing a B064K type - B064K(B064K<'a>), + B064K(B064K), /// B016M Primitive, representing a B016M type - B016M(B016M<'a>), + B016M(B016M), } -impl EncodablePrimitive<'_> { +impl EncodablePrimitive { // Provides the encoding logic for each primitive type. // // The `encode` method takes the `EncodablePrimitive` variant and serializes it @@ -154,7 +154,7 @@ impl EncodablePrimitive<'_> { } // Provides the logic for calculating the size of the encodable field. -impl GetSize for EncodablePrimitive<'_> { +impl GetSize for EncodablePrimitive { fn get_size(&self) -> usize { match self { Self::U8(v) => v.get_size(), @@ -182,18 +182,18 @@ impl GetSize for EncodablePrimitive<'_> { /// (a struct). The encoding process for [`EncodableField`] supports nesting, allowing /// for complex hierarchical data structures to be serialized. #[derive(Debug)] -pub enum EncodableField<'a> { +pub enum EncodableField { /// Represents a primitive value /// /// For the full supported list please see [`EncodablePrimitive`] - Primitive(EncodablePrimitive<'a>), + Primitive(EncodablePrimitive), /// Represents a struct like field structure. /// /// Note that this is a recursive enum type. - Struct(Vec>), + Struct(Vec), } -impl EncodableField<'_> { +impl EncodableField { /// The `encode` method serializes a field into the destination buffer `dst`, starting /// at the provided `offset`. If the field is a structure, it recursively encodes /// each contained field. If the buffer is too small or encoding fails, the method @@ -228,7 +228,7 @@ impl EncodableField<'_> { } } -impl GetSize for EncodableField<'_> { +impl GetSize for EncodableField { fn get_size(&self) -> usize { match self { Self::Primitive(p) => p.get_size(), diff --git a/sv2/binary-sv2/src/codec/impls.rs b/sv2/binary-sv2/src/codec/impls.rs index 1e98b1bc29..564d354a2e 100644 --- a/sv2/binary-sv2/src/codec/impls.rs +++ b/sv2/binary-sv2/src/codec/impls.rs @@ -47,37 +47,37 @@ impl GetMarker for u64 { FieldMarker::Primitive(PrimitiveMarker::U64) } } -impl GetMarker for U256<'_> { +impl GetMarker for U256 { fn get_marker() -> FieldMarker { FieldMarker::Primitive(PrimitiveMarker::U256) } } -impl GetMarker for Signature<'_> { +impl GetMarker for Signature { fn get_marker() -> FieldMarker { FieldMarker::Primitive(PrimitiveMarker::Signature) } } -impl GetMarker for B032<'_> { +impl GetMarker for B032 { fn get_marker() -> FieldMarker { FieldMarker::Primitive(PrimitiveMarker::B032) } } -impl GetMarker for B0255<'_> { +impl GetMarker for B0255 { fn get_marker() -> FieldMarker { FieldMarker::Primitive(PrimitiveMarker::B0255) } } -impl GetMarker for B064K<'_> { +impl GetMarker for B064K { fn get_marker() -> FieldMarker { FieldMarker::Primitive(PrimitiveMarker::B064K) } } -impl GetMarker for B016M<'_> { +impl GetMarker for B016M { fn get_marker() -> FieldMarker { FieldMarker::Primitive(PrimitiveMarker::B016M) } } -impl GetMarker for U32AsRef<'_> { +impl GetMarker for U32AsRef { fn get_marker() -> FieldMarker { FieldMarker::Primitive(PrimitiveMarker::U32AsRef) } @@ -85,190 +85,190 @@ impl GetMarker for U32AsRef<'_> { // IMPL DECODABLE FOR PRIMITIVES -impl<'a> Decodable<'a> for u8 { +impl Decodable for u8 { fn get_structure(_: &[u8]) -> Result, Error> { Ok(vec![PrimitiveMarker::U8.into()]) } - fn from_decoded_fields(mut data: Vec>) -> Result { + fn from_decoded_fields(mut data: Vec) -> Result { data.pop().ok_or(Error::NoDecodableFieldPassed)?.try_into() } } -impl<'a> Decodable<'a> for u16 { +impl Decodable for u16 { fn get_structure(_: &[u8]) -> Result, Error> { Ok(vec![PrimitiveMarker::U16.into()]) } - fn from_decoded_fields(mut data: Vec>) -> Result { + fn from_decoded_fields(mut data: Vec) -> Result { data.pop().ok_or(Error::NoDecodableFieldPassed)?.try_into() } } -impl<'a> Decodable<'a> for u32 { +impl Decodable for u32 { fn get_structure(_: &[u8]) -> Result, Error> { Ok(vec![PrimitiveMarker::U32.into()]) } - fn from_decoded_fields(mut data: Vec>) -> Result { + fn from_decoded_fields(mut data: Vec) -> Result { data.pop().ok_or(Error::NoDecodableFieldPassed)?.try_into() } } -impl<'a> Decodable<'a> for f32 { +impl Decodable for f32 { fn get_structure(_: &[u8]) -> Result, Error> { Ok(vec![PrimitiveMarker::F32.into()]) } - fn from_decoded_fields(mut data: Vec>) -> Result { + fn from_decoded_fields(mut data: Vec) -> Result { data.pop().ok_or(Error::NoDecodableFieldPassed)?.try_into() } } -impl<'a> Decodable<'a> for u64 { +impl Decodable for u64 { fn get_structure(_: &[u8]) -> Result, Error> { Ok(vec![PrimitiveMarker::U64.into()]) } - fn from_decoded_fields(mut data: Vec>) -> Result { + fn from_decoded_fields(mut data: Vec) -> Result { data.pop().ok_or(Error::NoDecodableFieldPassed)?.try_into() } } -impl<'a> Decodable<'a> for bool { +impl Decodable for bool { fn get_structure(_: &[u8]) -> Result, Error> { Ok(vec![PrimitiveMarker::Bool.into()]) } - fn from_decoded_fields(mut data: Vec>) -> Result { + fn from_decoded_fields(mut data: Vec) -> Result { data.pop().ok_or(Error::NoDecodableFieldPassed)?.try_into() } } -impl<'a> Decodable<'a> for U24 { +impl Decodable for U24 { fn get_structure(_: &[u8]) -> Result, Error> { Ok(vec![PrimitiveMarker::U24.into()]) } - fn from_decoded_fields(mut data: Vec>) -> Result { + fn from_decoded_fields(mut data: Vec) -> Result { data.pop().ok_or(Error::NoDecodableFieldPassed)?.try_into() } } -impl<'a> Decodable<'a> for U256<'a> { +impl Decodable for U256 { fn get_structure(_: &[u8]) -> Result, Error> { Ok(vec![PrimitiveMarker::U256.into()]) } - fn from_decoded_fields(mut data: Vec>) -> Result { + fn from_decoded_fields(mut data: Vec) -> Result { data.pop().ok_or(Error::NoDecodableFieldPassed)?.try_into() } } -impl<'a> Decodable<'a> for Signature<'a> { +impl Decodable for Signature { fn get_structure(_: &[u8]) -> Result, Error> { Ok(vec![PrimitiveMarker::Signature.into()]) } - fn from_decoded_fields(mut data: Vec>) -> Result { + fn from_decoded_fields(mut data: Vec) -> Result { data.pop().ok_or(Error::NoDecodableFieldPassed)?.try_into() } } -impl<'a> Decodable<'a> for B032<'a> { +impl Decodable for B032 { fn get_structure(_: &[u8]) -> Result, Error> { Ok(vec![PrimitiveMarker::B032.into()]) } - fn from_decoded_fields(mut data: Vec>) -> Result { + fn from_decoded_fields(mut data: Vec) -> Result { data.pop().ok_or(Error::NoDecodableFieldPassed)?.try_into() } } -impl<'a> Decodable<'a> for B0255<'a> { +impl Decodable for B0255 { fn get_structure(_: &[u8]) -> Result, Error> { Ok(vec![PrimitiveMarker::B0255.into()]) } - fn from_decoded_fields(mut data: Vec>) -> Result { + fn from_decoded_fields(mut data: Vec) -> Result { data.pop().ok_or(Error::NoDecodableFieldPassed)?.try_into() } } -impl<'a> Decodable<'a> for B064K<'a> { +impl Decodable for B064K { fn get_structure(_: &[u8]) -> Result, Error> { Ok(vec![PrimitiveMarker::B064K.into()]) } - fn from_decoded_fields(mut data: Vec>) -> Result { + fn from_decoded_fields(mut data: Vec) -> Result { data.pop().ok_or(Error::NoDecodableFieldPassed)?.try_into() } } -impl<'a> Decodable<'a> for B016M<'a> { +impl Decodable for B016M { fn get_structure(_: &[u8]) -> Result, Error> { Ok(vec![PrimitiveMarker::B016M.into()]) } - fn from_decoded_fields(mut data: Vec>) -> Result { + fn from_decoded_fields(mut data: Vec) -> Result { data.pop().ok_or(Error::NoDecodableFieldPassed)?.try_into() } } -impl<'a> Decodable<'a> for U32AsRef<'a> { +impl Decodable for U32AsRef { fn get_structure(_: &[u8]) -> Result, Error> { Ok(vec![PrimitiveMarker::U32AsRef.into()]) } - fn from_decoded_fields(mut data: Vec>) -> Result { + fn from_decoded_fields(mut data: Vec) -> Result { data.pop().ok_or(Error::NoDecodableFieldPassed)?.try_into() } } // IMPL TRY_FROM PRIMITIVE FOR PRIMITIVEs -impl<'a> TryFrom> for u8 { +impl TryFrom for u8 { type Error = Error; - fn try_from(value: DecodablePrimitive<'a>) -> Result { + fn try_from(value: DecodablePrimitive) -> Result { match value { DecodablePrimitive::U8(val) => Ok(val), _ => Err(Error::PrimitiveConversionError), } } } -impl<'a> TryFrom> for u16 { +impl TryFrom for u16 { type Error = Error; - fn try_from(value: DecodablePrimitive<'a>) -> Result { + fn try_from(value: DecodablePrimitive) -> Result { match value { DecodablePrimitive::U16(val) => Ok(val), _ => Err(Error::PrimitiveConversionError), } } } -impl<'a> TryFrom> for u32 { +impl TryFrom for u32 { type Error = Error; - fn try_from(value: DecodablePrimitive<'a>) -> Result { + fn try_from(value: DecodablePrimitive) -> Result { match value { DecodablePrimitive::U32(val) => Ok(val), _ => Err(Error::PrimitiveConversionError), } } } -impl<'a> TryFrom> for f32 { +impl TryFrom for f32 { type Error = Error; - fn try_from(value: DecodablePrimitive<'a>) -> Result { + fn try_from(value: DecodablePrimitive) -> Result { match value { DecodablePrimitive::F32(val) => Ok(val), _ => Err(Error::PrimitiveConversionError), } } } -impl<'a> TryFrom> for u64 { +impl TryFrom for u64 { type Error = Error; - fn try_from(value: DecodablePrimitive<'a>) -> Result { + fn try_from(value: DecodablePrimitive) -> Result { match value { DecodablePrimitive::U64(val) => Ok(val), _ => Err(Error::PrimitiveConversionError), } } } -impl<'a> TryFrom> for bool { +impl TryFrom for bool { type Error = Error; - fn try_from(value: DecodablePrimitive<'a>) -> Result { + fn try_from(value: DecodablePrimitive) -> Result { match value { DecodablePrimitive::Bool(val) => Ok(val), _ => Err(Error::PrimitiveConversionError), @@ -276,80 +276,80 @@ impl<'a> TryFrom> for bool { } } -impl<'a> TryFrom> for U24 { +impl TryFrom for U24 { type Error = Error; - fn try_from(value: DecodablePrimitive<'a>) -> Result { + fn try_from(value: DecodablePrimitive) -> Result { match value { DecodablePrimitive::U24(val) => Ok(val), _ => Err(Error::PrimitiveConversionError), } } } -impl<'a> TryFrom> for U256<'a> { +impl TryFrom for U256 { type Error = Error; - fn try_from(value: DecodablePrimitive<'a>) -> Result { + fn try_from(value: DecodablePrimitive) -> Result { match value { DecodablePrimitive::U256(val) => Ok(val), _ => Err(Error::PrimitiveConversionError), } } } -impl<'a> TryFrom> for Signature<'a> { +impl TryFrom for Signature { type Error = Error; - fn try_from(value: DecodablePrimitive<'a>) -> Result { + fn try_from(value: DecodablePrimitive) -> Result { match value { DecodablePrimitive::Signature(val) => Ok(val), _ => Err(Error::PrimitiveConversionError), } } } -impl<'a> TryFrom> for B032<'a> { +impl TryFrom for B032 { type Error = Error; - fn try_from(value: DecodablePrimitive<'a>) -> Result { + fn try_from(value: DecodablePrimitive) -> Result { match value { DecodablePrimitive::B032(val) => Ok(val), _ => Err(Error::PrimitiveConversionError), } } } -impl<'a> TryFrom> for B0255<'a> { +impl TryFrom for B0255 { type Error = Error; - fn try_from(value: DecodablePrimitive<'a>) -> Result { + fn try_from(value: DecodablePrimitive) -> Result { match value { DecodablePrimitive::B0255(val) => Ok(val), _ => Err(Error::PrimitiveConversionError), } } } -impl<'a> TryFrom> for B064K<'a> { +impl TryFrom for B064K { type Error = Error; - fn try_from(value: DecodablePrimitive<'a>) -> Result { + fn try_from(value: DecodablePrimitive) -> Result { match value { DecodablePrimitive::B064K(val) => Ok(val), _ => Err(Error::PrimitiveConversionError), } } } -impl<'a> TryFrom> for B016M<'a> { +impl TryFrom for B016M { type Error = Error; - fn try_from(value: DecodablePrimitive<'a>) -> Result { + fn try_from(value: DecodablePrimitive) -> Result { match value { DecodablePrimitive::B016M(val) => Ok(val), _ => Err(Error::PrimitiveConversionError), } } } -impl<'a> TryFrom> for U32AsRef<'a> { +impl TryFrom for U32AsRef { type Error = Error; - fn try_from(value: DecodablePrimitive<'a>) -> Result { + fn try_from(value: DecodablePrimitive) -> Result { match value { DecodablePrimitive::U32AsRef(val) => Ok(val), _ => Err(Error::PrimitiveConversionError), @@ -359,140 +359,140 @@ impl<'a> TryFrom> for U32AsRef<'a> { // IMPL TRY_FROM DECODEC FIELD FOR PRIMITIVES -impl<'a> TryFrom> for u8 { +impl TryFrom for u8 { type Error = Error; - fn try_from(value: DecodableField<'a>) -> Result { + fn try_from(value: DecodableField) -> Result { match value { DecodableField::Primitive(p) => p.try_into(), _ => Err(Error::DecodableConversionError), } } } -impl<'a> TryFrom> for u16 { +impl TryFrom for u16 { type Error = Error; - fn try_from(value: DecodableField<'a>) -> Result { + fn try_from(value: DecodableField) -> Result { match value { DecodableField::Primitive(p) => p.try_into(), _ => Err(Error::DecodableConversionError), } } } -impl<'a> TryFrom> for u32 { +impl TryFrom for u32 { type Error = Error; - fn try_from(value: DecodableField<'a>) -> Result { + fn try_from(value: DecodableField) -> Result { match value { DecodableField::Primitive(p) => p.try_into(), _ => Err(Error::DecodableConversionError), } } } -impl<'a> TryFrom> for f32 { +impl TryFrom for f32 { type Error = Error; - fn try_from(value: DecodableField<'a>) -> Result { + fn try_from(value: DecodableField) -> Result { match value { DecodableField::Primitive(p) => p.try_into(), _ => Err(Error::DecodableConversionError), } } } -impl<'a> TryFrom> for u64 { +impl TryFrom for u64 { type Error = Error; - fn try_from(value: DecodableField<'a>) -> Result { + fn try_from(value: DecodableField) -> Result { match value { DecodableField::Primitive(p) => p.try_into(), _ => Err(Error::DecodableConversionError), } } } -impl<'a> TryFrom> for bool { +impl TryFrom for bool { type Error = Error; - fn try_from(value: DecodableField<'a>) -> Result { + fn try_from(value: DecodableField) -> Result { match value { DecodableField::Primitive(p) => p.try_into(), _ => Err(Error::DecodableConversionError), } } } -impl<'a> TryFrom> for U24 { +impl TryFrom for U24 { type Error = Error; - fn try_from(value: DecodableField<'a>) -> Result { + fn try_from(value: DecodableField) -> Result { match value { DecodableField::Primitive(p) => p.try_into(), _ => Err(Error::DecodableConversionError), } } } -impl<'a> TryFrom> for U256<'a> { +impl TryFrom for U256 { type Error = Error; - fn try_from(value: DecodableField<'a>) -> Result { + fn try_from(value: DecodableField) -> Result { match value { DecodableField::Primitive(p) => p.try_into(), _ => Err(Error::DecodableConversionError), } } } -impl<'a> TryFrom> for Signature<'a> { +impl TryFrom for Signature { type Error = Error; - fn try_from(value: DecodableField<'a>) -> Result { + fn try_from(value: DecodableField) -> Result { match value { DecodableField::Primitive(p) => p.try_into(), _ => Err(Error::DecodableConversionError), } } } -impl<'a> TryFrom> for B032<'a> { +impl TryFrom for B032 { type Error = Error; - fn try_from(value: DecodableField<'a>) -> Result { + fn try_from(value: DecodableField) -> Result { match value { DecodableField::Primitive(p) => p.try_into(), _ => Err(Error::DecodableConversionError), } } } -impl<'a> TryFrom> for B0255<'a> { +impl TryFrom for B0255 { type Error = Error; - fn try_from(value: DecodableField<'a>) -> Result { + fn try_from(value: DecodableField) -> Result { match value { DecodableField::Primitive(p) => p.try_into(), _ => Err(Error::DecodableConversionError), } } } -impl<'a> TryFrom> for B064K<'a> { +impl TryFrom for B064K { type Error = Error; - fn try_from(value: DecodableField<'a>) -> Result { + fn try_from(value: DecodableField) -> Result { match value { DecodableField::Primitive(p) => p.try_into(), _ => Err(Error::DecodableConversionError), } } } -impl<'a> TryFrom> for B016M<'a> { +impl TryFrom for B016M { type Error = Error; - fn try_from(value: DecodableField<'a>) -> Result { + fn try_from(value: DecodableField) -> Result { match value { DecodableField::Primitive(p) => p.try_into(), _ => Err(Error::DecodableConversionError), } } } -impl<'a> TryFrom> for U32AsRef<'a> { +impl TryFrom for U32AsRef { type Error = Error; - fn try_from(value: DecodableField<'a>) -> Result { + fn try_from(value: DecodableField) -> Result { match value { DecodableField::Primitive(p) => p.try_into(), _ => Err(Error::DecodableConversionError), @@ -502,210 +502,210 @@ impl<'a> TryFrom> for U32AsRef<'a> { // IMPL FROM PRIMITIVES FOR ENCODED FIELD -impl From for EncodableField<'_> { +impl From for EncodableField { fn from(v: bool) -> Self { EncodableField::Primitive(EncodablePrimitive::Bool(v)) } } -impl<'a> TryFrom> for bool { +impl TryFrom for bool { type Error = Error; - fn try_from(value: EncodableField<'a>) -> Result { + fn try_from(value: EncodableField) -> Result { match value { EncodableField::Primitive(EncodablePrimitive::Bool(v)) => Ok(v), _ => Err(Error::NonPrimitiveTypeCannotBeEncoded), } } } -impl From for EncodableField<'_> { +impl From for EncodableField { fn from(v: u8) -> Self { EncodableField::Primitive(EncodablePrimitive::U8(v)) } } -impl<'a> TryFrom> for u8 { +impl TryFrom for u8 { type Error = Error; - fn try_from(value: EncodableField<'a>) -> Result { + fn try_from(value: EncodableField) -> Result { match value { EncodableField::Primitive(EncodablePrimitive::U8(v)) => Ok(v), _ => Err(Error::NonPrimitiveTypeCannotBeEncoded), } } } -impl From for EncodableField<'_> { +impl From for EncodableField { fn from(v: u16) -> Self { EncodableField::Primitive(EncodablePrimitive::U16(v)) } } -impl<'a> TryFrom> for u16 { +impl TryFrom for u16 { type Error = Error; - fn try_from(value: EncodableField<'a>) -> Result { + fn try_from(value: EncodableField) -> Result { match value { EncodableField::Primitive(EncodablePrimitive::U16(v)) => Ok(v), _ => Err(Error::NonPrimitiveTypeCannotBeEncoded), } } } -impl From for EncodableField<'_> { +impl From for EncodableField { fn from(v: U24) -> Self { EncodableField::Primitive(EncodablePrimitive::U24(v)) } } -impl<'a> TryFrom> for U24 { +impl TryFrom for U24 { type Error = Error; - fn try_from(value: EncodableField<'a>) -> Result { + fn try_from(value: EncodableField) -> Result { match value { EncodableField::Primitive(EncodablePrimitive::U24(v)) => Ok(v), _ => Err(Error::NonPrimitiveTypeCannotBeEncoded), } } } -impl From for EncodableField<'_> { +impl From for EncodableField { fn from(v: u32) -> Self { EncodableField::Primitive(EncodablePrimitive::U32(v)) } } -impl<'a> TryFrom> for u32 { +impl TryFrom for u32 { type Error = Error; - fn try_from(value: EncodableField<'a>) -> Result { + fn try_from(value: EncodableField) -> Result { match value { EncodableField::Primitive(EncodablePrimitive::U32(v)) => Ok(v), _ => Err(Error::NonPrimitiveTypeCannotBeEncoded), } } } -impl From for EncodableField<'_> { +impl From for EncodableField { fn from(v: f32) -> Self { EncodableField::Primitive(EncodablePrimitive::F32(v)) } } -impl<'a> TryFrom> for f32 { +impl TryFrom for f32 { type Error = Error; - fn try_from(value: EncodableField<'a>) -> Result { + fn try_from(value: EncodableField) -> Result { match value { EncodableField::Primitive(EncodablePrimitive::F32(v)) => Ok(v), _ => Err(Error::NonPrimitiveTypeCannotBeEncoded), } } } -impl From for EncodableField<'_> { +impl From for EncodableField { fn from(v: u64) -> Self { EncodableField::Primitive(EncodablePrimitive::U64(v)) } } -impl<'a> TryFrom> for u64 { +impl TryFrom for u64 { type Error = Error; - fn try_from(value: EncodableField<'a>) -> Result { + fn try_from(value: EncodableField) -> Result { match value { EncodableField::Primitive(EncodablePrimitive::U64(v)) => Ok(v), _ => Err(Error::NonPrimitiveTypeCannotBeEncoded), } } } -impl<'a> From> for EncodableField<'a> { - fn from(v: U256<'a>) -> Self { +impl From for EncodableField { + fn from(v: U256) -> Self { EncodableField::Primitive(EncodablePrimitive::U256(v)) } } -impl<'a> TryFrom> for U256<'a> { +impl TryFrom for U256 { type Error = Error; - fn try_from(value: EncodableField<'a>) -> Result { + fn try_from(value: EncodableField) -> Result { match value { EncodableField::Primitive(EncodablePrimitive::U256(v)) => Ok(v), _ => Err(Error::NonPrimitiveTypeCannotBeEncoded), } } } -impl<'a> From> for EncodableField<'a> { - fn from(v: Signature<'a>) -> Self { +impl From for EncodableField { + fn from(v: Signature) -> Self { EncodableField::Primitive(EncodablePrimitive::Signature(v)) } } -impl<'a> TryFrom> for Signature<'a> { +impl TryFrom for Signature { type Error = Error; - fn try_from(value: EncodableField<'a>) -> Result { + fn try_from(value: EncodableField) -> Result { match value { EncodableField::Primitive(EncodablePrimitive::Signature(v)) => Ok(v), _ => Err(Error::NonPrimitiveTypeCannotBeEncoded), } } } -impl<'a> From> for EncodableField<'a> { - fn from(v: B032<'a>) -> Self { +impl From for EncodableField { + fn from(v: B032) -> Self { EncodableField::Primitive(EncodablePrimitive::B032(v)) } } -impl<'a> From> for EncodableField<'a> { - fn from(v: B0255<'a>) -> Self { +impl From for EncodableField { + fn from(v: B0255) -> Self { EncodableField::Primitive(EncodablePrimitive::B0255(v)) } } -impl<'a> TryFrom> for B032<'a> { +impl TryFrom for B032 { type Error = Error; - fn try_from(value: EncodableField<'a>) -> Result { + fn try_from(value: EncodableField) -> Result { match value { EncodableField::Primitive(EncodablePrimitive::B032(v)) => Ok(v), _ => Err(Error::NonPrimitiveTypeCannotBeEncoded), } } } -impl<'a> TryFrom> for B0255<'a> { +impl TryFrom for B0255 { type Error = Error; - fn try_from(value: EncodableField<'a>) -> Result { + fn try_from(value: EncodableField) -> Result { match value { EncodableField::Primitive(EncodablePrimitive::B0255(v)) => Ok(v), _ => Err(Error::NonPrimitiveTypeCannotBeEncoded), } } } -impl<'a> From> for EncodableField<'a> { - fn from(v: B064K<'a>) -> Self { +impl From for EncodableField { + fn from(v: B064K) -> Self { EncodableField::Primitive(EncodablePrimitive::B064K(v)) } } -impl<'a> TryFrom> for B064K<'a> { +impl TryFrom for B064K { type Error = Error; - fn try_from(value: EncodableField<'a>) -> Result { + fn try_from(value: EncodableField) -> Result { match value { EncodableField::Primitive(EncodablePrimitive::B064K(v)) => Ok(v), _ => Err(Error::NonPrimitiveTypeCannotBeEncoded), } } } -impl<'a> From> for EncodableField<'a> { - fn from(v: B016M<'a>) -> Self { +impl From for EncodableField { + fn from(v: B016M) -> Self { EncodableField::Primitive(EncodablePrimitive::B016M(v)) } } -impl<'a> TryFrom> for B016M<'a> { +impl TryFrom for B016M { type Error = Error; - fn try_from(value: EncodableField<'a>) -> Result { + fn try_from(value: EncodableField) -> Result { match value { EncodableField::Primitive(EncodablePrimitive::B016M(v)) => Ok(v), _ => Err(Error::NonPrimitiveTypeCannotBeEncoded), } } } -impl<'a> From> for EncodableField<'a> { - fn from(v: U32AsRef<'a>) -> Self { +impl From for EncodableField { + fn from(v: U32AsRef) -> Self { EncodableField::Primitive(EncodablePrimitive::U32AsRef(v)) } } -impl<'a> TryFrom> for U32AsRef<'a> { +impl TryFrom for U32AsRef { type Error = Error; - fn try_from(value: EncodableField<'a>) -> Result { + fn try_from(value: EncodableField) -> Result { match value { EncodableField::Primitive(EncodablePrimitive::U32AsRef(v)) => Ok(v), _ => Err(Error::NonPrimitiveTypeCannotBeEncoded), @@ -755,43 +755,43 @@ impl From for FieldMarker { } } -impl<'a> From> for FieldMarker { - fn from(_: Inner<'a, true, 32, 0, 0>) -> Self { +impl From> for FieldMarker { + fn from(_: Inner) -> Self { FieldMarker::Primitive(PrimitiveMarker::U256) } } -impl<'a> From> for FieldMarker { - fn from(_: Inner<'a, true, 64, 0, 0>) -> Self { +impl From> for FieldMarker { + fn from(_: Inner) -> Self { FieldMarker::Primitive(PrimitiveMarker::Signature) } } -impl<'a> From> for FieldMarker { - fn from(_: B032<'a>) -> Self { +impl From for FieldMarker { + fn from(_: B032) -> Self { FieldMarker::Primitive(PrimitiveMarker::B032) } } -impl<'a> From> for FieldMarker { - fn from(_: Inner<'a, false, 1, 1, 255>) -> Self { +impl From> for FieldMarker { + fn from(_: Inner) -> Self { FieldMarker::Primitive(PrimitiveMarker::B0255) } } -impl<'a> From> for FieldMarker { - fn from(_: Inner<'a, false, 1, 2, { 2_usize.pow(16) - 1 }>) -> Self { +impl From> for FieldMarker { + fn from(_: Inner) -> Self { FieldMarker::Primitive(PrimitiveMarker::B064K) } } -impl<'a> From> for FieldMarker { - fn from(_: Inner<'a, false, 1, 3, { 2_usize.pow(24) - 1 }>) -> Self { +impl From> for FieldMarker { + fn from(_: Inner) -> Self { FieldMarker::Primitive(PrimitiveMarker::B016M) } } -impl<'a> From> for FieldMarker { - fn from(_: U32AsRef<'a>) -> Self { +impl From for FieldMarker { + fn from(_: U32AsRef) -> Self { FieldMarker::Primitive(PrimitiveMarker::U32AsRef) } } diff --git a/sv2/binary-sv2/src/datatypes/copy_data_types.rs b/sv2/binary-sv2/src/datatypes/copy_data_types.rs index 56db4a79f5..02cff2c879 100644 --- a/sv2/binary-sv2/src/datatypes/copy_data_types.rs +++ b/sv2/binary-sv2/src/datatypes/copy_data_types.rs @@ -41,8 +41,8 @@ impl Fixed for bool { const SIZE: usize = 1; } -impl<'a> Sv2DataType<'a> for bool { - fn from_bytes_unchecked(data: &'a mut [u8]) -> Self { +impl Sv2DataType for bool { + fn from_bytes_unchecked(data: &mut [u8]) -> Self { match data .first() .map(|x: &u8| x << 7) @@ -72,7 +72,7 @@ impl<'a> Sv2DataType<'a> for bool { Self::from_bytes_(&mut dst) } - fn to_slice_unchecked(&'a self, dst: &mut [u8]) { + fn to_slice_unchecked(&self, dst: &mut [u8]) { match self { true => dst[0] = 1, false => dst[0] = 0, @@ -113,8 +113,8 @@ impl Fixed for u64 { /// serialization and deserialization, ensuring consistency across platforms. macro_rules! impl_sv2_for_unsigned { ($a:ty) => { - impl<'a> Sv2DataType<'a> for $a { - fn from_bytes_unchecked(data: &'a mut [u8]) -> Self { + impl Sv2DataType for $a { + fn from_bytes_unchecked(data: &mut [u8]) -> Self { // unchecked function is fine to panic let a: &[u8; Self::SIZE] = data[0..Self::SIZE].try_into().expect( "Try to decode a copy data type from a buffer that do not have enough bytes", @@ -137,7 +137,7 @@ macro_rules! impl_sv2_for_unsigned { Ok(Self::from_bytes_unchecked(&mut dst)) } - fn to_slice_unchecked(&'a self, dst: &mut [u8]) { + fn to_slice_unchecked(&self, dst: &mut [u8]) { let dst = &mut dst[0..Self::SIZE]; let src = self.to_le_bytes(); dst.copy_from_slice(&src); diff --git a/sv2/binary-sv2/src/datatypes/mod.rs b/sv2/binary-sv2/src/datatypes/mod.rs index 86102ba67f..9bd489e7c9 100644 --- a/sv2/binary-sv2/src/datatypes/mod.rs +++ b/sv2/binary-sv2/src/datatypes/mod.rs @@ -57,18 +57,18 @@ use std::io::{Error as E, Read, Write}; /// /// This trait includes functions for both checked and unchecked conversions, providing flexibility /// in situations where error handling can be safely ignored. -pub trait Sv2DataType<'a>: Sized + SizeHint + GetSize + TryInto { +pub trait Sv2DataType: Sized + SizeHint + GetSize + TryInto { /// Creates an instance of the type from a mutable byte slice, checking for size constraints. /// /// This function verifies that the provided byte slice has the correct size according to the /// type's size hint. - fn from_bytes_(data: &'a mut [u8]) -> Result { + fn from_bytes_(data: &mut [u8]) -> Result { Self::size_hint(data, 0)?; Ok(Self::from_bytes_unchecked(data)) } /// Constructs an instance from a mutable byte slice without verifying size constraints. - fn from_bytes_unchecked(data: &'a mut [u8]) -> Self; + fn from_bytes_unchecked(data: &mut [u8]) -> Self; /// Constructs an instance from a vector, checking for the correct size. fn from_vec_(data: Vec) -> Result; @@ -81,7 +81,7 @@ pub trait Sv2DataType<'a>: Sized + SizeHint + GetSize + TryInto { fn from_reader_(reader: &mut impl Read) -> Result; /// Serializes the instance to a mutable slice, checking the destination size. - fn to_slice(&'a self, dst: &mut [u8]) -> Result { + fn to_slice(&self, dst: &mut [u8]) -> Result { if dst.len() >= self.get_size() { self.to_slice_unchecked(dst); Ok(self.get_size()) @@ -91,7 +91,7 @@ pub trait Sv2DataType<'a>: Sized + SizeHint + GetSize + TryInto { } /// Serializes the instance to a mutable slice without checking the destination size. - fn to_slice_unchecked(&'a self, dst: &mut [u8]); + fn to_slice_unchecked(&self, dst: &mut [u8]); // Serializes the instance to a writer destination, checking for I/O errors. #[cfg(not(feature = "no_std"))] diff --git a/sv2/binary-sv2/src/datatypes/non_copy_data_types/inner.rs b/sv2/binary-sv2/src/datatypes/non_copy_data_types/inner.rs index 0e41134429..faa85421cd 100644 --- a/sv2/binary-sv2/src/datatypes/non_copy_data_types/inner.rs +++ b/sv2/binary-sv2/src/datatypes/non_copy_data_types/inner.rs @@ -1,13 +1,12 @@ -// Provides a flexible container for managing either owned or mutable references to byte arrays. +// Provides a flexible container for managing owned byte arrays. // // # Overview -// Defines the `Inner` enum to manage both mutable references to byte slices and owned vectors -// (`Vec`). Accommodates both fixed-size and variable-size data using const generics, offering -// control over size and header length constraints. +// Defines the `Inner` enum to manage owned vectors (`Vec`). Accommodates both fixed-size and +// variable-size data using const generics, offering control over size and header length +// constraints. // // # `Inner` Enum -// The `Inner` enum has two variants for data management: -// - `Ref(&'a mut [u8])`: A mutable reference to a byte slice, allowing in-place data modification. +// The `Inner` enum has one variant for data management: // - `Owned(Vec)`: An owned byte vector, providing full control over data and supporting move // semantics. // @@ -21,7 +20,7 @@ // // # Usage // `Inner` offers several methods for data manipulation, including: -// - `to_vec()`: Returns a `Vec`, cloning the slice or owned data. +// - `to_vec()`: Returns a `Vec`, cloning the owned data. // - `inner_as_ref()` and `inner_as_mut()`: Provide immutable or mutable access to the data. // - `expected_length(data: &[u8])`: Computes the expected length, validating it against // constraints. @@ -46,13 +45,11 @@ use core::convert::{TryFrom, TryInto}; #[cfg(not(feature = "no_std"))] use std::io::{Error as E, Read, Write}; -// The `Inner` enum represents a flexible container for managing both reference to mutable -// slices and owned bytes arrays (`Vec`). This design allows the container to either own -// its data or simply reference existing mutable data. It uses const generics to differentiate -// between fixed-size and variable-size data, as well as to specify key size-related parameters. +// The `Inner` enum represents a flexible container for managing owned bytes arrays (`Vec`). +// It uses const generics to differentiate between fixed-size and variable-size data, as well as +// to specify key size-related parameters. // -// It has two variants: -// - `Ref(&'a mut [u8])`: A mutable reference to an external byte slice. +// It has one variant: // - `Owned (Vec)`: A vector that owns its data, enabling dynamic ownership. // // The const parameters that govern the behavior of this enum are: @@ -64,87 +61,71 @@ use std::io::{Error as E, Read, Write}; #[derive(Debug)] pub enum Inner< - 'a, const ISFIXED: bool, const SIZE: usize, const HEADERSIZE: usize, const MAXSIZE: usize, > { - Ref(&'a mut [u8]), Owned(Vec), } -impl Inner<'_, true, SIZE, 0, 0> { - // Converts the inner data to a vector, either by cloning the referenced slice or - // returning a clone of the owned vector. +impl Inner { + // Converts the inner data to a vector by cloning the owned vector. pub fn to_vec(&self) -> Vec { match self { - Inner::Ref(ref_) => ref_.to_vec(), Inner::Owned(v) => v.clone(), } } - // Returns an immutable reference to the inner data, whether it's a reference or - // an owned vector. + // Returns an immutable reference to the inner data. pub fn inner_as_ref(&self) -> &[u8] { match self { - Inner::Ref(ref_) => ref_, Inner::Owned(v) => v, } } - // Provides a mutable reference to the inner data, allowing modification if the - // data is being referenced. + // Provides a mutable reference to the inner data. pub fn inner_as_mut(&mut self) -> &mut [u8] { match self { - Inner::Ref(ref_) => ref_, Inner::Owned(v) => v, } } } impl - Inner<'_, false, SIZE, HEADERSIZE, MAXSIZE> + Inner { // Similar to the fixed-size variant, this method converts the inner data into a vector. - // The data is either cloned from the referenced slice or returned as a clone of the - // owned vector. pub fn to_vec(&self) -> Vec { match self { - Inner::Ref(ref_) => ref_[..].to_vec(), Inner::Owned(v) => v[..].to_vec(), } } - // Returns an immutable reference to the inner data for variable-size types, either - // referencing a slice or an owned vector. + // Returns an immutable reference to the inner data for variable-size types. pub fn inner_as_ref(&self) -> &[u8] { match self { - Inner::Ref(ref_) => &ref_[..], Inner::Owned(v) => &v[..], } } } impl - PartialEq for Inner<'_, ISFIXED, SIZE, HEADERSIZE, MAXSIZE> + PartialEq for Inner { // Provides equality comparison between two `Inner` instances by checking the equality - // of their data, regardless of whether they are references or owned vectors. + // of their data. fn eq(&self, other: &Self) -> bool { match (self, other) { - (Inner::Ref(b), Inner::Owned(a)) => *b == &a[..], - (Inner::Owned(b), Inner::Ref(a)) => *a == &b[..], (Inner::Owned(b), Inner::Owned(a)) => b == a, - (Inner::Ref(b), Inner::Ref(a)) => b == a, } } } impl Eq - for Inner<'_, ISFIXED, SIZE, HEADERSIZE, MAXSIZE> + for Inner { } impl - Inner<'_, ISFIXED, SIZE, HEADERSIZE, MAXSIZE> + Inner { // Calculates the expected length of the data based on the type's parameters (fixed-size // or variable-size). It checks if the length conforms to the specified constraints like @@ -213,11 +194,10 @@ impl usize { match (self, ISFIXED) { - (Inner::Ref(data), false) => data.len(), (Inner::Owned(data), false) => data.len(), (_, true) => 1, } @@ -235,14 +215,14 @@ impl - TryFrom<&'a mut [u8]> for Inner<'a, ISFIXED, SIZE, HEADERSIZE, MAXSIZE> +impl + TryFrom<&mut [u8]> for Inner { type Error = Error; - fn try_from(value: &'a mut [u8]) -> Result { + fn try_from(value: &mut [u8]) -> Result { if ISFIXED && value.len() == SIZE { - Ok(Self::Ref(value)) + Ok(Self::Owned(value.to_vec())) } else if ISFIXED { Err(Error::ValueExceedsMaxSize( ISFIXED, @@ -253,7 +233,7 @@ impl<'a, const ISFIXED: bool, const SIZE: usize, const HEADERSIZE: usize, const value.len(), )) } else if value.len() <= MAXSIZE { - Ok(Self::Ref(value)) + Ok(Self::Owned(value.to_vec())) } else { Err(Error::ValueExceedsMaxSize( ISFIXED, @@ -268,7 +248,7 @@ impl<'a, const ISFIXED: bool, const SIZE: usize, const HEADERSIZE: usize, const } impl - TryFrom> for Inner<'_, ISFIXED, SIZE, HEADERSIZE, MAXSIZE> + TryFrom> for Inner { type Error = Error; @@ -300,18 +280,17 @@ impl GetSize - for Inner<'_, ISFIXED, SIZE, HEADERSIZE, MAXSIZE> + for Inner { fn get_size(&self) -> usize { match self { - Inner::Ref(data) => data.len() + HEADERSIZE, Inner::Owned(data) => data.len() + HEADERSIZE, } } } impl SizeHint - for Inner<'_, ISFIXED, HEADERSIZE, SIZE, MAXSIZE> + for Inner { fn size_hint(data: &[u8], offset: usize) -> Result { if offset >= data.len() { @@ -329,16 +308,16 @@ impl - Sv2DataType<'a> for Inner<'a, ISFIXED, SIZE, HEADERSIZE, MAXSIZE> +impl + Sv2DataType for Inner where Self: TryInto, { - fn from_bytes_unchecked(data: &'a mut [u8]) -> Self { + fn from_bytes_unchecked(data: &mut [u8]) -> Self { if ISFIXED { - Self::Ref(data) + Self::Owned(data[..SIZE].to_vec()) } else { - Self::Ref(&mut data[HEADERSIZE..]) + Self::Owned(data[HEADERSIZE..].to_vec()) } } @@ -361,15 +340,11 @@ where Ok(Self::from_vec_unchecked(dst)) } - fn to_slice_unchecked(&'a self, dst: &mut [u8]) { + fn to_slice_unchecked(&self, dst: &mut [u8]) { let size = self.get_size(); let header = self.get_header(); dst[0..HEADERSIZE].copy_from_slice(&header[..HEADERSIZE]); match self { - Inner::Ref(data) => { - let dst = &mut dst[0..size]; - dst[HEADERSIZE..].copy_from_slice(data); - } Inner::Owned(data) => { let dst = &mut dst[0..size]; dst[HEADERSIZE..].copy_from_slice(data); @@ -380,9 +355,6 @@ where #[cfg(not(feature = "no_std"))] fn to_writer_(&self, writer: &mut impl Write) -> Result<(), E> { match self { - Inner::Ref(data) => { - writer.write_all(data)?; - } Inner::Owned(data) => { writer.write_all(data)?; } @@ -392,55 +364,36 @@ where } impl - IntoOwned for Inner<'_, ISFIXED, SIZE, HEADERSIZE, MAXSIZE> + IntoOwned for Inner { fn into_owned(self) -> Self { - match self { - Inner::Ref(data) => { - let v: Vec = data.into(); - Self::Owned(v) - } - Inner::Owned(_) => self, - } + self } } impl - Inner<'_, ISFIXED, SIZE, HEADERSIZE, MAXSIZE> + Inner { - pub fn into_static(self) -> Inner<'static, ISFIXED, SIZE, HEADERSIZE, MAXSIZE> { - match self { - Inner::Ref(data) => { - let mut v = Vec::with_capacity(data.len()); - v.extend_from_slice(data); - Inner::Owned(v) - } - Inner::Owned(data) => Inner::Owned(data), - } + pub fn into_static(self) -> Inner { + self } } impl Clone - for Inner<'_, ISFIXED, SIZE, HEADERSIZE, MAXSIZE> + for Inner { - fn clone(&self) -> Inner<'static, ISFIXED, SIZE, HEADERSIZE, MAXSIZE> { + fn clone(&self) -> Inner { match self { - Inner::Ref(data) => { - let mut v = Vec::with_capacity(data.len()); - v.extend_from_slice(data); - Inner::Owned(v) - } Inner::Owned(data) => Inner::Owned(data.clone()), } } } impl - AsRef<[u8]> for Inner<'_, ISFIXED, SIZE, HEADERSIZE, MAXSIZE> + AsRef<[u8]> for Inner { fn as_ref(&self) -> &[u8] { match self { - Inner::Ref(r) => &r[..], Inner::Owned(r) => &r[..], } } diff --git a/sv2/binary-sv2/src/datatypes/non_copy_data_types/mod.rs b/sv2/binary-sv2/src/datatypes/non_copy_data_types/mod.rs index fc2c3d75e6..2c892d0669 100644 --- a/sv2/binary-sv2/src/datatypes/non_copy_data_types/mod.rs +++ b/sv2/binary-sv2/src/datatypes/non_copy_data_types/mod.rs @@ -1,8 +1,8 @@ // Provides a flexible, low-level interface for representing fixed-size and variable-size byte // arrays, simplifying serialization and deserialization of cryptographic and protocol data. // -// The core component is the [`Inner`] type, a wrapper for managing both fixed and variable-length -// data slices or owned values. It offers aliases for commonly used data types like 32-byte hashes +// The core component is the [`Inner`] type, a wrapper for managing fixed and variable-length +// owned data. It offers aliases for commonly used data types like 32-byte hashes // (`U256`), public keys (`PubKey`), cryptographic signatures (`Signature`), and dynamically-sized // arrays (`B0255`, `B064K`). @@ -12,7 +12,7 @@ // - **Variable-size Aliases**: Types like [`B032`], [`B0255`], [`Str0255`], [`B064K`], and // [`B016M`] handle data with bounded sizes, providing flexibility for dynamic data. // - **Traits and Conversions**: Implements traits like `From`, `TryFrom`, and [`IntoOwned`] for -// seamless transformations between owned and reference-based values. +// seamless transformations between owned values. // - **Property Testing** (optional, requires the `prop_test` feature): Supports generating // arbitrary test data for property-based testing. @@ -48,33 +48,33 @@ pub use seq_inner::{Seq0255, Seq064K, Sv2Option}; /// Type alias for a 4-byte slice or owned data represented using the `Inner` /// type with fixed-size configuration. -pub type U32AsRef<'a> = Inner<'a, true, 4, 0, 0>; +pub type U32AsRef = Inner; /// Type alias for a 32-byte slice or owned data (commonly used for cryptographic /// hashes or IDs) represented using the `Inner` type with fixed-size configuration. -pub type U256<'a> = Inner<'a, true, 32, 0, 0>; +pub type U256 = Inner; /// Type alias for a 32-byte public key represented using the `Inner` type /// with fixed-size configuration. -pub type PubKey<'a> = Inner<'a, true, 32, 0, 0>; +pub type PubKey = Inner; /// Type alias for a 64-byte cryptographic signature represented using the /// `Inner` type with fixed-size configuration. -pub type Signature<'a> = Inner<'a, true, 64, 0, 0>; +pub type Signature = Inner; /// Type alias for a variable-sized byte array with a maximum size of 32 bytes, /// represented using the `Inner` type with a 1-byte header. -pub type B032<'a> = Inner<'a, false, 1, 1, 32>; +pub type B032 = Inner; /// Type alias for a variable-sized byte array with a maximum size of 255 bytes, /// represented using the `Inner` type with a 1-byte header. -pub type B0255<'a> = Inner<'a, false, 1, 1, 255>; +pub type B0255 = Inner; /// Type alias for a variable-sized string with a maximum size of 255 bytes, /// represented using the `Inner` type with a 1-byte header. -pub type Str0255<'a> = Inner<'a, false, 1, 1, 255>; +pub type Str0255 = Inner; /// Type alias for a variable-sized byte array with a maximum size of 64 KB, /// represented using the `Inner` type with a 2-byte header. -pub type B064K<'a> = Inner<'a, false, 1, 2, { u16::MAX as usize }>; +pub type B064K = Inner; /// Type alias for a variable-sized byte array with a maximum size of ~16 MB, /// represented using the `Inner` type with a 3-byte header. -pub type B016M<'a> = Inner<'a, false, 1, 3, { 2_usize.pow(24) - 1 }>; +pub type B016M = Inner; -impl fmt::Display for U32AsRef<'_> { +impl fmt::Display for U32AsRef { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let inner = self.inner_as_ref(); write!( @@ -85,8 +85,8 @@ impl fmt::Display for U32AsRef<'_> { } } -impl fmt::Display for Sv2Option<'_, u32> { - // internally Sv2Option is pub struct Sv2Option<'a, T>(pub Vec, PhantomData<&'a T>); +impl fmt::Display for Sv2Option { + // internally Sv2Option is pub struct Sv2Option(pub Vec); fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let inner = self.to_owned().into_inner(); match inner { @@ -96,7 +96,7 @@ impl fmt::Display for Sv2Option<'_, u32> { } } -impl B0255<'_> { +impl B0255 { pub fn as_hex(&self) -> String { let inner = self .inner_as_ref() @@ -107,7 +107,7 @@ impl B0255<'_> { } } -impl Str0255<'_> { +impl Str0255 { /// Returns the value as a UTF-8 string if possible, otherwise as a hex string prefixed with 0x. pub fn as_utf8_or_hex(&self) -> String { match core::str::from_utf8(self.inner_as_ref()) { @@ -123,7 +123,7 @@ impl Str0255<'_> { } } -impl fmt::Display for B064K<'_> { +impl fmt::Display for B064K { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let inner = self .inner_as_ref() @@ -134,7 +134,7 @@ impl fmt::Display for B064K<'_> { } } -impl fmt::Display for U256<'_> { +impl fmt::Display for U256 { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let inner = self .inner_as_ref() @@ -146,10 +146,10 @@ impl fmt::Display for U256<'_> { } } -impl fmt::Display for Seq0255<'_, U256<'_>> { +impl fmt::Display for Seq0255 { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let len = self.0.len(); - let as_hex = |item: &U256<'_>| { + let as_hex = |item: &U256| { item.inner_as_ref() .iter() .rev() @@ -180,11 +180,11 @@ impl fmt::Display for Seq0255<'_, U256<'_>> { } } -impl fmt::Display for Seq064K<'_, B016M<'_>> { +impl fmt::Display for Seq064K { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let len = self.0.len(); - let as_hex = |item: &B016M<'_>| { + let as_hex = |item: &B016M| { let hex: String = item .inner_as_ref() .iter() @@ -222,10 +222,10 @@ impl fmt::Display for Seq064K<'_, B016M<'_>> { } } -impl fmt::Display for Seq064K<'_, U256<'_>> { +impl fmt::Display for Seq064K { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let len = self.0.len(); - let as_hex = |item: &U256<'_>| { + let as_hex = |item: &U256| { item.inner_as_ref() .iter() .map(|byte| format!("{byte:02x}")) @@ -255,7 +255,7 @@ impl fmt::Display for Seq064K<'_, U256<'_>> { } } -impl fmt::Display for Seq064K<'_, u16> { +impl fmt::Display for Seq064K { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let len = self.0.len(); write!(f, "Seq064K { } } } -impl fmt::Display for Seq064K<'_, u32> { +impl fmt::Display for Seq064K { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let len = self.0.len(); write!(f, "Seq064K { } } -impl fmt::Display for B032<'_> { +impl fmt::Display for B032 { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let item = self .inner_as_ref() @@ -307,14 +307,14 @@ impl fmt::Display for B032<'_> { } } -impl From<[u8; 32]> for U256<'_> { +impl From<[u8; 32]> for U256 { fn from(v: [u8; 32]) -> Self { Inner::Owned(v.into()) } } #[cfg(feature = "prop_test")] -impl<'a> U256<'a> { +impl U256 { pub fn from_gen(g: &mut Gen) -> Self { let mut inner = Vec::::arbitrary(g); inner.resize(32, 0); @@ -325,7 +325,7 @@ impl<'a> U256<'a> { } #[cfg(feature = "prop_test")] -impl<'a> B016M<'a> { +impl B016M { pub fn from_gen(g: &mut Gen) -> Self { // This can fail but is used only for tests purposes Vec::::arbitrary(g).try_into().unwrap() @@ -334,8 +334,8 @@ impl<'a> B016M<'a> { use core::convert::{TryFrom, TryInto}; -// Attempts to convert a `String` into a `Str0255<'a>`. -impl TryFrom for Str0255<'_> { +// Attempts to convert a `String` into a `Str0255`. +impl TryFrom for Str0255 { type Error = crate::Error; fn try_from(value: String) -> Result { @@ -345,7 +345,7 @@ impl TryFrom for Str0255<'_> { /// Represents a reference to a 32-bit unsigned integer (`u32`), /// providing methods for convenient conversions. -impl U32AsRef<'_> { +impl U32AsRef { /// Returns the `u32` value represented by this reference. pub fn as_u32(&self) -> u32 { let inner = self.inner_as_ref(); @@ -353,7 +353,7 @@ impl U32AsRef<'_> { } } -impl From for U32AsRef<'_> { +impl From for U32AsRef { fn from(v: u32) -> Self { let bytes = v.to_le_bytes(); let inner = vec![bytes[0], bytes[1], bytes[2], bytes[3]]; @@ -361,8 +361,8 @@ impl From for U32AsRef<'_> { } } -impl<'a> From<&'a U32AsRef<'a>> for u32 { - fn from(v: &'a U32AsRef<'a>) -> Self { +impl From<&U32AsRef> for u32 { + fn from(v: &U32AsRef) -> Self { let b = v.inner_as_ref(); u32::from_le_bytes([b[0], b[1], b[2], b[3]]) } diff --git a/sv2/binary-sv2/src/datatypes/non_copy_data_types/seq_inner.rs b/sv2/binary-sv2/src/datatypes/non_copy_data_types/seq_inner.rs index 7360fd9b46..a0f2064d89 100644 --- a/sv2/binary-sv2/src/datatypes/non_copy_data_types/seq_inner.rs +++ b/sv2/binary-sv2/src/datatypes/non_copy_data_types/seq_inner.rs @@ -52,11 +52,10 @@ use crate::{ datatypes::{Sv2DataType, *}, Error, }; -use core::marker::PhantomData; // TODO add test for that -impl<'a, const SIZE: usize, const HEADERSIZE: usize, const MAXSIZE: usize> - Seq0255<'a, super::inner::Inner<'a, false, SIZE, HEADERSIZE, MAXSIZE>> +impl + Seq0255> { /// Converts the inner types to owned vector, and collects. pub fn to_vec(&self) -> Vec> { @@ -69,7 +68,7 @@ impl<'a, const SIZE: usize, const HEADERSIZE: usize, const MAXSIZE: usize> } // TODO add test for that -impl<'a, const SIZE: usize> Seq0255<'a, super::inner::Inner<'a, true, SIZE, 0, 0>> { +impl Seq0255> { /// Converts the inner types to owned vector, and collects. pub fn to_vec(&self) -> Vec> { self.0.iter().map(|x| x.to_vec()).collect() @@ -81,8 +80,8 @@ impl<'a, const SIZE: usize> Seq0255<'a, super::inner::Inner<'a, true, SIZE, 0, 0 } } // TODO add test for that -impl<'a, const SIZE: usize, const HEADERSIZE: usize, const MAXSIZE: usize> - Seq064K<'a, super::inner::Inner<'a, false, SIZE, HEADERSIZE, MAXSIZE>> +impl + Seq064K> { /// Converts the inner types to owned vector, and collects. pub fn to_vec(&self) -> Vec> { @@ -96,7 +95,7 @@ impl<'a, const SIZE: usize, const HEADERSIZE: usize, const MAXSIZE: usize> } // TODO add test for that -impl<'a, const SIZE: usize> Seq064K<'a, super::inner::Inner<'a, true, SIZE, 0, 0>> { +impl Seq064K> { /// Converts the inner types to owned vector, and collects. pub fn to_vec(&self) -> Vec> { self.0.iter().map(|x| x.to_vec()).collect() @@ -112,12 +111,11 @@ impl<'a, const SIZE: usize> Seq064K<'a, super::inner::Inner<'a, true, SIZE, 0, 0 use std::io::Read; /// [`Seq0255`] represents a sequence with a maximum length of 255 elements. -/// This structure uses a generic type `T` and a lifetime parameter `'a`. #[derive(Debug, Clone, Eq, PartialEq)] -pub struct Seq0255<'a, T>(pub Vec, PhantomData<&'a T>); +pub struct Seq0255(pub Vec); -impl<'a, T: 'a> Seq0255<'a, T> { +impl Seq0255 { const HEADERSIZE: usize = 1; // Determines the expected length of the sequence by examining the first byte of `data`. @@ -132,7 +130,7 @@ impl<'a, T: 'a> Seq0255<'a, T> { /// Creates a new `Seq0255` instance with the given inner vector. pub fn new(inner: Vec) -> Result { if inner.len() <= 255 { - Ok(Self(inner, PhantomData)) + Ok(Self(inner)) } else { Err(Error::SeqExceedsMaxSize) } @@ -144,7 +142,7 @@ impl<'a, T: 'a> Seq0255<'a, T> { } } -impl GetSize for Seq0255<'_, T> { +impl GetSize for Seq0255 { // Calculates the total size of the sequence in bytes. fn get_size(&self) -> usize { let mut size = Self::HEADERSIZE; @@ -156,11 +154,10 @@ impl GetSize for Seq0255<'_, T> { } /// [`Seq064K`] represents a sequence with a maximum length of 65535 elements. -/// This structure uses a generic type `T` and a lifetime parameter `'a`. #[derive(Debug, Clone, Eq, PartialEq)] -pub struct Seq064K<'a, T>(pub(crate) Vec, PhantomData<&'a T>); +pub struct Seq064K(pub Vec); -impl<'a, T: 'a> Seq064K<'a, T> { +impl Seq064K { const HEADERSIZE: usize = 2; // Determines the expected length of the sequence by examining the first two bytes of `data`. @@ -175,7 +172,7 @@ impl<'a, T: 'a> Seq064K<'a, T> { /// Creates a new `Seq064K` instance with the given inner vector. pub fn new(inner: Vec) -> Result { if inner.len() <= 65535 { - Ok(Self(inner, PhantomData)) + Ok(Self(inner)) } else { Err(Error::SeqExceedsMaxSize) } @@ -187,7 +184,7 @@ impl<'a, T: 'a> Seq064K<'a, T> { } } -impl GetSize for Seq064K<'_, T> { +impl GetSize for Seq064K { fn get_size(&self) -> usize { let mut size = Self::HEADERSIZE; for with_size in &self.0 { @@ -201,9 +198,7 @@ impl GetSize for Seq064K<'_, T> { /// `Sv2Option`). macro_rules! impl_codec_for_sequence { ($a:ty) => { - impl<'a, T: 'a + Sv2DataType<'a> + GetMarker + GetSize + Decodable<'a>> Decodable<'a> - for $a - { + impl Decodable for $a { fn get_structure( data: &[u8], ) -> Result, Error> { @@ -218,7 +213,7 @@ macro_rules! impl_codec_for_sequence { } fn from_decoded_fields( - data: Vec>, + data: Vec, ) -> Result { let mut inner: Vec = Vec::with_capacity(data.len()); let mut i = 0; @@ -236,10 +231,10 @@ macro_rules! impl_codec_for_sequence { } i += 1; } - Ok(Self(inner, PhantomData)) + Ok(Self(inner)) } - fn from_bytes(data: &'a mut [u8]) -> Result { + fn from_bytes(data: &mut [u8]) -> Result { let len = Self::expected_len(data)?; let mut inner = Vec::new(); @@ -254,7 +249,7 @@ macro_rules! impl_codec_for_sequence { tail = t; inner.push(T::from_bytes_unchecked(head)); } - Ok(Self(inner, PhantomData)) + Ok(Self(inner)) } #[cfg(not(feature = "no_std"))] @@ -269,24 +264,24 @@ macro_rules! impl_codec_for_sequence { for _ in 0..len { inner.push(T::from_reader_(reader)?); } - Ok(Self(inner, PhantomData)) + Ok(Self(inner)) } } }; } // Implementations for encoding/decoding -impl_codec_for_sequence!(Seq0255<'a, T>); -impl_codec_for_sequence!(Seq064K<'a, T>); -impl_codec_for_sequence!(Sv2Option<'a, T>); +impl_codec_for_sequence!(Seq0255); +impl_codec_for_sequence!(Seq064K); +impl_codec_for_sequence!(Sv2Option); /// The `impl_into_encodable_field_for_seq` macro provides implementations of the `From` trait /// to convert `Seq0255`, `Seq064K`, and `Sv2Option` types into `EncodableField`, making these /// sequence types compatible with encoding. macro_rules! impl_into_encodable_field_for_seq { ($a:ty) => { - impl<'a> From> for EncodableField<'a> { - fn from(v: Seq064K<'a, $a>) -> Self { + impl From> for EncodableField { + fn from(v: Seq064K<$a>) -> Self { let inner_len = v.0.len() as u16; let mut as_encodable: Vec = Vec::with_capacity(inner_len as usize + 2); @@ -303,7 +298,7 @@ macro_rules! impl_into_encodable_field_for_seq { } } - impl<'a> From> for EncodableField<'a> { + impl From> for EncodableField { fn from(v: Seq0255<$a>) -> Self { let inner_len = v.0.len() as u8; let mut as_encodable: Vec = @@ -318,7 +313,7 @@ macro_rules! impl_into_encodable_field_for_seq { } } - impl<'a> From> for EncodableField<'a> { + impl From> for EncodableField { fn from(v: Sv2Option<$a>) -> Self { let inner_len = v.0.len() as u8; let mut as_encodable: Vec = @@ -341,16 +336,16 @@ impl_into_encodable_field_for_seq!(u16); impl_into_encodable_field_for_seq!(U24); impl_into_encodable_field_for_seq!(u32); impl_into_encodable_field_for_seq!(u64); -impl_into_encodable_field_for_seq!(U256<'a>); -impl_into_encodable_field_for_seq!(Signature<'a>); -impl_into_encodable_field_for_seq!(B0255<'a>); -impl_into_encodable_field_for_seq!(B064K<'a>); -impl_into_encodable_field_for_seq!(B016M<'a>); +impl_into_encodable_field_for_seq!(U256); +impl_into_encodable_field_for_seq!(Signature); +impl_into_encodable_field_for_seq!(B0255); +impl_into_encodable_field_for_seq!(B064K); +impl_into_encodable_field_for_seq!(B016M); #[cfg(feature = "prop_test")] -impl<'a, T> core::convert::TryFrom> for Vec { +impl core::convert::TryFrom> for Vec { type Error = &'static str; - fn try_from(v: Seq0255<'a, T>) -> Result { + fn try_from(v: Seq0255) -> Result { if v.0.len() > 255 { Ok(v.0) } else { @@ -360,9 +355,9 @@ impl<'a, T> core::convert::TryFrom> for Vec { } #[cfg(feature = "prop_test")] -impl<'a, T> core::convert::TryFrom> for Vec { +impl core::convert::TryFrom> for Vec { type Error = &'static str; - fn try_from(v: Seq064K<'a, T>) -> Result { + fn try_from(v: Seq064K) -> Result { if v.0.len() > 64 { Ok(v.0) } else { @@ -371,39 +366,37 @@ impl<'a, T> core::convert::TryFrom> for Vec { } } -impl From> for Seq0255<'_, T> { +impl From> for Seq0255 { fn from(v: Vec) -> Self { - Seq0255(v, PhantomData) + Seq0255(v) } } -impl From> for Seq064K<'_, T> { +impl From> for Seq064K { fn from(v: Vec) -> Self { - Seq064K(v, PhantomData) + Seq064K(v) } } -impl Seq0255<'_, T> { - /// converts the lifetime to static - pub fn into_static(self) -> Seq0255<'static, T> { +impl Seq0255 { + /// converts the lifetime to static (no-op, always owned) + pub fn into_static(self) -> Seq0255 { // Safe unwrap cause the initial value is a valid Seq0255 Seq0255::new(self.0).unwrap() } } -impl Sv2Option<'_, T> { - /// converts the lifetime to static - pub fn into_static(self) -> Sv2Option<'static, T> { +impl Sv2Option { + /// converts the lifetime to static (no-op, always owned) + pub fn into_static(self) -> Sv2Option { Sv2Option::new(self.into_inner()) } } -impl<'a, const ISFIXED: bool, const SIZE: usize, const HEADERSIZE: usize, const MAXSIZE: usize> - Seq0255<'a, Inner<'a, ISFIXED, SIZE, HEADERSIZE, MAXSIZE>> +impl + Seq0255> { - /// converts the lifetime to static - pub fn into_static( - self, - ) -> Seq0255<'static, Inner<'static, ISFIXED, SIZE, HEADERSIZE, MAXSIZE>> { + /// converts the lifetime to static (no-op, always owned) + pub fn into_static(self) -> Seq0255> { let seq = self.0; let static_seq = seq.into_iter().map(|x| x.into_static()).collect(); // Safe unwrap cause the initial value is a valid Seq0255 @@ -411,34 +404,30 @@ impl<'a, const ISFIXED: bool, const SIZE: usize, const HEADERSIZE: usize, const } } -impl<'a, const ISFIXED: bool, const SIZE: usize, const HEADERSIZE: usize, const MAXSIZE: usize> - Sv2Option<'a, Inner<'a, ISFIXED, SIZE, HEADERSIZE, MAXSIZE>> +impl + Sv2Option> { - /// converts the lifetime to static - pub fn into_static( - self, - ) -> Sv2Option<'static, Inner<'static, ISFIXED, SIZE, HEADERSIZE, MAXSIZE>> { + /// converts the lifetime to static (no-op, always owned) + pub fn into_static(self) -> Sv2Option> { let inner = self.into_inner(); let static_inner = inner.map(|x| x.into_static()); Sv2Option::new(static_inner) } } -impl Seq064K<'_, T> { - /// converts the lifetime to static - pub fn into_static(self) -> Seq064K<'static, T> { +impl Seq064K { + /// converts the lifetime to static (no-op, always owned) + pub fn into_static(self) -> Seq064K { // Safe unwrap cause the initial value is a valid Seq064K Seq064K::new(self.0).unwrap() } } -impl<'a, const ISFIXED: bool, const SIZE: usize, const HEADERSIZE: usize, const MAXSIZE: usize> - Seq064K<'a, Inner<'a, ISFIXED, SIZE, HEADERSIZE, MAXSIZE>> +impl + Seq064K> { - /// converts the lifetime to static - pub fn into_static( - self, - ) -> Seq064K<'static, Inner<'static, ISFIXED, SIZE, HEADERSIZE, MAXSIZE>> { + /// converts the lifetime to static (no-op, always owned) + pub fn into_static(self) -> Seq064K> { let seq = self.0; let static_seq = seq.into_iter().map(|x| x.into_static()).collect(); // Safe unwrap cause the initial value is a valid Seq064K @@ -446,13 +435,11 @@ impl<'a, const ISFIXED: bool, const SIZE: usize, const HEADERSIZE: usize, const } } -/// The lifetime 'a is defined. - #[derive(Debug, Clone, Eq, PartialEq)] -pub struct Sv2Option<'a, T>(pub Vec, PhantomData<&'a T>); +pub struct Sv2Option(pub Vec); // TODO add test for that -impl<'a, const SIZE: usize> Sv2Option<'a, super::inner::Inner<'a, true, SIZE, 0, 0>> { +impl Sv2Option> { /// Gets the owned first element of the sequence, if present pub fn to_option(&self) -> Option> { let v: Vec> = self.0.iter().map(|x| x.to_vec()).collect(); @@ -475,7 +462,7 @@ impl<'a, const SIZE: usize> Sv2Option<'a, super::inner::Inner<'a, true, SIZE, 0, } } -impl<'a, T: 'a> Sv2Option<'a, T> { +impl Sv2Option { const HEADERSIZE: usize = 1; /// Return the len of the inner vector @@ -494,8 +481,8 @@ impl<'a, T: 'a> Sv2Option<'a, T> { /// Initializes a new option type pub fn new(inner: Option) -> Self { match inner { - Some(x) => Self(vec![x], PhantomData), - None => Self(vec![], PhantomData), + Some(x) => Self(vec![x]), + None => Self(vec![]), } } @@ -512,7 +499,7 @@ impl<'a, T: 'a> Sv2Option<'a, T> { } } -impl GetSize for Sv2Option<'_, T> { +impl GetSize for Sv2Option { fn get_size(&self) -> usize { let mut size = Self::HEADERSIZE; for with_size in &self.0 { diff --git a/sv2/binary-sv2/src/lib.rs b/sv2/binary-sv2/src/lib.rs index 9f7f7fd24b..c5653800af 100644 --- a/sv2/binary-sv2/src/lib.rs +++ b/sv2/binary-sv2/src/lib.rs @@ -99,7 +99,7 @@ pub fn to_writer(src: T, dst: &mut [u8]) -> Result<(), Error> { } /// Decodes an SV2-encoded byte slice into the specified data type. -pub fn from_bytes<'a, T: Decodable<'a>>(data: &'a mut [u8]) -> Result { +pub fn from_bytes(data: &mut [u8]) -> Result { T::from_bytes(data) } @@ -301,21 +301,21 @@ impl GetSize for Vec { } } -impl From> for EncodableField<'_> { +impl From> for EncodableField { fn from(v: Vec) -> Self { EncodableField::Struct(v.into_iter().map(Into::into).collect()) } } #[cfg(feature = "with_buffer_pool")] -impl From for EncodableField<'_> { +impl From for EncodableField { fn from(_v: buffer_sv2::Slice) -> Self { unreachable!() } } /// Converts a value implementing the `Into` trait into a custom `U256` type. -pub fn u256_from_int>(value: V) -> U256<'static> { +pub fn u256_from_int>(value: V) -> U256 { // initialize u256 as a bytes vec of len 24 let mut u256 = vec![0_u8; 24]; let val: u64 = value.into(); diff --git a/sv2/binary-sv2/tests/test.rs b/sv2/binary-sv2/tests/test.rs index afdc1a9391..3d9b1f23d9 100644 --- a/sv2/binary-sv2/tests/test.rs +++ b/sv2/binary-sv2/tests/test.rs @@ -59,8 +59,8 @@ mod test_b0255 { use core::convert::TryInto; #[derive(Clone, Deserialize, Serialize, PartialEq, Debug)] - struct Test<'decoder> { - a: B0255<'decoder>, + struct Test { + a: B0255, } #[test] @@ -97,8 +97,8 @@ mod test_u256 { use core::convert::TryInto; #[derive(Clone, Deserialize, Serialize, PartialEq, Debug)] - struct Test<'decoder> { - a: U256<'decoder>, + struct Test { + a: U256, } #[test] @@ -121,8 +121,8 @@ mod test_signature { use core::convert::TryInto; #[derive(Deserialize, Serialize, PartialEq, Debug, Clone)] - struct Test<'decoder> { - a: Signature<'decoder>, + struct Test { + a: Signature, } #[test] @@ -145,9 +145,9 @@ mod test_b016m { use core::convert::TryInto; #[derive(Deserialize, Serialize, PartialEq, Debug, Clone)] - struct Test<'decoder> { + struct Test { b: bool, - a: B016M<'decoder>, + a: B016M, } #[test] @@ -186,9 +186,9 @@ mod test_b064k { use core::convert::TryInto; #[derive(Deserialize, Serialize, PartialEq, Debug, Clone)] - struct Test<'decoder> { + struct Test { b: bool, - a: B064K<'decoder>, + a: B064K, } #[test] @@ -213,8 +213,8 @@ mod test_seq0255_u256 { use core::convert::TryInto; #[derive(Deserialize, Serialize, PartialEq, Debug, Clone)] - struct Test<'decoder> { - a: Seq0255<'decoder, U256<'decoder>>, + struct Test { + a: Seq0255, } #[test] @@ -245,8 +245,8 @@ mod test_0255_bool { use super::*; #[derive(Deserialize, Serialize, PartialEq, Debug, Clone)] - struct Test<'decoder> { - a: Seq0255<'decoder, bool>, + struct Test { + a: Seq0255, } #[test] @@ -267,8 +267,8 @@ mod test_seq0255_u16 { use super::*; #[derive(Deserialize, Serialize, PartialEq, Debug, Clone)] - struct Test<'decoder> { - a: Seq0255<'decoder, u16>, + struct Test { + a: Seq0255, } #[test] @@ -290,8 +290,8 @@ mod test_seq_0255_u24 { use core::convert::TryInto; #[derive(Deserialize, Serialize, PartialEq, Debug, Clone)] - struct Test<'decoder> { - a: Seq0255<'decoder, U24>, + struct Test { + a: Seq0255, } #[test] @@ -317,8 +317,8 @@ mod test_seqo255_u32 { use super::*; #[derive(Deserialize, Serialize, PartialEq, Debug, Clone)] - struct Test<'decoder> { - a: Seq0255<'decoder, u32>, + struct Test { + a: Seq0255, } #[test] @@ -340,8 +340,8 @@ mod test_seq0255_signature { use core::convert::TryInto; #[derive(Deserialize, Serialize, PartialEq, Debug, Clone)] - struct Test<'decoder> { - a: Seq0255<'decoder, Signature<'decoder>>, + struct Test { + a: Seq0255, } #[test] @@ -371,8 +371,8 @@ mod test_seq_064_u256 { use core::convert::TryInto; #[derive(Deserialize, Serialize, PartialEq, Debug, Clone)] - struct Test<'decoder> { - a: Seq064K<'decoder, U256<'decoder>>, + struct Test { + a: Seq064K, } #[test] @@ -403,8 +403,8 @@ mod test_064_bool { use super::*; #[derive(Deserialize, Serialize, PartialEq, Debug, Clone)] - struct Test<'decoder> { - a: Seq064K<'decoder, bool>, + struct Test { + a: Seq064K, } #[test] @@ -430,8 +430,8 @@ mod test_se1o64k_u16 { use super::*; #[derive(Deserialize, Serialize, PartialEq, Debug, Clone)] - struct Test<'decoder> { - a: Seq064K<'decoder, u16>, + struct Test { + a: Seq064K, } #[test] @@ -453,8 +453,8 @@ mod test_seq064k_u24 { use core::convert::TryInto; #[derive(Deserialize, Serialize, PartialEq, Debug, Clone)] - struct Test<'decoder> { - a: Seq064K<'decoder, U24>, + struct Test { + a: Seq064K, } #[test] @@ -480,8 +480,8 @@ mod test_seq064k_u32 { use super::*; #[derive(Deserialize, Serialize, PartialEq, Debug, Clone)] - struct Test<'decoder> { - a: Seq064K<'decoder, u32>, + struct Test { + a: Seq064K, } #[test] @@ -502,8 +502,8 @@ mod test_seq064k_signature { use core::convert::TryInto; #[derive(Deserialize, Serialize, PartialEq, Debug, Clone)] - struct Test<'decoder> { - a: Seq064K<'decoder, Signature<'decoder>>, + struct Test { + a: Seq064K, } #[test] @@ -532,8 +532,8 @@ mod test_seq064k_b016m { use core::convert::TryInto; #[derive(Deserialize, Serialize, PartialEq, Debug, Clone)] - struct Test<'decoder> { - a: Seq064K<'decoder, B016M<'decoder>>, + struct Test { + a: Seq064K, } #[test] @@ -561,9 +561,9 @@ mod test_seq_0255_in_struct { use super::*; #[derive(Deserialize, Serialize, PartialEq, Debug, Clone)] - struct Test<'decoder> { + struct Test { a: u8, - b: Seq0255<'decoder, u8>, + b: Seq0255, c: u32, } @@ -586,8 +586,8 @@ mod test_sv2_option_u256 { use core::convert::TryInto; #[derive(Deserialize, Serialize, PartialEq, Debug, Clone)] - struct Test<'decoder> { - a: Sv2Option<'decoder, U256<'decoder>>, + struct Test { + a: Sv2Option, } #[test] @@ -613,8 +613,8 @@ mod test_sv2_option_none { use super::*; #[derive(Deserialize, Serialize, PartialEq, Debug, Clone)] - struct Test<'decoder> { - a: Sv2Option<'decoder, U256<'decoder>>, + struct Test { + a: Sv2Option, } #[test] diff --git a/sv2/channels-sv2/src/chain_tip.rs b/sv2/channels-sv2/src/chain_tip.rs index 236be0edc8..488c43e0a8 100644 --- a/sv2/channels-sv2/src/chain_tip.rs +++ b/sv2/channels-sv2/src/chain_tip.rs @@ -10,14 +10,14 @@ use template_distribution_sv2::SetNewPrevHash as SetNewPrevHashTdp; /// - validating shares. #[derive(Debug, Clone)] pub struct ChainTip { - prev_hash: U256<'static>, + prev_hash: U256, nbits: u32, min_ntime: u32, } impl ChainTip { /// Constructs a new `ChainTip` instance. - pub fn new(prev_hash: U256<'static>, nbits: u32, min_ntime: u32) -> Self { + pub fn new(prev_hash: U256, nbits: u32, min_ntime: u32) -> Self { Self { prev_hash, nbits, @@ -26,7 +26,7 @@ impl ChainTip { } /// Retrieves the hash of the previous block - pub fn prev_hash(&self) -> U256<'static> { + pub fn prev_hash(&self) -> U256 { self.prev_hash.clone() } @@ -41,7 +41,7 @@ impl ChainTip { } } -impl From> for ChainTip { +impl From for ChainTip { fn from(set_new_prev_hash: SetNewPrevHashTdp) -> Self { let set_new_prev_hash_static = set_new_prev_hash.into_static(); let prev_hash = set_new_prev_hash_static.prev_hash; @@ -51,7 +51,7 @@ impl From> for ChainTip { } } -impl From> for ChainTip { +impl From for ChainTip { fn from(set_new_prev_hash: SetNewPrevHashMp) -> Self { let set_new_prev_hash_static = set_new_prev_hash.into_static(); let prev_hash = set_new_prev_hash_static.prev_hash; diff --git a/sv2/channels-sv2/src/client/extended.rs b/sv2/channels-sv2/src/client/extended.rs index bee34ba35c..44040b574e 100644 --- a/sv2/channels-sv2/src/client/extended.rs +++ b/sv2/channels-sv2/src/client/extended.rs @@ -39,7 +39,7 @@ use tracing::debug; /// - A [`NewExtendedMiningJob`] message /// - The `extranonce_prefix` in use when the job was created /// - The target of the job -pub type ExtendedJob<'a> = (NewExtendedMiningJob<'a>, Vec, Target); +pub type ExtendedJob = (NewExtendedMiningJob, Vec, Target); /// Mining Client abstraction for the state management of an Sv2 Extended Channel. /// @@ -60,7 +60,7 @@ pub type ExtendedJob<'a> = (NewExtendedMiningJob<'a>, Vec, Target); /// - Share accounting for the channel (as tracked by the client). /// - The channel's current chain tip. #[derive(Clone, Debug)] -pub struct ExtendedChannel<'a> { +pub struct ExtendedChannel { channel_id: u32, user_identity: String, extranonce_prefix: Vec, @@ -69,17 +69,17 @@ pub struct ExtendedChannel<'a> { nominal_hashrate: f32, version_rolling: bool, // future jobs are indexed with job_id (u32) - future_jobs: HashMap>, - active_job: Option>, + future_jobs: HashMap, + active_job: Option, // past jobs are indexed with job_id (u32) - past_jobs: HashMap>, + past_jobs: HashMap, // stale jobs are indexed with job_id (u32) - stale_jobs: HashMap>, + stale_jobs: HashMap, share_accounting: ShareAccounting, chain_tip: Option, } -impl<'a> ExtendedChannel<'a> { +impl ExtendedChannel { /// Constructs a new [`ExtendedChannel`]. pub fn new( channel_id: u32, @@ -188,22 +188,22 @@ impl<'a> ExtendedChannel<'a> { } /// Returns a reference to the currently active job, if any. - pub fn get_active_job(&self) -> Option<&ExtendedJob<'a>> { + pub fn get_active_job(&self) -> Option<&ExtendedJob> { self.active_job.as_ref() } /// Returns a reference to all future jobs for this channel. - pub fn get_future_jobs(&self) -> &HashMap> { + pub fn get_future_jobs(&self) -> &HashMap { &self.future_jobs } /// Returns a reference to all past jobs for this channel. - pub fn get_past_jobs(&self) -> &HashMap> { + pub fn get_past_jobs(&self) -> &HashMap { &self.past_jobs } /// Returns a reference to all stale jobs for this channel. - pub fn get_stale_jobs(&self) -> &HashMap> { + pub fn get_stale_jobs(&self) -> &HashMap { &self.stale_jobs } @@ -232,7 +232,7 @@ impl<'a> ExtendedChannel<'a> { /// - Otherwise, the job is activated and previous active job moves to the past jobs list. pub fn on_new_extended_mining_job( &mut self, - mut new_extended_mining_job: NewExtendedMiningJob<'a>, + mut new_extended_mining_job: NewExtendedMiningJob, ) -> Result<(), ExtendedChannelError> { // try to strip bip141 bytes from coinbase_tx_prefix and coinbase_tx_suffix, if they are // present @@ -286,7 +286,7 @@ impl<'a> ExtendedChannel<'a> { /// To be used by a Sv2 Job Declarator Client pub fn on_set_custom_mining_job_success( &mut self, - set_custom_mining_job: SetCustomMiningJob<'a>, + set_custom_mining_job: SetCustomMiningJob, set_custom_mining_job_success: SetCustomMiningJobSuccess, ) -> Result<(), ExtendedChannelError> { if set_custom_mining_job.channel_id != set_custom_mining_job_success.channel_id @@ -427,7 +427,7 @@ impl<'a> ExtendedChannel<'a> { /// - Updates the chain tip for the channel. pub fn on_set_new_prev_hash( &mut self, - set_new_prev_hash: SetNewPrevHashMp<'a>, + set_new_prev_hash: SetNewPrevHashMp, ) -> Result<(), ExtendedChannelError> { match self.future_jobs.remove(&set_new_prev_hash.job_id) { Some(mut activated_job) => { diff --git a/sv2/channels-sv2/src/client/group.rs b/sv2/channels-sv2/src/client/group.rs index d875f8ba14..4b54c832f3 100644 --- a/sv2/channels-sv2/src/client/group.rs +++ b/sv2/channels-sv2/src/client/group.rs @@ -22,22 +22,22 @@ use mining_sv2::{NewExtendedMiningJob, SetNewPrevHash as SetNewPrevHashMp}; /// - past or stale jobs /// - share validation state (handled per-channel) #[derive(Debug, Clone)] -pub struct GroupChannel<'a> { +pub struct GroupChannel { /// Unique identifier for the group channel group_channel_id: u32, /// Set of channel IDs associated with this group channel channel_ids: HashSet, /// Future jobs, indexed by job_id, waiting to be activated - future_jobs: HashMap>, + future_jobs: HashMap, /// Currently active mining job for the group channel - active_job: Option>, + active_job: Option, /// Full extranonce size for jobs associated with this group channel. /// The constructor initializes this as None, but as new channels are added, we keep this updated. /// At no point in time, two channels can belong to the same group while having different full extranonce sizes. full_extranonce_size: Option, } -impl<'a> GroupChannel<'a> { +impl GroupChannel { /// Creates a new [`GroupChannel`] with the given group_channel_id. pub fn new(group_channel_id: u32) -> Self { Self { @@ -97,12 +97,12 @@ impl<'a> GroupChannel<'a> { } /// Returns a reference to the current active job, if any. - pub fn get_active_job(&self) -> Option<&NewExtendedMiningJob<'a>> { + pub fn get_active_job(&self) -> Option<&NewExtendedMiningJob> { self.active_job.as_ref() } /// Returns a reference to all future jobs indexed by job_id. - pub fn get_future_jobs(&self) -> &HashMap> { + pub fn get_future_jobs(&self) -> &HashMap { &self.future_jobs } @@ -117,7 +117,7 @@ impl<'a> GroupChannel<'a> { /// - If `min_ntime` is empty, stores it as a future job. pub fn on_new_extended_mining_job( &mut self, - new_extended_mining_job: NewExtendedMiningJob<'a>, + new_extended_mining_job: NewExtendedMiningJob, ) { match new_extended_mining_job.min_ntime.clone().into_inner() { Some(_min_ntime) => { @@ -138,7 +138,7 @@ impl<'a> GroupChannel<'a> { /// Returns `Err(GroupChannelError::JobIdNotFound)` if no matching job found. pub fn on_set_new_prev_hash( &mut self, - set_new_prev_hash: SetNewPrevHashMp<'a>, + set_new_prev_hash: SetNewPrevHashMp, ) -> Result<(), GroupChannelError> { match self.future_jobs.remove(&set_new_prev_hash.job_id) { Some(job) => { diff --git a/sv2/channels-sv2/src/client/standard.rs b/sv2/channels-sv2/src/client/standard.rs index 8bce59d330..35ba821215 100644 --- a/sv2/channels-sv2/src/client/standard.rs +++ b/sv2/channels-sv2/src/client/standard.rs @@ -29,7 +29,7 @@ use mining_sv2::{ use tracing::debug; /// A type alias representing a standard mining job tied to a specific `target`. -pub type StandardJob<'a> = (NewMiningJob<'a>, Target); +pub type StandardJob = (NewMiningJob, Target); /// Mining Client abstraction over the state of a Sv2 Standard Channel. /// @@ -46,21 +46,21 @@ pub type StandardJob<'a> = (NewMiningJob<'a>, Target); /// - share accounting state /// - chain tip state #[derive(Debug, Clone)] -pub struct StandardChannel<'a> { +pub struct StandardChannel { channel_id: u32, user_identity: String, extranonce_prefix: Vec, target: Target, nominal_hashrate: f32, - future_jobs: HashMap>, - active_job: Option>, - past_jobs: HashMap>, - stale_jobs: HashMap>, + future_jobs: HashMap, + active_job: Option, + past_jobs: HashMap, + stale_jobs: HashMap, share_accounting: ShareAccounting, chain_tip: Option, } -impl<'a> StandardChannel<'a> { +impl StandardChannel { /// Creates a new [`StandardChannel`] instance with provided channel parameters. pub fn new( channel_id: u32, @@ -144,22 +144,22 @@ impl<'a> StandardChannel<'a> { /// Returns all future jobs for this channel. /// /// The list is cleared once a [`StandardChannel::on_set_new_prev_hash`] is processed. - pub fn get_future_jobs(&self) -> &HashMap> { + pub fn get_future_jobs(&self) -> &HashMap { &self.future_jobs } /// Returns the currently active job, if any. - pub fn get_active_job(&self) -> Option<&StandardJob<'a>> { + pub fn get_active_job(&self) -> Option<&StandardJob> { self.active_job.as_ref() } /// Returns all past jobs for the channel (active jobs under current chain tip). - pub fn get_past_jobs(&self) -> &HashMap> { + pub fn get_past_jobs(&self) -> &HashMap { &self.past_jobs } /// Returns all stale jobs for the channel (jobs from previous chain tip). - pub fn get_stale_jobs(&self) -> &HashMap> { + pub fn get_stale_jobs(&self) -> &HashMap { &self.stale_jobs } @@ -183,7 +183,7 @@ impl<'a> StandardChannel<'a> { /// and activating it in this channel's context. /// /// The new job is constructed using the current extranonce prefix. - pub fn on_new_group_channel_job(&mut self, new_extended_mining_job: NewExtendedMiningJob<'a>) { + pub fn on_new_group_channel_job(&mut self, new_extended_mining_job: NewExtendedMiningJob) { let merkle_root = merkle_root_from_path( new_extended_mining_job.coinbase_tx_prefix.inner_as_ref(), new_extended_mining_job.coinbase_tx_suffix.inner_as_ref(), @@ -210,7 +210,7 @@ impl<'a> StandardChannel<'a> { /// - If `min_ntime` is present, the job is activated and replaces the current active job. /// - If `min_ntime` is empty, the job is added to future jobs. /// - If an active job exists, it is moved to past jobs on activation. - pub fn on_new_mining_job(&mut self, new_mining_job: NewMiningJob<'a>) { + pub fn on_new_mining_job(&mut self, new_mining_job: NewMiningJob) { match new_mining_job.min_ntime.clone().into_inner() { Some(_min_ntime) => { if let Some(active_job) = self.active_job.as_ref() { @@ -236,7 +236,7 @@ impl<'a> StandardChannel<'a> { /// - Updates chain tip information. Returns error if no matching future job found. pub fn on_set_new_prev_hash( &mut self, - set_new_prev_hash: SetNewPrevHashMp<'a>, + set_new_prev_hash: SetNewPrevHashMp, ) -> Result<(), StandardChannelError> { match self.future_jobs.remove(&set_new_prev_hash.job_id) { Some(mut activated_job) => { diff --git a/sv2/channels-sv2/src/server/extended.rs b/sv2/channels-sv2/src/server/extended.rs index d07ec91d04..82736d3f1b 100644 --- a/sv2/channels-sv2/src/server/extended.rs +++ b/sv2/channels-sv2/src/server/extended.rs @@ -57,7 +57,7 @@ use bitcoin::{ CompactTarget, Target, }; use mining_sv2::{SetCustomMiningJob, SubmitSharesExtended}; -use std::{collections::HashMap, convert::TryInto, marker::PhantomData}; +use std::{collections::HashMap, convert::TryInto}; use template_distribution_sv2::{NewTemplate, SetNewPrevHash as SetNewPrevHashTdp}; use tracing::debug; @@ -79,9 +79,9 @@ use tracing::debug; /// - the channel's [`JobFactory`] /// - the channel's [`ChainTip`] #[derive(Debug)] -pub struct ExtendedChannel<'a, J> +pub struct ExtendedChannel where - J: JobStore>, + J: JobStore, { channel_id: u32, user_identity: String, @@ -96,12 +96,11 @@ where share_accounting: ShareAccounting, expected_share_per_minute: f32, chain_tip: Option, - phantom: PhantomData<&'a ()>, } -impl<'a, J> ExtendedChannel<'a, J> +impl ExtendedChannel where - J: JobStore>, + J: JobStore, { /// Constructor of `ExtendedChannel` for a Sv2 Pool Server. /// Not meant for usage on a Sv2 Job Declaration Client. @@ -245,7 +244,6 @@ where share_accounting: ShareAccounting::new(share_batch_size), expected_share_per_minute, chain_tip: None, - phantom: PhantomData, }) } @@ -410,19 +408,19 @@ where } /// Returns an owned copy of the currently active job, if any. - pub fn get_active_job(&self) -> Option> { + pub fn get_active_job(&self) -> Option { // cloning happens inside the job store self.job_store.get_active_job() } /// Returns an owned copy of a future job from its job ID, if any. - pub fn get_future_job(&self, job_id: u32) -> Option> { + pub fn get_future_job(&self, job_id: u32) -> Option { // cloning happens inside the job store self.job_store.get_future_job(job_id) } /// Returns an owned copy of a past job from its job ID, if any. - pub fn get_past_job(&self, job_id: u32) -> Option> { + pub fn get_past_job(&self, job_id: u32) -> Option { // cloning happens inside the job store self.job_store.get_past_job(job_id) } @@ -443,7 +441,7 @@ where /// If this flag is set, on_set_custom_mining_job should be used instead. pub fn on_new_template( &mut self, - template: NewTemplate<'a>, + template: NewTemplate, coinbase_reward_outputs: Vec, ) -> Result<(), ExtendedChannelError> { match template.future_template { @@ -501,7 +499,7 @@ where /// If this flag is set, on_set_custom_mining_job should be used instead. pub fn on_group_channel_job( &mut self, - mut extended_job: ExtendedJob<'a>, + mut extended_job: ExtendedJob, ) -> Result<(), ExtendedChannelError> { // make sure the extranonce prefix is associated to the channel's extranonce prefix extended_job.set_extranonce_prefix(self.extranonce_prefix.clone()); @@ -539,7 +537,7 @@ where /// All past jobs are cleared. pub fn on_set_new_prev_hash( &mut self, - set_new_prev_hash: SetNewPrevHashTdp<'a>, + set_new_prev_hash: SetNewPrevHashTdp, ) -> Result<(), ExtendedChannelError> { // clear the job id to target mapping self.job_id_to_target.clear(); @@ -592,7 +590,7 @@ where /// To be used by a Sv2 Pool Server upon receiving a `SetCustomMiningJob` message. pub fn on_set_custom_mining_job( &mut self, - set_custom_mining_job: SetCustomMiningJob<'a>, + set_custom_mining_job: SetCustomMiningJob, ) -> Result { let new_job = self .job_factory diff --git a/sv2/channels-sv2/src/server/group.rs b/sv2/channels-sv2/src/server/group.rs index ecea25c07e..880b9ad3b1 100644 --- a/sv2/channels-sv2/src/server/group.rs +++ b/sv2/channels-sv2/src/server/group.rs @@ -38,7 +38,7 @@ use crate::{ }, }; use bitcoin::transaction::TxOut; -use std::{collections::HashSet, marker::PhantomData}; +use std::collections::HashSet; use template_distribution_sv2::{NewTemplate, SetNewPrevHash as SetNewPrevHashTdp}; /// Abstraction of a Group Channel. @@ -58,9 +58,9 @@ use template_distribution_sv2::{NewTemplate, SetNewPrevHash as SetNewPrevHashTdp /// - the group channel's stale jobs /// - the group channel's share validation state #[derive(Debug)] -pub struct GroupChannel<'a, J> +pub struct GroupChannel where - J: JobStore>, + J: JobStore, { group_channel_id: u32, channel_ids: HashSet, @@ -68,12 +68,11 @@ where job_store: J, chain_tip: Option, full_extranonce_size: usize, - phantom: PhantomData<&'a ()>, } -impl<'a, J> GroupChannel<'a, J> +impl GroupChannel where - J: JobStore>, + J: JobStore, { /// Constructor of `GroupChannel` for a Sv2 Pool Server. /// Not meant for usage on a Sv2 Job Declaration Client. @@ -153,7 +152,6 @@ where job_store, chain_tip: None, full_extranonce_size, - phantom: PhantomData, }) } @@ -215,7 +213,7 @@ where } /// Returns an owned copy of the currently active job, if any. - pub fn get_active_job(&self) -> Option> { + pub fn get_active_job(&self) -> Option { // cloning happens inside the job store self.job_store.get_active_job() } @@ -227,7 +225,7 @@ where } /// Returns an owned copy of a future job from its job ID, if any. - pub fn get_future_job(&self, job_id: u32) -> Option> { + pub fn get_future_job(&self, job_id: u32) -> Option { // cloning happens inside the job store self.job_store.get_future_job(job_id) } @@ -239,7 +237,7 @@ where /// Returns an error if a non-future job cannot be created due to missing chain tip. pub fn on_new_template( &mut self, - template: NewTemplate<'a>, + template: NewTemplate, coinbase_reward_outputs: Vec, ) -> Result<(), GroupChannelError> { match template.future_template { @@ -293,7 +291,7 @@ where /// Returns an error if no matching future job is found. pub fn on_set_new_prev_hash( &mut self, - set_new_prev_hash: SetNewPrevHashTdp<'a>, + set_new_prev_hash: SetNewPrevHashTdp, ) -> Result<(), GroupChannelError> { match self.job_store.has_future_jobs() { false => { diff --git a/sv2/channels-sv2/src/server/jobs/extended.rs b/sv2/channels-sv2/src/server/jobs/extended.rs index ff90d95156..620732832e 100644 --- a/sv2/channels-sv2/src/server/jobs/extended.rs +++ b/sv2/channels-sv2/src/server/jobs/extended.rs @@ -25,16 +25,16 @@ use template_distribution_sv2::NewTemplate; /// That makes it easy to calculate the coinbase `txid` (instead of `wtxid`) for merkle root /// calculation. #[derive(Debug, Clone)] -pub struct ExtendedJob<'a> { - origin: JobOrigin<'a>, +pub struct ExtendedJob { + origin: JobOrigin, extranonce_prefix: Vec, coinbase_outputs: Vec, coinbase_tx_prefix_with_bip141: Vec, coinbase_tx_suffix_with_bip141: Vec, - job_message: NewExtendedMiningJob<'a>, + job_message: NewExtendedMiningJob, } -impl Job for ExtendedJob<'_> { +impl Job for ExtendedJob { fn get_job_id(&self) -> u32 { self.job_message.job_id } @@ -44,17 +44,17 @@ impl Job for ExtendedJob<'_> { } } -impl<'a> ExtendedJob<'a> { +impl ExtendedJob { /// Creates a new job from a template. /// /// `additional_coinbase_outputs` are added to the coinbase outputs coming from the template. pub fn from_template( - template: NewTemplate<'a>, + template: NewTemplate, extranonce_prefix: Vec, additional_coinbase_outputs: Vec, coinbase_tx_prefix: Vec, coinbase_tx_suffix: Vec, - job_message: NewExtendedMiningJob<'a>, + job_message: NewExtendedMiningJob, ) -> Result { let template_coinbase_outputs = deserialize_template_outputs( template.coinbase_tx_outputs.to_vec(), @@ -79,12 +79,12 @@ impl<'a> ExtendedJob<'a> { /// /// Used for jobs originating from [`SetCustomMiningJob`] messages. pub fn from_custom_job( - custom_job: SetCustomMiningJob<'a>, + custom_job: SetCustomMiningJob, extranonce_prefix: Vec, coinbase_outputs: Vec, coinbase_tx_prefix: Vec, coinbase_tx_suffix: Vec, - job_message: NewExtendedMiningJob<'a>, + job_message: NewExtendedMiningJob, ) -> Self { Self { origin: JobOrigin::SetCustomMiningJob(custom_job), @@ -104,7 +104,7 @@ impl<'a> ExtendedJob<'a> { self, channel_id: u32, extranonce_prefix: Vec, - ) -> Result, ExtendedJobError> { + ) -> Result { // here we can only convert extended jobs that were created from a template let template = match self.get_origin() { JobOrigin::NewTemplate(template) => template, @@ -148,7 +148,7 @@ impl<'a> ExtendedJob<'a> { } /// Returns the origin message for this job (template or custom job). - pub fn get_origin(&self) -> &JobOrigin<'a> { + pub fn get_origin(&self) -> &JobOrigin { &self.origin } @@ -178,15 +178,15 @@ impl<'a> ExtendedJob<'a> { &self.coinbase_outputs } /// Returns the [`NewExtendedMiningJob`] message for this job. - pub fn get_job_message(&self) -> &NewExtendedMiningJob<'a> { + pub fn get_job_message(&self) -> &NewExtendedMiningJob { &self.job_message } /// Returns the merkle path for this job. - pub fn get_merkle_path(&self) -> &Seq0255<'a, U256<'a>> { + pub fn get_merkle_path(&self) -> &Seq0255 { &self.job_message.merkle_path } /// Returns the minimum ntime for this job (if set). - pub fn get_min_ntime(&self) -> Sv2Option<'a, u32> { + pub fn get_min_ntime(&self) -> Sv2Option { self.job_message.min_ntime.clone() } /// Returns the block version for this job. diff --git a/sv2/channels-sv2/src/server/jobs/factory.rs b/sv2/channels-sv2/src/server/jobs/factory.rs index 266555c3b2..e12e7780f8 100644 --- a/sv2/channels-sv2/src/server/jobs/factory.rs +++ b/sv2/channels-sv2/src/server/jobs/factory.rs @@ -141,14 +141,14 @@ impl JobFactory { /// /// It's up to the caller to ensure that the sum of `additional_coinbase_outputs` is equal to /// available template revenue. Returns an error otherwise. - pub fn new_standard_job<'a>( + pub fn new_standard_job( &mut self, channel_id: u32, chain_tip: Option, extranonce_prefix: Vec, - template: NewTemplate<'a>, + template: NewTemplate, additional_coinbase_outputs: Vec, - ) -> Result, JobFactoryError> { + ) -> Result { let coinbase_outputs_sum = additional_coinbase_outputs .iter() .map(|o| o.value.to_sat()) @@ -233,10 +233,10 @@ impl JobFactory { channel_id: u32, chain_tip: Option, extranonce_prefix: Vec, - template: NewTemplate<'a>, + template: NewTemplate, additional_coinbase_outputs: Vec, full_extranonce_size: usize, - ) -> Result, JobFactoryError> { + ) -> Result { let coinbase_outputs_sum = additional_coinbase_outputs .iter() .map(|o| o.value.to_sat()) @@ -326,7 +326,7 @@ impl JobFactory { /// is equal to available template revenue. Returns an error otherwise. pub fn new_coinbase_tx_prefix_and_suffix( &self, - template: NewTemplate<'_>, + template: NewTemplate, additional_coinbase_outputs: Vec, full_extranonce_size: usize, ) -> Result<(Vec, Vec), JobFactoryError> { @@ -355,16 +355,16 @@ impl JobFactory { /// It's up to the caller to ensure that the sum of the additional coinbase outputs is equal to /// available template revenue. #[allow(clippy::too_many_arguments)] - pub fn new_custom_job<'a>( + pub fn new_custom_job( &self, channel_id: u32, request_id: u32, - token: B0255<'a>, + token: B0255, chain_tip: ChainTip, - template: NewTemplate<'a>, + template: NewTemplate, additional_coinbase_outputs: Vec, full_extranonce_size: usize, - ) -> Result, JobFactoryError> { + ) -> Result { let coinbase_outputs_sum = additional_coinbase_outputs .iter() .map(|o| o.value.to_sat()) @@ -418,12 +418,12 @@ impl JobFactory { /// Assumes that the SetCustomMiningJob message has already been validated. /// /// To be used by Extended Channels on a Sv2 Pool Server. - pub fn new_extended_job_from_custom_job<'a>( + pub fn new_extended_job_from_custom_job( &mut self, - set_custom_mining_job: SetCustomMiningJob<'a>, + set_custom_mining_job: SetCustomMiningJob, extranonce_prefix: Vec, full_extranonce_size: usize, - ) -> Result, JobFactoryError> { + ) -> Result { let serialized_outputs = set_custom_mining_job .coinbase_tx_outputs .inner_as_ref() @@ -486,7 +486,7 @@ impl JobFactory { // coinbase fn custom_coinbase( &self, - m: SetCustomMiningJob<'_>, + m: SetCustomMiningJob, full_extranonce_size: usize, ) -> Result { let deserialized_outputs = Vec::::consensus_decode( @@ -518,7 +518,7 @@ impl JobFactory { fn custom_coinbase_tx_prefix( &self, - m: SetCustomMiningJob<'_>, + m: SetCustomMiningJob, full_extranonce_size: usize, ) -> Result, JobFactoryError> { let coinbase = self.custom_coinbase(m.clone(), full_extranonce_size)?; @@ -539,7 +539,7 @@ impl JobFactory { fn custom_coinbase_tx_suffix( &self, - m: SetCustomMiningJob<'_>, + m: SetCustomMiningJob, full_extranonce_size: usize, ) -> Result, JobFactoryError> { let coinbase = self.custom_coinbase(m.clone(), full_extranonce_size)?; @@ -562,7 +562,7 @@ impl JobFactory { // build a coinbase transaction from some template in the JobFactory fn coinbase( &self, - template: NewTemplate<'_>, + template: NewTemplate, coinbase_reward_outputs: Vec, full_extranonce_size: usize, ) -> Result { @@ -620,7 +620,7 @@ impl JobFactory { fn coinbase_tx_prefix( &self, - template: NewTemplate<'_>, + template: NewTemplate, coinbase_reward_outputs: Vec, full_extranonce_size: usize, ) -> Result, JobFactoryError> { @@ -654,7 +654,7 @@ impl JobFactory { fn coinbase_tx_suffix( &self, - template: NewTemplate<'_>, + template: NewTemplate, coinbase_reward_outputs: Vec, full_extranonce_size: usize, ) -> Result, JobFactoryError> { diff --git a/sv2/channels-sv2/src/server/jobs/mod.rs b/sv2/channels-sv2/src/server/jobs/mod.rs index 32c9cd98f8..8dd92cb93f 100644 --- a/sv2/channels-sv2/src/server/jobs/mod.rs +++ b/sv2/channels-sv2/src/server/jobs/mod.rs @@ -28,9 +28,9 @@ use mining_sv2::SetCustomMiningJob; use template_distribution_sv2::NewTemplate; #[derive(Clone, Debug, PartialEq)] -pub enum JobOrigin<'a> { - NewTemplate(NewTemplate<'a>), - SetCustomMiningJob(SetCustomMiningJob<'a>), +pub enum JobOrigin { + NewTemplate(NewTemplate), + SetCustomMiningJob(SetCustomMiningJob), } /// Trait for mining job types in SV2 mining servers. diff --git a/sv2/channels-sv2/src/server/jobs/standard.rs b/sv2/channels-sv2/src/server/jobs/standard.rs index 7efc109ff7..01fc9080c3 100644 --- a/sv2/channels-sv2/src/server/jobs/standard.rs +++ b/sv2/channels-sv2/src/server/jobs/standard.rs @@ -34,14 +34,14 @@ use template_distribution_sv2::NewTemplate; /// - all coinbase outputs (spendable + unspendable) associated with the job /// - the `NewMiningJob` message to be sent across the wire #[derive(Debug, Clone)] -pub struct StandardJob<'a> { - template: NewTemplate<'a>, +pub struct StandardJob { + template: NewTemplate, extranonce_prefix: Vec, coinbase_outputs: Vec, - job_message: NewMiningJob<'a>, + job_message: NewMiningJob, } -impl Job for StandardJob<'_> { +impl Job for StandardJob { /// Returns the job ID for this job. fn get_job_id(&self) -> u32 { self.job_message.job_id @@ -53,16 +53,16 @@ impl Job for StandardJob<'_> { } } -impl<'a> StandardJob<'a> { +impl StandardJob { /// Creates a new standard job from a template. /// /// Combines coinbase outputs from the template and any additional outputs. /// Returns an error if coinbase outputs cannot be deserialized. pub fn from_template( - template: NewTemplate<'a>, + template: NewTemplate, extranonce_prefix: Vec, additional_coinbase_outputs: Vec, - job_message: NewMiningJob<'a>, + job_message: NewMiningJob, ) -> Result { let template_coinbase_outputs = deserialize_template_outputs( template.coinbase_tx_outputs.to_vec(), @@ -94,15 +94,15 @@ impl<'a> StandardJob<'a> { &self.extranonce_prefix } /// Returns the `NewMiningJob` message for this job. - pub fn get_job_message(&self) -> &NewMiningJob<'a> { + pub fn get_job_message(&self) -> &NewMiningJob { &self.job_message } /// Returns the originating `NewTemplate` message for this job. - pub fn get_template(&self) -> &NewTemplate<'a> { + pub fn get_template(&self) -> &NewTemplate { &self.template } /// Returns the merkle root for this job. - pub fn get_merkle_root(&self) -> &U256<'a> { + pub fn get_merkle_root(&self) -> &U256 { &self.job_message.merkle_root } /// Returns true if the job is a future job (not yet activated). diff --git a/sv2/channels-sv2/src/server/standard.rs b/sv2/channels-sv2/src/server/standard.rs index 813f536783..eb6ff4aab0 100644 --- a/sv2/channels-sv2/src/server/standard.rs +++ b/sv2/channels-sv2/src/server/standard.rs @@ -57,7 +57,7 @@ use bitcoin::{ CompactTarget, Sequence, Target, }; use mining_sv2::SubmitSharesStandard; -use std::{collections::HashMap, convert::TryInto, marker::PhantomData}; +use std::{collections::HashMap, convert::TryInto}; use template_distribution_sv2::{NewTemplate, SetNewPrevHash}; use tracing::debug; @@ -77,9 +77,9 @@ use tracing::debug; /// - the channel's job factory /// - the channel's chain tip #[derive(Debug)] -pub struct StandardChannel<'a, J> +pub struct StandardChannel where - J: JobStore>, + J: JobStore, { pub channel_id: u32, user_identity: String, @@ -93,12 +93,11 @@ where job_store: J, job_factory: JobFactory, chain_tip: Option, - phantom: PhantomData<&'a ()>, } -impl<'a, J> StandardChannel<'a, J> +impl StandardChannel where - J: JobStore>, + J: JobStore, { /// Constructor of `StandardChannel` for a Sv2 Pool Server. /// Not meant for usage on a Sv2 Job Declaration Client. @@ -230,7 +229,6 @@ where job_factory: JobFactory::new(true, pool_tag_string, miner_tag_string), chain_tip: None, job_store, - phantom: PhantomData, }) } @@ -357,7 +355,7 @@ where } /// Returns the currently active job, if any. - pub fn get_active_job(&self) -> Option> { + pub fn get_active_job(&self) -> Option { // cloning happens inside the job store self.job_store.get_active_job() } @@ -368,19 +366,19 @@ where } /// Returns an owned copy of a future job from its job ID, if any. - pub fn get_future_job(&self, job_id: u32) -> Option> { + pub fn get_future_job(&self, job_id: u32) -> Option { // cloning happens inside the job store self.job_store.get_future_job(job_id) } /// Returns an owned copy of a past job from its job ID, if any. - pub fn get_past_job(&self, job_id: u32) -> Option> { + pub fn get_past_job(&self, job_id: u32) -> Option { // cloning happens inside the job store self.job_store.get_past_job(job_id) } /// Returns an owned copy of a stale job from its job ID, if any. - pub fn get_stale_job(&self, job_id: u32) -> Option> { + pub fn get_stale_job(&self, job_id: u32) -> Option { // cloning happens inside the job store self.job_store.get_stale_job(job_id) } @@ -419,7 +417,7 @@ where /// instead. pub fn on_new_template( &mut self, - template: NewTemplate<'a>, + template: NewTemplate, coinbase_reward_outputs: Vec, ) -> Result<(), StandardChannelError> { match template.future_template { @@ -473,7 +471,7 @@ where /// was broadcasted to the group channel. pub fn on_group_channel_job( &mut self, - extended_job: ExtendedJob<'a>, + extended_job: ExtendedJob, ) -> Result<(), StandardChannelError> { let standard_job = extended_job .into_standard_job(self.channel_id, self.extranonce_prefix.clone()) @@ -505,7 +503,7 @@ where /// All past jobs are cleared. pub fn on_set_new_prev_hash( &mut self, - set_new_prev_hash: SetNewPrevHash<'a>, + set_new_prev_hash: SetNewPrevHash, ) -> Result<(), StandardChannelError> { // clear the job id to target mapping self.job_id_to_target.clear(); diff --git a/sv2/channels-sv2/src/target.rs b/sv2/channels-sv2/src/target.rs index abd233df1b..6ce9d30c79 100644 --- a/sv2/channels-sv2/src/target.rs +++ b/sv2/channels-sv2/src/target.rs @@ -8,7 +8,7 @@ use core::{cmp::max, fmt::Write, ops::Div}; use primitive_types::U256 as U256Primitive; /// Converts a `u256` to a [`BlockHash`] type. -pub fn u256_to_block_hash(v: U256<'static>) -> BlockHash { +pub fn u256_to_block_hash(v: U256) -> BlockHash { let hash: [u8; 32] = v.to_vec().try_into().unwrap(); let hash = Hash::from_slice(&hash).unwrap(); BlockHash::from_raw_hash(hash) @@ -161,7 +161,7 @@ pub enum InputError { /// - `h`: Mining device hashrate (H/s). /// - `t`: Target threshold. /// - `s`: Shares per minute. -pub fn hash_rate_from_target(target: U256<'static>, share_per_min: f64) -> Result { +pub fn hash_rate_from_target(target: U256, share_per_min: f64) -> Result { // checks that we are not dividing by zero if share_per_min == 0.0 { return Err(InputError::DivisionByZero); diff --git a/sv2/codec-sv2/src/decoder.rs b/sv2/codec-sv2/src/decoder.rs index 7f527066e7..8b804b8835 100644 --- a/sv2/codec-sv2/src/decoder.rs +++ b/sv2/codec-sv2/src/decoder.rs @@ -127,7 +127,7 @@ pub struct WithNoise { } #[cfg(feature = "noise_sv2")] -impl<'a, T: Serialize + GetSize + Deserialize<'a>, B: IsBuffer + AeadBuffer> WithNoise { +impl WithNoise { /// Attempts to decode the next Noise encrypted frame. /// /// On success, the decoded and decrypted frame is returned. Otherwise, an error indicating the diff --git a/sv2/extensions-sv2/src/extensions_negotiation.rs b/sv2/extensions-sv2/src/extensions_negotiation.rs index 71cecd1ad6..cf0eb8e844 100644 --- a/sv2/extensions-sv2/src/extensions_negotiation.rs +++ b/sv2/extensions-sv2/src/extensions_negotiation.rs @@ -31,7 +31,7 @@ pub const CHANNEL_BIT_REQUEST_EXTENSIONS_ERROR: bool = false; /// Clients MUST NOT use any features from extensions that are not confirmed as /// supported by the server. #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)] -pub struct RequestExtensions<'decoder> { +pub struct RequestExtensions { /// Unique identifier for pairing request/response. /// /// The server will echo this value in its response to allow the client @@ -42,10 +42,10 @@ pub struct RequestExtensions<'decoder> { /// /// Each u16 value corresponds to a specific extension identifier. /// For example: 0x0001 for Extensions Negotiation (this extension itself) - pub requested_extensions: Seq064K<'decoder, u16>, + pub requested_extensions: Seq064K, } -impl fmt::Display for RequestExtensions<'_> { +impl fmt::Display for RequestExtensions { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!( f, @@ -61,7 +61,7 @@ impl fmt::Display for RequestExtensions<'_> { /// which of the requested extensions the server supports and will enable for /// this connection. #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)] -pub struct RequestExtensionsSuccess<'decoder> { +pub struct RequestExtensionsSuccess { /// Unique identifier for pairing request/response. /// /// This MUST match the request_id from the corresponding RequestExtensions message. @@ -72,10 +72,10 @@ pub struct RequestExtensionsSuccess<'decoder> { /// This must be a subset of the extensions requested in the RequestExtensions /// message. Extensions not listed here are not supported and MUST NOT be used /// by the client. - pub supported_extensions: Seq064K<'decoder, u16>, + pub supported_extensions: Seq064K, } -impl fmt::Display for RequestExtensionsSuccess<'_> { +impl fmt::Display for RequestExtensionsSuccess { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!( f, @@ -91,7 +91,7 @@ impl fmt::Display for RequestExtensionsSuccess<'_> { /// cannot support some or all of the requested extensions, or when the server requires /// extensions that were not requested by the client. #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)] -pub struct RequestExtensionsError<'decoder> { +pub struct RequestExtensionsError { /// Unique identifier for pairing request/response. /// /// This MUST match the request_id from the corresponding RequestExtensions message. @@ -101,17 +101,17 @@ pub struct RequestExtensionsError<'decoder> { /// /// Contains the extension identifiers from the client's request that the server /// does not support. - pub unsupported_extensions: Seq064K<'decoder, u16>, + pub unsupported_extensions: Seq064K, /// List of extension identifiers required by the server. /// /// Contains extension identifiers that the server requires but were not included /// in the client's request. If the client does not retry with these required /// extensions, the server MUST disconnect the client. - pub required_extensions: Seq064K<'decoder, u16>, + pub required_extensions: Seq064K, } -impl fmt::Display for RequestExtensionsError<'_> { +impl fmt::Display for RequestExtensionsError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!( f, diff --git a/sv2/handlers-sv2/src/common.rs b/sv2/handlers-sv2/src/common.rs index 958aa99458..dd902277ec 100644 --- a/sv2/handlers-sv2/src/common.rs +++ b/sv2/handlers-sv2/src/common.rs @@ -41,7 +41,7 @@ pub trait HandleCommonMessagesFromServerSync { ) -> Result<(), Self::Error> { let negotiated_extensions = self.get_negotiated_extensions_with_server(server_id)?; if negotiated_extensions.is_empty() { - let parsed: CommonMessages<'_> = (header.msg_type(), payload) + let parsed: CommonMessages = (header.msg_type(), payload) .try_into() .map_err(Self::Error::parse_error)?; return self.handle_common_message_from_server(server_id, parsed, None); @@ -69,7 +69,7 @@ pub trait HandleCommonMessagesFromServerSync { fn handle_common_message_from_server( &mut self, server_id: Option, - message: CommonMessages<'_>, + message: CommonMessages, tlv_fields: Option<&[Tlv]>, ) -> Result<(), Self::Error> { match message { @@ -157,7 +157,7 @@ pub trait HandleCommonMessagesFromServerAsync { async move { let negotiated_extensions = self.get_negotiated_extensions_with_server(server_id)?; if negotiated_extensions.is_empty() { - let parsed: CommonMessages<'_> = (header.msg_type(), payload) + let parsed: CommonMessages = (header.msg_type(), payload) .try_into() .map_err(Self::Error::parse_error)?; return self @@ -190,7 +190,7 @@ pub trait HandleCommonMessagesFromServerAsync { async fn handle_common_message_from_server( &mut self, server_id: Option, - message: CommonMessages<'_>, + message: CommonMessages, tlv_fields: Option<&[Tlv]>, ) -> Result<(), Self::Error> { async move { @@ -283,7 +283,7 @@ pub trait HandleCommonMessagesFromClientSync { ) -> Result<(), Self::Error> { let negotiated_extensions = self.get_negotiated_extensions_with_client(client_id)?; if negotiated_extensions.is_empty() { - let parsed: CommonMessages<'_> = (header.msg_type(), payload) + let parsed: CommonMessages = (header.msg_type(), payload) .try_into() .map_err(Self::Error::parse_error)?; return self.handle_common_message_from_client(client_id, parsed, None); @@ -311,7 +311,7 @@ pub trait HandleCommonMessagesFromClientSync { fn handle_common_message_from_client( &mut self, client_id: Option, - message: CommonMessages<'_>, + message: CommonMessages, tlv_fields: Option<&[Tlv]>, ) -> Result<(), Self::Error> { match message { @@ -382,7 +382,7 @@ pub trait HandleCommonMessagesFromClientAsync { async move { let negotiated_extensions = self.get_negotiated_extensions_with_client(client_id)?; if negotiated_extensions.is_empty() { - let parsed: CommonMessages<'_> = (header.msg_type(), payload) + let parsed: CommonMessages = (header.msg_type(), payload) .try_into() .map_err(Self::Error::parse_error)?; return self @@ -414,7 +414,7 @@ pub trait HandleCommonMessagesFromClientAsync { async fn handle_common_message_from_client( &mut self, client_id: Option, - message: CommonMessages<'_>, + message: CommonMessages, tlv_fields: Option<&[Tlv]>, ) -> Result<(), Self::Error> { async move { diff --git a/sv2/handlers-sv2/src/extensions.rs b/sv2/handlers-sv2/src/extensions.rs index cb18803b7c..010ae5af99 100644 --- a/sv2/handlers-sv2/src/extensions.rs +++ b/sv2/handlers-sv2/src/extensions.rs @@ -39,7 +39,7 @@ pub trait HandleExtensionsFromServerSync { ) -> Result<(), Self::Error> { let negotiated_extensions = self.get_negotiated_extensions_with_server(server_id)?; if negotiated_extensions.is_empty() { - let parsed: Extensions<'_> = (header.ext_type(), header.msg_type(), payload) + let parsed: Extensions = (header.ext_type(), header.msg_type(), payload) .try_into() .map_err(Self::Error::parse_error)?; return self.handle_extensions_message_from_server(server_id, parsed, None); @@ -67,7 +67,7 @@ pub trait HandleExtensionsFromServerSync { fn handle_extensions_message_from_server( &mut self, server_id: Option, - message: Extensions<'_>, + message: Extensions, tlv_fields: Option<&[Tlv]>, ) -> Result<(), Self::Error> { match message { @@ -141,7 +141,7 @@ pub trait HandleExtensionsFromServerAsync { async move { let negotiated_extensions = self.get_negotiated_extensions_with_server(server_id)?; if negotiated_extensions.is_empty() { - let parsed: Extensions<'_> = (header.ext_type(), header.msg_type(), payload) + let parsed: Extensions = (header.ext_type(), header.msg_type(), payload) .try_into() .map_err(Self::Error::parse_error)?; return self @@ -177,7 +177,7 @@ pub trait HandleExtensionsFromServerAsync { async fn handle_extensions_message_from_server( &mut self, server_id: Option, - message: Extensions<'_>, + message: Extensions, tlv_fields: Option<&[Tlv]>, ) -> Result<(), Self::Error> { async move { @@ -253,7 +253,7 @@ pub trait HandleExtensionsFromClientSync { ) -> Result<(), Self::Error> { let negotiated_extensions = self.get_negotiated_extensions_with_client(client_id)?; if negotiated_extensions.is_empty() { - let parsed: Extensions<'_> = (header.ext_type(), header.msg_type(), payload) + let parsed: Extensions = (header.ext_type(), header.msg_type(), payload) .try_into() .map_err(Self::Error::parse_error)?; return self.handle_extensions_message_from_client(client_id, parsed, None); @@ -281,7 +281,7 @@ pub trait HandleExtensionsFromClientSync { fn handle_extensions_message_from_client( &mut self, client_id: Option, - message: Extensions<'_>, + message: Extensions, tlv_fields: Option<&[Tlv]>, ) -> Result<(), Self::Error> { match message { @@ -351,7 +351,7 @@ pub trait HandleExtensionsFromClientAsync { async move { let negotiated_extensions = self.get_negotiated_extensions_with_client(client_id)?; if negotiated_extensions.is_empty() { - let parsed: Extensions<'_> = (header.ext_type(), header.msg_type(), payload) + let parsed: Extensions = (header.ext_type(), header.msg_type(), payload) .try_into() .map_err(Self::Error::parse_error)?; return self @@ -387,7 +387,7 @@ pub trait HandleExtensionsFromClientAsync { async fn handle_extensions_message_from_client( &mut self, client_id: Option, - message: Extensions<'_>, + message: Extensions, tlv_fields: Option<&[Tlv]>, ) -> Result<(), Self::Error> { async move { diff --git a/sv2/handlers-sv2/src/job_declaration.rs b/sv2/handlers-sv2/src/job_declaration.rs index 3f2b70bc33..e3b6cf8a91 100644 --- a/sv2/handlers-sv2/src/job_declaration.rs +++ b/sv2/handlers-sv2/src/job_declaration.rs @@ -44,7 +44,7 @@ pub trait HandleJobDeclarationMessagesFromServerSync { ) -> Result<(), Self::Error> { let negotiated_extensions = self.get_negotiated_extensions_with_server(server_id)?; if negotiated_extensions.is_empty() { - let parsed: JobDeclaration<'_> = (header.msg_type(), payload) + let parsed: JobDeclaration = (header.msg_type(), payload) .try_into() .map_err(Self::Error::parse_error)?; return self.handle_job_declaration_message_from_server(server_id, parsed, None); @@ -74,7 +74,7 @@ pub trait HandleJobDeclarationMessagesFromServerSync { fn handle_job_declaration_message_from_server( &mut self, server_id: Option, - message: JobDeclaration<'_>, + message: JobDeclaration, tlv_fields: Option<&[Tlv]>, ) -> Result<(), Self::Error> { match message { @@ -177,7 +177,7 @@ pub trait HandleJobDeclarationMessagesFromServerAsync { async move { let negotiated_extensions = self.get_negotiated_extensions_with_server(server_id)?; if negotiated_extensions.is_empty() { - let parsed: JobDeclaration<'_> = (header.msg_type(), payload) + let parsed: JobDeclaration = (header.msg_type(), payload) .try_into() .map_err(Self::Error::parse_error)?; return self @@ -213,7 +213,7 @@ pub trait HandleJobDeclarationMessagesFromServerAsync { async fn handle_job_declaration_message_from_server( &mut self, server_id: Option, - message: JobDeclaration<'_>, + message: JobDeclaration, tlv_fields: Option<&[Tlv]>, ) -> Result<(), Self::Error> { async move { @@ -320,7 +320,7 @@ pub trait HandleJobDeclarationMessagesFromClientSync { ) -> Result<(), Self::Error> { let negotiated_extensions = self.get_negotiated_extensions_with_client(client_id)?; if negotiated_extensions.is_empty() { - let parsed: JobDeclaration<'_> = (header.msg_type(), payload) + let parsed: JobDeclaration = (header.msg_type(), payload) .try_into() .map_err(Self::Error::parse_error)?; return self.handle_job_declaration_message_from_client(client_id, parsed, None); @@ -350,7 +350,7 @@ pub trait HandleJobDeclarationMessagesFromClientSync { fn handle_job_declaration_message_from_client( &mut self, client_id: Option, - message: JobDeclaration<'_>, + message: JobDeclaration, tlv_fields: Option<&[Tlv]>, ) -> Result<(), Self::Error> { match message { @@ -451,7 +451,7 @@ pub trait HandleJobDeclarationMessagesFromClientAsync { async move { let negotiated_extensions = self.get_negotiated_extensions_with_client(client_id)?; if negotiated_extensions.is_empty() { - let parsed: JobDeclaration<'_> = (header.msg_type(), payload) + let parsed: JobDeclaration = (header.msg_type(), payload) .try_into() .map_err(Self::Error::parse_error)?; return self @@ -487,7 +487,7 @@ pub trait HandleJobDeclarationMessagesFromClientAsync { async fn handle_job_declaration_message_from_client( &mut self, client_id: Option, - message: JobDeclaration<'_>, + message: JobDeclaration, tlv_fields: Option<&[Tlv]>, ) -> Result<(), Self::Error> { async move { diff --git a/sv2/handlers-sv2/src/mining.rs b/sv2/handlers-sv2/src/mining.rs index e86c19a5d8..6e67b32615 100644 --- a/sv2/handlers-sv2/src/mining.rs +++ b/sv2/handlers-sv2/src/mining.rs @@ -56,7 +56,7 @@ pub trait HandleMiningMessagesFromServerSync { ) -> Result<(), Self::Error> { let negotiated_extensions = self.get_negotiated_extensions_with_server(server_id)?; if negotiated_extensions.is_empty() { - let parsed: Mining<'_> = (header.msg_type(), payload) + let parsed: Mining = (header.msg_type(), payload) .try_into() .map_err(Self::Error::parse_error)?; return self.handle_mining_message_from_server(server_id, parsed, None); @@ -351,7 +351,7 @@ pub trait HandleMiningMessagesFromServerAsync { async move { let negotiated_extensions = self.get_negotiated_extensions_with_server(server_id)?; if negotiated_extensions.is_empty() { - let parsed: Mining<'_> = (header.msg_type(), payload) + let parsed: Mining = (header.msg_type(), payload) .try_into() .map_err(Self::Error::parse_error)?; return self @@ -676,7 +676,7 @@ pub trait HandleMiningMessagesFromClientSync { ) -> Result<(), Self::Error> { let negotiated_extensions = self.get_negotiated_extensions_with_client(client_id)?; if negotiated_extensions.is_empty() { - let parsed: Mining<'_> = (header.msg_type(), payload) + let parsed: Mining = (header.msg_type(), payload) .try_into() .map_err(Self::Error::parse_error)?; return self.handle_mining_message_from_client(client_id, parsed, None); @@ -916,7 +916,7 @@ pub trait HandleMiningMessagesFromClientAsync { async move { let negotiated_extensions = self.get_negotiated_extensions_with_client(client_id)?; if negotiated_extensions.is_empty() { - let parsed: Mining<'_> = (header.msg_type(), payload) + let parsed: Mining = (header.msg_type(), payload) .try_into() .map_err(Self::Error::parse_error)?; return self diff --git a/sv2/handlers-sv2/src/template_distribution.rs b/sv2/handlers-sv2/src/template_distribution.rs index 15dce450d4..f89cace6c7 100644 --- a/sv2/handlers-sv2/src/template_distribution.rs +++ b/sv2/handlers-sv2/src/template_distribution.rs @@ -43,7 +43,7 @@ pub trait HandleTemplateDistributionMessagesFromServerSync { ) -> Result<(), Self::Error> { let negotiated_extensions = self.get_negotiated_extensions_with_server(server_id)?; if negotiated_extensions.is_empty() { - let parsed: TemplateDistribution<'_> = (header.msg_type(), payload) + let parsed: TemplateDistribution = (header.msg_type(), payload) .try_into() .map_err(Self::Error::parse_error)?; return self.handle_template_distribution_message_from_server(server_id, parsed, None); @@ -74,7 +74,7 @@ pub trait HandleTemplateDistributionMessagesFromServerSync { fn handle_template_distribution_message_from_server( &mut self, server_id: Option, - message: TemplateDistribution<'_>, + message: TemplateDistribution, tlv_fields: Option<&[Tlv]>, ) -> Result<(), Self::Error> { match message { @@ -169,7 +169,7 @@ pub trait HandleTemplateDistributionMessagesFromServerAsync { async move { let negotiated_extensions = self.get_negotiated_extensions_with_server(server_id)?; if negotiated_extensions.is_empty() { - let parsed: TemplateDistribution<'_> = (header.msg_type(), payload) + let parsed: TemplateDistribution = (header.msg_type(), payload) .try_into() .map_err(Self::Error::parse_error)?; return self @@ -205,7 +205,7 @@ pub trait HandleTemplateDistributionMessagesFromServerAsync { async fn handle_template_distribution_message_from_server( &mut self, server_id: Option, - message: TemplateDistribution<'_>, + message: TemplateDistribution, tlv_fields: Option<&[Tlv]>, ) -> Result<(), Self::Error> { async move { @@ -303,7 +303,7 @@ pub trait HandleTemplateDistributionMessagesFromClientSync { ) -> Result<(), Self::Error> { let negotiated_extensions = self.get_negotiated_extensions_with_client(client_id)?; if negotiated_extensions.is_empty() { - let parsed: TemplateDistribution<'_> = (header.msg_type(), payload) + let parsed: TemplateDistribution = (header.msg_type(), payload) .try_into() .map_err(Self::Error::parse_error)?; return self.handle_template_distribution_message_from_client(client_id, parsed, None); @@ -334,7 +334,7 @@ pub trait HandleTemplateDistributionMessagesFromClientSync { fn handle_template_distribution_message_from_client( &mut self, client_id: Option, - message: TemplateDistribution<'_>, + message: TemplateDistribution, tlv_fields: Option<&[Tlv]>, ) -> Result<(), Self::Error> { match message { @@ -423,7 +423,7 @@ pub trait HandleTemplateDistributionMessagesFromClientAsync { async move { let negotiated_extensions = self.get_negotiated_extensions_with_client(client_id)?; if negotiated_extensions.is_empty() { - let parsed: TemplateDistribution<'_> = (header.msg_type(), payload) + let parsed: TemplateDistribution = (header.msg_type(), payload) .try_into() .map_err(Self::Error::parse_error)?; return self @@ -459,7 +459,7 @@ pub trait HandleTemplateDistributionMessagesFromClientAsync { async fn handle_template_distribution_message_from_client( &mut self, client_id: Option, - message: TemplateDistribution<'_>, + message: TemplateDistribution, tlv_fields: Option<&[Tlv]>, ) -> Result<(), Self::Error> { async move { diff --git a/sv2/parsers-sv2/src/lib.rs b/sv2/parsers-sv2/src/lib.rs index c51d058cb6..b0dc5d41d3 100644 --- a/sv2/parsers-sv2/src/lib.rs +++ b/sv2/parsers-sv2/src/lib.rs @@ -136,21 +136,21 @@ pub fn message_type_to_name(msg_type: u8) -> &'static str { /// A parser of messages that are common to all Sv2 subprotocols, to be used for parsing raw /// messages #[derive(Clone, Debug, PartialEq)] -pub enum CommonMessages<'a> { +pub enum CommonMessages { /// Notifies about changes in channel endpoint configuration. ChannelEndpointChanged(ChannelEndpointChanged), /// Reconnects a client to a new server - Reconnect(Reconnect<'a>), + Reconnect(Reconnect), /// Initiates a connection between a client and server. - SetupConnection(SetupConnection<'a>), + SetupConnection(SetupConnection), /// Indicates an error during connection setup. - SetupConnectionError(SetupConnectionError<'a>), + SetupConnectionError(SetupConnectionError), /// Acknowledges successful connection setup. SetupConnectionSuccess(SetupConnectionSuccess), } -impl fmt::Display for CommonMessages<'_> { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { +impl fmt::Display for CommonMessages { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { CommonMessages::ChannelEndpointChanged(m) => write!(f, "{m}"), CommonMessages::Reconnect(m) => write!(f, "{m}"), @@ -163,18 +163,18 @@ impl fmt::Display for CommonMessages<'_> { /// A parser of messages of Template Distribution subprotocol, to be used for parsing raw messages #[derive(Clone, Debug)] -pub enum TemplateDistribution<'a> { +pub enum TemplateDistribution { CoinbaseOutputConstraints(CoinbaseOutputConstraints), - NewTemplate(NewTemplate<'a>), + NewTemplate(NewTemplate), RequestTransactionData(RequestTransactionData), - RequestTransactionDataError(RequestTransactionDataError<'a>), - RequestTransactionDataSuccess(RequestTransactionDataSuccess<'a>), - SetNewPrevHash(SetNewPrevHash<'a>), - SubmitSolution(SubmitSolution<'a>), + RequestTransactionDataError(RequestTransactionDataError), + RequestTransactionDataSuccess(RequestTransactionDataSuccess), + SetNewPrevHash(SetNewPrevHash), + SubmitSolution(SubmitSolution), } -impl fmt::Display for TemplateDistribution<'_> { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { +impl fmt::Display for TemplateDistribution { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { TemplateDistribution::CoinbaseOutputConstraints(m) => { write!(f, "CoinbaseOutputConstraints: {m}") @@ -197,19 +197,19 @@ impl fmt::Display for TemplateDistribution<'_> { /// A parser of messages of Job Declaration subprotocol, to be used for parsing raw messages #[derive(Clone, Debug)] -pub enum JobDeclaration<'a> { - AllocateMiningJobToken(AllocateMiningJobToken<'a>), - AllocateMiningJobTokenSuccess(AllocateMiningJobTokenSuccess<'a>), - DeclareMiningJob(DeclareMiningJob<'a>), - DeclareMiningJobError(DeclareMiningJobError<'a>), - DeclareMiningJobSuccess(DeclareMiningJobSuccess<'a>), - ProvideMissingTransactions(ProvideMissingTransactions<'a>), - ProvideMissingTransactionsSuccess(ProvideMissingTransactionsSuccess<'a>), - PushSolution(PushSolution<'a>), -} - -impl fmt::Display for JobDeclaration<'_> { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { +pub enum JobDeclaration { + AllocateMiningJobToken(AllocateMiningJobToken), + AllocateMiningJobTokenSuccess(AllocateMiningJobTokenSuccess), + DeclareMiningJob(DeclareMiningJob), + DeclareMiningJobError(DeclareMiningJobError), + DeclareMiningJobSuccess(DeclareMiningJobSuccess), + ProvideMissingTransactions(ProvideMissingTransactions), + ProvideMissingTransactionsSuccess(ProvideMissingTransactionsSuccess), + PushSolution(PushSolution), +} + +impl fmt::Display for JobDeclaration { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { JobDeclaration::AllocateMiningJobToken(m) => write!(f, "AllocateMiningJobToken: {m}"), JobDeclaration::AllocateMiningJobTokenSuccess(m) => { @@ -255,32 +255,32 @@ impl fmt::Display for JobDeclaration<'_> { /// unified interface for handling mining-related communication. This reduces complexity and /// ensures consistency across roles. #[derive(Clone, Debug)] -pub enum Mining<'a> { - CloseChannel(CloseChannel<'a>), - NewExtendedMiningJob(NewExtendedMiningJob<'a>), - NewMiningJob(NewMiningJob<'a>), - OpenExtendedMiningChannel(OpenExtendedMiningChannel<'a>), - OpenExtendedMiningChannelSuccess(OpenExtendedMiningChannelSuccess<'a>), - OpenMiningChannelError(OpenMiningChannelError<'a>), - OpenStandardMiningChannel(OpenStandardMiningChannel<'a>), - OpenStandardMiningChannelSuccess(OpenStandardMiningChannelSuccess<'a>), - SetCustomMiningJob(SetCustomMiningJob<'a>), - SetCustomMiningJobError(SetCustomMiningJobError<'a>), +pub enum Mining { + CloseChannel(CloseChannel), + NewExtendedMiningJob(NewExtendedMiningJob), + NewMiningJob(NewMiningJob), + OpenExtendedMiningChannel(OpenExtendedMiningChannel), + OpenExtendedMiningChannelSuccess(OpenExtendedMiningChannelSuccess), + OpenMiningChannelError(OpenMiningChannelError), + OpenStandardMiningChannel(OpenStandardMiningChannel), + OpenStandardMiningChannelSuccess(OpenStandardMiningChannelSuccess), + SetCustomMiningJob(SetCustomMiningJob), + SetCustomMiningJobError(SetCustomMiningJobError), SetCustomMiningJobSuccess(SetCustomMiningJobSuccess), - SetExtranoncePrefix(SetExtranoncePrefix<'a>), - SetGroupChannel(SetGroupChannel<'a>), - SetNewPrevHash(MiningSetNewPrevHash<'a>), - SetTarget(SetTarget<'a>), - SubmitSharesError(SubmitSharesError<'a>), - SubmitSharesExtended(SubmitSharesExtended<'a>), + SetExtranoncePrefix(SetExtranoncePrefix), + SetGroupChannel(SetGroupChannel), + SetNewPrevHash(MiningSetNewPrevHash), + SetTarget(SetTarget), + SubmitSharesError(SubmitSharesError), + SubmitSharesExtended(SubmitSharesExtended), SubmitSharesStandard(SubmitSharesStandard), SubmitSharesSuccess(SubmitSharesSuccess), - UpdateChannel(UpdateChannel<'a>), - UpdateChannelError(UpdateChannelError<'a>), + UpdateChannel(UpdateChannel), + UpdateChannelError(UpdateChannelError), } -impl fmt::Display for Mining<'_> { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { +impl fmt::Display for Mining { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { Mining::CloseChannel(m) => write!(f, "{m}"), Mining::NewExtendedMiningJob(m) => write!(f, "{m}"), @@ -307,9 +307,9 @@ impl fmt::Display for Mining<'_> { } } -impl Mining<'_> { +impl Mining { /// converter into static lifetime - pub fn into_static(self) -> Mining<'static> { + pub fn into_static(self) -> Mining { match self { Mining::CloseChannel(m) => Mining::CloseChannel(m.into_static()), Mining::NewExtendedMiningJob(m) => Mining::NewExtendedMiningJob(m.into_static()), @@ -346,9 +346,9 @@ impl Mining<'_> { } } -impl CommonMessages<'_> { +impl CommonMessages { /// converter into static lifetime - pub fn into_static(self) -> CommonMessages<'static> { + pub fn into_static(self) -> CommonMessages { match self { CommonMessages::ChannelEndpointChanged(m) => CommonMessages::ChannelEndpointChanged(m), CommonMessages::Reconnect(m) => CommonMessages::Reconnect(m.into_static()), @@ -361,9 +361,9 @@ impl CommonMessages<'_> { } } -impl TemplateDistribution<'_> { +impl TemplateDistribution { /// converter into static lifetime - pub fn into_static(self) -> TemplateDistribution<'static> { + pub fn into_static(self) -> TemplateDistribution { match self { TemplateDistribution::CoinbaseOutputConstraints(m) => { TemplateDistribution::CoinbaseOutputConstraints(m) @@ -390,9 +390,9 @@ impl TemplateDistribution<'_> { } } -impl JobDeclaration<'_> { +impl JobDeclaration { /// converter into static lifetime - pub fn into_static(self) -> JobDeclaration<'static> { + pub fn into_static(self) -> JobDeclaration { match self { JobDeclaration::AllocateMiningJobToken(m) => { JobDeclaration::AllocateMiningJobToken(m.into_static()) @@ -425,14 +425,14 @@ impl JobDeclaration<'_> { /// These messages allow endpoints to negotiate which optional extensions are supported /// during connection setup. #[derive(Clone, Debug)] -pub enum ExtensionsNegotiation<'a> { - RequestExtensions(RequestExtensions<'a>), - RequestExtensionsSuccess(RequestExtensionsSuccess<'a>), - RequestExtensionsError(RequestExtensionsError<'a>), +pub enum ExtensionsNegotiation { + RequestExtensions(RequestExtensions), + RequestExtensionsSuccess(RequestExtensionsSuccess), + RequestExtensionsError(RequestExtensionsError), } -impl fmt::Display for ExtensionsNegotiation<'_> { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { +impl fmt::Display for ExtensionsNegotiation { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { ExtensionsNegotiation::RequestExtensions(m) => write!(f, "{m}"), ExtensionsNegotiation::RequestExtensionsSuccess(m) => write!(f, "{m}"), @@ -441,9 +441,9 @@ impl fmt::Display for ExtensionsNegotiation<'_> { } } -impl ExtensionsNegotiation<'_> { +impl ExtensionsNegotiation { /// converter into static lifetime - pub fn into_static(self) -> ExtensionsNegotiation<'static> { + pub fn into_static(self) -> ExtensionsNegotiation { match self { ExtensionsNegotiation::RequestExtensions(m) => { ExtensionsNegotiation::RequestExtensions(m.into_static()) @@ -471,22 +471,22 @@ impl ExtensionsNegotiation<'_> { /// /// Future extension types will be added as new variants (e.g., Worker Hashrate Tracking). #[derive(Clone, Debug)] -pub enum Extensions<'a> { +pub enum Extensions { /// Extensions Negotiation messages (extension_type=0x0001) - ExtensionsNegotiation(ExtensionsNegotiation<'a>), + ExtensionsNegotiation(ExtensionsNegotiation), } -impl fmt::Display for Extensions<'_> { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { +impl fmt::Display for Extensions { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { Extensions::ExtensionsNegotiation(m) => write!(f, "{m}"), } } } -impl Extensions<'_> { +impl Extensions { /// converter into static lifetime - pub fn into_static(self) -> Extensions<'static> { + pub fn into_static(self) -> Extensions { match self { Extensions::ExtensionsNegotiation(m) => { Extensions::ExtensionsNegotiation(m.into_static()) @@ -495,9 +495,9 @@ impl Extensions<'_> { } } -impl AnyMessage<'_> { +impl AnyMessage { /// converter into static lifetime - pub fn into_static(self) -> AnyMessage<'static> { + pub fn into_static(self) -> AnyMessage { match self { AnyMessage::Common(m) => AnyMessage::Common(m.into_static()), AnyMessage::Mining(m) => AnyMessage::Mining(m.into_static()), @@ -515,9 +515,9 @@ pub fn parse_message_frame_with_tlvs( header: Header, payload: &mut [u8], negotiated_extensions: &[u16], -) -> Result<(AnyMessage<'static>, Option>), ParserError> { +) -> Result<(AnyMessage, Option>), ParserError> { let raw_payload = payload.to_vec(); - let message: AnyMessage<'_> = (header, payload).try_into()?; + let message: AnyMessage = (header, payload).try_into()?; let message_size = message.get_size(); let tlvs = extract_tlv_fields(&raw_payload, message_size, negotiated_extensions); Ok((message.into_static(), tlvs)) @@ -545,7 +545,7 @@ pub trait IsSv2Message { fn extension_type(&self) -> u16; } -impl IsSv2Message for CommonMessages<'_> { +impl IsSv2Message for CommonMessages { fn message_type(&self) -> u8 { match self { Self::ChannelEndpointChanged(_) => MESSAGE_TYPE_CHANNEL_ENDPOINT_CHANGED, @@ -571,7 +571,7 @@ impl IsSv2Message for CommonMessages<'_> { } } -impl IsSv2Message for TemplateDistribution<'_> { +impl IsSv2Message for TemplateDistribution { fn message_type(&self) -> u8 { match self { Self::CoinbaseOutputConstraints(_) => MESSAGE_TYPE_COINBASE_OUTPUT_CONSTRAINTS, @@ -599,7 +599,7 @@ impl IsSv2Message for TemplateDistribution<'_> { 0 // Template Distribution messages are not extensions } } -impl IsSv2Message for JobDeclaration<'_> { +impl IsSv2Message for JobDeclaration { fn message_type(&self) -> u8 { match self { Self::AllocateMiningJobToken(_) => MESSAGE_TYPE_ALLOCATE_MINING_JOB_TOKEN, @@ -635,7 +635,7 @@ impl IsSv2Message for JobDeclaration<'_> { 0 // Job Declaration messages are not extensions } } -impl IsSv2Message for Mining<'_> { +impl IsSv2Message for Mining { fn message_type(&self) -> u8 { match self { Self::CloseChannel(_) => MESSAGE_TYPE_CLOSE_CHANNEL, @@ -701,7 +701,7 @@ impl IsSv2Message for Mining<'_> { } } -impl IsSv2Message for Extensions<'_> { +impl IsSv2Message for Extensions { fn message_type(&self) -> u8 { match self { Self::ExtensionsNegotiation(m) => match m { @@ -737,8 +737,8 @@ impl IsSv2Message for Extensions<'_> { } } -impl<'decoder> From> for EncodableField<'decoder> { - fn from(m: CommonMessages<'decoder>) -> Self { +impl From for EncodableField { + fn from(m: CommonMessages) -> Self { match m { CommonMessages::ChannelEndpointChanged(a) => a.into(), CommonMessages::Reconnect(a) => a.into(), @@ -748,8 +748,8 @@ impl<'decoder> From> for EncodableField<'decoder> { } } } -impl<'decoder> From> for EncodableField<'decoder> { - fn from(m: TemplateDistribution<'decoder>) -> Self { +impl From for EncodableField { + fn from(m: TemplateDistribution) -> Self { match m { TemplateDistribution::CoinbaseOutputConstraints(a) => a.into(), TemplateDistribution::NewTemplate(a) => a.into(), @@ -761,8 +761,8 @@ impl<'decoder> From> for EncodableField<'decoder> } } } -impl<'decoder> From> for EncodableField<'decoder> { - fn from(m: JobDeclaration<'decoder>) -> Self { +impl From for EncodableField { + fn from(m: JobDeclaration) -> Self { match m { JobDeclaration::AllocateMiningJobToken(a) => a.into(), JobDeclaration::AllocateMiningJobTokenSuccess(a) => a.into(), @@ -776,8 +776,8 @@ impl<'decoder> From> for EncodableField<'decoder> { } } -impl<'decoder> From> for EncodableField<'decoder> { - fn from(m: Mining<'decoder>) -> Self { +impl From for EncodableField { + fn from(m: Mining) -> Self { match m { Mining::CloseChannel(a) => a.into(), Mining::NewExtendedMiningJob(a) => a.into(), @@ -804,7 +804,7 @@ impl<'decoder> From> for EncodableField<'decoder> { } } -impl GetSize for CommonMessages<'_> { +impl GetSize for CommonMessages { fn get_size(&self) -> usize { match self { CommonMessages::ChannelEndpointChanged(a) => a.get_size(), @@ -815,7 +815,7 @@ impl GetSize for CommonMessages<'_> { } } } -impl GetSize for TemplateDistribution<'_> { +impl GetSize for TemplateDistribution { fn get_size(&self) -> usize { match self { TemplateDistribution::CoinbaseOutputConstraints(a) => a.get_size(), @@ -828,7 +828,7 @@ impl GetSize for TemplateDistribution<'_> { } } } -impl GetSize for JobDeclaration<'_> { +impl GetSize for JobDeclaration { fn get_size(&self) -> usize { match self { JobDeclaration::AllocateMiningJobToken(a) => a.get_size(), @@ -842,7 +842,7 @@ impl GetSize for JobDeclaration<'_> { } } } -impl GetSize for Mining<'_> { +impl GetSize for Mining { fn get_size(&self) -> usize { match self { Mining::CloseChannel(a) => a.get_size(), @@ -870,8 +870,8 @@ impl GetSize for Mining<'_> { } } -impl<'decoder> From> for EncodableField<'decoder> { - fn from(m: Extensions<'decoder>) -> Self { +impl From for EncodableField { + fn from(m: Extensions) -> Self { match m { Extensions::ExtensionsNegotiation(ext) => match ext { ExtensionsNegotiation::RequestExtensions(a) => a.into(), @@ -882,7 +882,7 @@ impl<'decoder> From> for EncodableField<'decoder> { } } -impl GetSize for Extensions<'_> { +impl GetSize for Extensions { fn get_size(&self) -> usize { match self { Extensions::ExtensionsNegotiation(m) => match m { @@ -894,75 +894,75 @@ impl GetSize for Extensions<'_> { } } -impl<'decoder> Deserialize<'decoder> for CommonMessages<'decoder> { +impl Deserialize for CommonMessages { fn get_structure(_v: &[u8]) -> core::result::Result, binary_sv2::Error> { unimplemented!() } fn from_decoded_fields( - _v: Vec>, + _v: Vec, ) -> core::result::Result { unimplemented!() } } -impl<'decoder> Deserialize<'decoder> for TemplateDistribution<'decoder> { +impl Deserialize for TemplateDistribution { fn get_structure(_v: &[u8]) -> core::result::Result, binary_sv2::Error> { unimplemented!() } fn from_decoded_fields( - _v: Vec>, + _v: Vec, ) -> core::result::Result { unimplemented!() } } -impl<'decoder> Deserialize<'decoder> for JobDeclaration<'decoder> { +impl Deserialize for JobDeclaration { fn get_structure(_v: &[u8]) -> core::result::Result, binary_sv2::Error> { unimplemented!() } fn from_decoded_fields( - _v: Vec>, + _v: Vec, ) -> core::result::Result { unimplemented!() } } -impl<'decoder> Deserialize<'decoder> for Mining<'decoder> { +impl Deserialize for Mining { fn get_structure(_v: &[u8]) -> core::result::Result, binary_sv2::Error> { unimplemented!() } fn from_decoded_fields( - _v: Vec>, + _v: Vec, ) -> core::result::Result { unimplemented!() } } -impl<'decoder> Deserialize<'decoder> for Extensions<'decoder> { +impl Deserialize for Extensions { fn get_structure(_v: &[u8]) -> core::result::Result, binary_sv2::Error> { unimplemented!() } fn from_decoded_fields( - _v: Vec>, + _v: Vec, ) -> core::result::Result { unimplemented!() } } -impl<'decoder> Deserialize<'decoder> for AnyMessage<'decoder> { +impl Deserialize for AnyMessage { fn get_structure(_v: &[u8]) -> core::result::Result, binary_sv2::Error> { unimplemented!() } fn from_decoded_fields( - _v: Vec>, + _v: Vec, ) -> core::result::Result { unimplemented!() } } -impl<'decoder> Deserialize<'decoder> for MiningDeviceMessages<'decoder> { +impl Deserialize for MiningDeviceMessages { fn get_structure(_v: &[u8]) -> core::result::Result, binary_sv2::Error> { unimplemented!() } fn from_decoded_fields( - _v: Vec>, + _v: Vec, ) -> core::result::Result { unimplemented!() } @@ -995,14 +995,14 @@ impl TryFrom for CommonMessageTypes { } } -impl<'a> TryFrom<(u8, &'a mut [u8])> for CommonMessages<'a> { +impl<'a> TryFrom<(u8, &'a mut [u8])> for CommonMessages { type Error = ParserError; fn try_from(v: (u8, &'a mut [u8])) -> Result { let msg_type: CommonMessageTypes = v.0.try_into()?; match msg_type { CommonMessageTypes::SetupConnection => { - let message: SetupConnection<'a> = from_bytes(v.1)?; + let message: SetupConnection = from_bytes(v.1)?; Ok(CommonMessages::SetupConnection(message)) } CommonMessageTypes::SetupConnectionSuccess => { @@ -1010,7 +1010,7 @@ impl<'a> TryFrom<(u8, &'a mut [u8])> for CommonMessages<'a> { Ok(CommonMessages::SetupConnectionSuccess(message)) } CommonMessageTypes::SetupConnectionError => { - let message: SetupConnectionError<'a> = from_bytes(v.1)?; + let message: SetupConnectionError = from_bytes(v.1)?; Ok(CommonMessages::SetupConnectionError(message)) } CommonMessageTypes::ChannelEndpointChanged => { @@ -1064,7 +1064,7 @@ impl TryFrom for TemplateDistributionTypes { } } -impl<'a> TryFrom<(u8, &'a mut [u8])> for TemplateDistribution<'a> { +impl<'a> TryFrom<(u8, &'a mut [u8])> for TemplateDistribution { type Error = ParserError; fn try_from(v: (u8, &'a mut [u8])) -> Result { @@ -1075,11 +1075,11 @@ impl<'a> TryFrom<(u8, &'a mut [u8])> for TemplateDistribution<'a> { Ok(TemplateDistribution::CoinbaseOutputConstraints(message)) } TemplateDistributionTypes::NewTemplate => { - let message: NewTemplate<'a> = from_bytes(v.1)?; + let message: NewTemplate = from_bytes(v.1)?; Ok(TemplateDistribution::NewTemplate(message)) } TemplateDistributionTypes::SetNewPrevHash => { - let message: SetNewPrevHash<'a> = from_bytes(v.1)?; + let message: SetNewPrevHash = from_bytes(v.1)?; Ok(TemplateDistribution::SetNewPrevHash(message)) } TemplateDistributionTypes::RequestTransactionData => { @@ -1145,7 +1145,7 @@ impl TryFrom for JobDeclarationTypes { } } -impl<'a> TryFrom<(u8, &'a mut [u8])> for JobDeclaration<'a> { +impl<'a> TryFrom<(u8, &'a mut [u8])> for JobDeclaration { type Error = ParserError; fn try_from(v: (u8, &'a mut [u8])) -> Result { @@ -1253,7 +1253,7 @@ impl TryFrom for MiningTypes { } } -impl<'a> TryFrom<(u8, &'a mut [u8])> for Mining<'a> { +impl<'a> TryFrom<(u8, &'a mut [u8])> for Mining { type Error = ParserError; fn try_from(v: (u8, &'a mut [u8])) -> Result { @@ -1378,7 +1378,7 @@ impl TryFrom for ExtensionsNegotiationTypes { /// Note: The channel_msg bit (bit 15) is automatically stripped from extension_type /// to ensure correct matching regardless of whether the caller passes the raw header /// value or a pre-processed one. -impl<'a> TryFrom<(u16, u8, &'a mut [u8])> for Extensions<'a> { +impl<'a> TryFrom<(u16, u8, &'a mut [u8])> for Extensions { type Error = ParserError; fn try_from(v: (u16, u8, &'a mut [u8])) -> Result { @@ -1419,13 +1419,13 @@ impl<'a> TryFrom<(u16, u8, &'a mut [u8])> for Extensions<'a> { /// A parser of messages that a Mining Device could send #[derive(Clone, Debug)] -pub enum MiningDeviceMessages<'a> { - Common(CommonMessages<'a>), - Mining(Mining<'a>), - Extensions(Extensions<'a>), +pub enum MiningDeviceMessages { + Common(CommonMessages), + Mining(Mining), + Extensions(Extensions), } -impl<'decoder> From> for EncodableField<'decoder> { - fn from(m: MiningDeviceMessages<'decoder>) -> Self { +impl From for EncodableField { + fn from(m: MiningDeviceMessages) -> Self { match m { MiningDeviceMessages::Common(a) => a.into(), MiningDeviceMessages::Mining(a) => a.into(), @@ -1433,7 +1433,7 @@ impl<'decoder> From> for EncodableField<'decoder> } } } -impl GetSize for MiningDeviceMessages<'_> { +impl GetSize for MiningDeviceMessages { fn get_size(&self) -> usize { match self { MiningDeviceMessages::Common(a) => a.get_size(), @@ -1442,7 +1442,7 @@ impl GetSize for MiningDeviceMessages<'_> { } } } -impl<'a> TryFrom<(u8, &'a mut [u8])> for MiningDeviceMessages<'a> { +impl<'a> TryFrom<(u8, &'a mut [u8])> for MiningDeviceMessages { type Error = ParserError; fn try_from(v: (u8, &'a mut [u8])) -> Result { @@ -1460,16 +1460,16 @@ impl<'a> TryFrom<(u8, &'a mut [u8])> for MiningDeviceMessages<'a> { /// A parser of all possible SV2 messages #[derive(Clone, Debug)] -pub enum AnyMessage<'a> { - Common(CommonMessages<'a>), - Mining(Mining<'a>), - JobDeclaration(JobDeclaration<'a>), - TemplateDistribution(TemplateDistribution<'a>), - Extensions(Extensions<'a>), +pub enum AnyMessage { + Common(CommonMessages), + Mining(Mining), + JobDeclaration(JobDeclaration), + TemplateDistribution(TemplateDistribution), + Extensions(Extensions), } -impl fmt::Display for AnyMessage<'_> { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { +impl fmt::Display for AnyMessage { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { AnyMessage::Common(m) => write!(f, "CommonMessage: {m}"), AnyMessage::Mining(m) => write!(f, "MiningMessage: {m}"), @@ -1480,10 +1480,10 @@ impl fmt::Display for AnyMessage<'_> { } } -impl<'a> TryFrom> for AnyMessage<'a> { +impl TryFrom for AnyMessage { type Error = ParserError; - fn try_from(value: MiningDeviceMessages<'a>) -> Result { + fn try_from(value: MiningDeviceMessages) -> Result { match value { MiningDeviceMessages::Common(m) => Ok(AnyMessage::Common(m)), MiningDeviceMessages::Mining(m) => Ok(AnyMessage::Mining(m)), @@ -1492,8 +1492,8 @@ impl<'a> TryFrom> for AnyMessage<'a> { } } -impl<'decoder> From> for EncodableField<'decoder> { - fn from(m: AnyMessage<'decoder>) -> Self { +impl From for EncodableField { + fn from(m: AnyMessage) -> Self { match m { AnyMessage::Common(a) => a.into(), AnyMessage::Mining(a) => a.into(), @@ -1503,7 +1503,7 @@ impl<'decoder> From> for EncodableField<'decoder> { } } } -impl GetSize for AnyMessage<'_> { +impl GetSize for AnyMessage { fn get_size(&self) -> usize { match self { AnyMessage::Common(a) => a.get_size(), @@ -1515,7 +1515,7 @@ impl GetSize for AnyMessage<'_> { } } -impl IsSv2Message for AnyMessage<'_> { +impl IsSv2Message for AnyMessage { fn message_type(&self) -> u8 { match self { AnyMessage::Common(a) => a.message_type(), @@ -1547,7 +1547,7 @@ impl IsSv2Message for AnyMessage<'_> { } } -impl IsSv2Message for MiningDeviceMessages<'_> { +impl IsSv2Message for MiningDeviceMessages { fn message_type(&self) -> u8 { match self { MiningDeviceMessages::Common(a) => a.message_type(), @@ -1578,7 +1578,7 @@ impl IsSv2Message for MiningDeviceMessages<'_> { /// This implementation handles all message types including Extensions messages which require /// both extension_type and message_type to be correctly parsed. Standard protocol messages /// (Common, Mining, etc.) have extension_type == 0 and only need the message_type. -impl<'a> TryFrom<(Header, &'a mut [u8])> for AnyMessage<'a> { +impl<'a> TryFrom<(Header, &'a mut [u8])> for AnyMessage { type Error = ParserError; fn try_from(v: (Header, &'a mut [u8])) -> Result { @@ -1626,76 +1626,76 @@ impl<'a> TryFrom<(Header, &'a mut [u8])> for AnyMessage<'a> { } } -impl<'a> From> for CommonMessages<'a> { - fn from(v: SetupConnection<'a>) -> Self { +impl From for CommonMessages { + fn from(v: SetupConnection) -> Self { CommonMessages::SetupConnection(v) } } -impl From for CommonMessages<'_> { +impl From for CommonMessages { fn from(v: SetupConnectionSuccess) -> Self { CommonMessages::SetupConnectionSuccess(v) } } -impl<'a> From> for CommonMessages<'a> { - fn from(v: SetupConnectionError<'a>) -> Self { +impl From for CommonMessages { + fn from(v: SetupConnectionError) -> Self { CommonMessages::SetupConnectionError(v) } } -impl<'a> From> for Extensions<'a> { - fn from(v: RequestExtensions<'a>) -> Self { +impl From for Extensions { + fn from(v: RequestExtensions) -> Self { Extensions::ExtensionsNegotiation(ExtensionsNegotiation::RequestExtensions(v)) } } -impl<'a> From> for Extensions<'a> { - fn from(v: RequestExtensionsSuccess<'a>) -> Self { +impl From for Extensions { + fn from(v: RequestExtensionsSuccess) -> Self { Extensions::ExtensionsNegotiation(ExtensionsNegotiation::RequestExtensionsSuccess(v)) } } -impl<'a> From> for Extensions<'a> { - fn from(v: RequestExtensionsError<'a>) -> Self { +impl From for Extensions { + fn from(v: RequestExtensionsError) -> Self { Extensions::ExtensionsNegotiation(ExtensionsNegotiation::RequestExtensionsError(v)) } } -impl<'a> From> for Mining<'a> { - fn from(v: OpenStandardMiningChannel<'a>) -> Self { +impl From for Mining { + fn from(v: OpenStandardMiningChannel) -> Self { Mining::OpenStandardMiningChannel(v) } } -impl<'a> From> for Mining<'a> { - fn from(v: UpdateChannel<'a>) -> Self { +impl From for Mining { + fn from(v: UpdateChannel) -> Self { Mining::UpdateChannel(v) } } -impl<'a> From> for Mining<'a> { - fn from(v: OpenStandardMiningChannelSuccess<'a>) -> Self { +impl From for Mining { + fn from(v: OpenStandardMiningChannelSuccess) -> Self { Mining::OpenStandardMiningChannelSuccess(v) } } -impl<'a, T: Into>> From for AnyMessage<'a> { +impl<'a, T: Into> From for AnyMessage { fn from(v: T) -> Self { AnyMessage::Common(v.into()) } } -impl<'a, T: Into>> From for MiningDeviceMessages<'a> { +impl<'a, T: Into> From for MiningDeviceMessages { fn from(v: T) -> Self { MiningDeviceMessages::Common(v.into()) } } -impl<'decoder, B: AsMut<[u8]> + AsRef<[u8]>> TryFrom> - for Sv2Frame, B> +impl<'decoder, B: AsMut<[u8]> + AsRef<[u8]>> TryFrom + for Sv2Frame { type Error = ParserError; - fn try_from(v: AnyMessage<'decoder>) -> Result { + fn try_from(v: AnyMessage) -> Result { let extension_type = v.extension_type(); let channel_bit = v.channel_bit(); let message_type = v.message_type(); @@ -1704,12 +1704,12 @@ impl<'decoder, B: AsMut<[u8]> + AsRef<[u8]>> TryFrom> } } -impl<'decoder, B: AsMut<[u8]> + AsRef<[u8]>> TryFrom> - for Sv2Frame, B> +impl<'decoder, B: AsMut<[u8]> + AsRef<[u8]>> TryFrom + for Sv2Frame { type Error = ParserError; - fn try_from(v: MiningDeviceMessages<'decoder>) -> Result { + fn try_from(v: MiningDeviceMessages) -> Result { let extension_type = v.extension_type(); let channel_bit = v.channel_bit(); let message_type = v.message_type(); @@ -1718,12 +1718,12 @@ impl<'decoder, B: AsMut<[u8]> + AsRef<[u8]>> TryFrom + AsRef<[u8]>> TryFrom> - for Sv2Frame, B> +impl<'decoder, B: AsMut<[u8]> + AsRef<[u8]>> TryFrom + for Sv2Frame { type Error = ParserError; - fn try_from(v: TemplateDistribution<'decoder>) -> Result { + fn try_from(v: TemplateDistribution) -> Result { let extension_type = 0; let channel_bit = v.channel_bit(); let message_type = v.message_type(); @@ -1732,10 +1732,10 @@ impl<'decoder, B: AsMut<[u8]> + AsRef<[u8]>> TryFrom TryFrom> for MiningDeviceMessages<'a> { +impl TryFrom for MiningDeviceMessages { type Error = ParserError; - fn try_from(value: AnyMessage<'a>) -> Result { + fn try_from(value: AnyMessage) -> Result { match value { AnyMessage::Common(message) => Ok(Self::Common(message)), AnyMessage::Mining(message) => Ok(Self::Mining(message)), @@ -1757,7 +1757,7 @@ mod test { use extensions_sv2::{RequestExtensions, EXTENSION_TYPE_EXTENSIONS_NEGOTIATION}; use mining_sv2::NewMiningJob; - pub type Message = AnyMessage<'static>; + pub type Message = AnyMessage; pub type StdFrame = StandardSv2Frame; #[test] @@ -1807,7 +1807,7 @@ mod test { message_serialization_check(mining_message, CORRECTLY_SERIALIZED_MSG); } - fn message_serialization_check(message: AnyMessage<'static>, expected_result: &[u8]) { + fn message_serialization_check(message: AnyMessage, expected_result: &[u8]) { let frame = StdFrame::try_from(message).unwrap(); let encoded_frame_length = frame.encoded_length(); diff --git a/sv2/subprotocols/common-messages/src/reconnect.rs b/sv2/subprotocols/common-messages/src/reconnect.rs index eff4cf95cf..a3ea9fb023 100644 --- a/sv2/subprotocols/common-messages/src/reconnect.rs +++ b/sv2/subprotocols/common-messages/src/reconnect.rs @@ -13,14 +13,14 @@ use core::convert::TryInto; /// not be able to redirect hashrate to an arbitrary server in case the pool server get compromised /// and instructed to send reconnects to a new location. #[derive(Serialize, Deserialize, Debug, Clone)] -pub struct Reconnect<'decoder> { +pub struct Reconnect { /// When empty, downstream node should attempt to reconnect to current pool host. - pub new_host: Str0255<'decoder>, + pub new_host: Str0255, /// When 0, downstream node should attempt to reconnect to current pool host. pub new_port: u16, } -impl fmt::Display for Reconnect<'_> { +impl fmt::Display for Reconnect { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!( f, @@ -31,7 +31,7 @@ impl fmt::Display for Reconnect<'_> { } } -impl PartialEq for Reconnect<'_> { +impl PartialEq for Reconnect { fn eq(&self, other: &Self) -> bool { self.new_host.as_ref() == other.new_host.as_ref() && self.new_port == other.new_port } diff --git a/sv2/subprotocols/common-messages/src/setup_connection.rs b/sv2/subprotocols/common-messages/src/setup_connection.rs index b631c9c1e6..0d632613ab 100644 --- a/sv2/subprotocols/common-messages/src/setup_connection.rs +++ b/sv2/subprotocols/common-messages/src/setup_connection.rs @@ -24,7 +24,7 @@ use core::convert::{TryFrom, TryInto}; /// A valid response to this message from the upstream role can either be [`SetupConnectionSuccess`] /// or [`SetupConnectionError`] message. #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)] -pub struct SetupConnection<'decoder> { +pub struct SetupConnection { /// Protocol to be used for the connection. pub protocol: Protocol, /// The minimum protocol version supported. @@ -40,20 +40,20 @@ pub struct SetupConnection<'decoder> { /// Each [`SetupConnection::protocol`] value has it's own flags. pub flags: u32, /// ASCII representation of the connection hostname or IP address. - pub endpoint_host: Str0255<'decoder>, + pub endpoint_host: Str0255, /// Connection port value. pub endpoint_port: u16, /// Device vendor name. - pub vendor: Str0255<'decoder>, + pub vendor: Str0255, /// Device hardware version. - pub hardware_version: Str0255<'decoder>, + pub hardware_version: Str0255, /// Device firmware version. - pub firmware: Str0255<'decoder>, + pub firmware: Str0255, /// Device identifier. - pub device_id: Str0255<'decoder>, + pub device_id: Str0255, } -impl fmt::Display for SetupConnection<'_> { +impl fmt::Display for SetupConnection { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!( f, @@ -72,7 +72,7 @@ impl fmt::Display for SetupConnection<'_> { } } -impl SetupConnection<'_> { +impl SetupConnection { /// Set the flag to indicate that the downstream requires a standard job pub fn set_requires_standard_job(&mut self) { self.flags |= 0b_0000_0000_0000_0000_0000_0000_0000_0001; @@ -240,7 +240,7 @@ impl fmt::Display for SetupConnectionSuccess { /// [`SetupConnectionError`] message and must consistently support the same set of flags across all /// servers on the same hostname and port number. #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)] -pub struct SetupConnectionError<'decoder> { +pub struct SetupConnectionError { /// Unsupported feature flags. /// /// In case `error_code` is `unsupported-feature-flags`, this field is used to indicate which @@ -252,10 +252,10 @@ pub struct SetupConnectionError<'decoder> { /// - unsupported-feature-flags /// - unsupported-protocol /// - protocol-version-mismatch - pub error_code: Str0255<'decoder>, + pub error_code: Str0255, } -impl fmt::Display for SetupConnectionError<'_> { +impl fmt::Display for SetupConnectionError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!( f, @@ -279,14 +279,14 @@ pub enum Protocol { TemplateDistributionProtocol = SV2_TEMPLATE_DISTRIBUTION_PROTOCOL_DISCRIMINANT, } -impl From for binary_sv2::encodable::EncodableField<'_> { +impl From for binary_sv2::encodable::EncodableField { fn from(v: Protocol) -> Self { let val = v as u8; val.into() } } -impl<'decoder> binary_sv2::Decodable<'decoder> for Protocol { +impl binary_sv2::Decodable for Protocol { fn get_structure( _: &[u8], ) -> core::result::Result, binary_sv2::Error> { @@ -294,7 +294,7 @@ impl<'decoder> binary_sv2::Decodable<'decoder> for Protocol { Ok(alloc::vec![field]) } fn from_decoded_fields( - mut v: alloc::vec::Vec>, + mut v: alloc::vec::Vec, ) -> core::result::Result { let val = v.pop().ok_or(binary_sv2::Error::NoDecodableFieldPassed)?; let val: u8 = val.try_into()?; @@ -391,7 +391,7 @@ mod test { assert!(!has_work_selection(flags)); } - fn create_setup_connection() -> SetupConnection<'static> { + fn create_setup_connection() -> SetupConnection { SetupConnection { protocol: Protocol::MiningProtocol, min_version: 1, diff --git a/sv2/subprotocols/job-declaration/src/allocate_mining_job_token.rs b/sv2/subprotocols/job-declaration/src/allocate_mining_job_token.rs index e1a9a3e47e..68d0e53f53 100644 --- a/sv2/subprotocols/job-declaration/src/allocate_mining_job_token.rs +++ b/sv2/subprotocols/job-declaration/src/allocate_mining_job_token.rs @@ -5,16 +5,16 @@ use core::convert::TryInto; /// Message used by JDC to request an identifier for a future mining job from JDS. #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)] #[repr(C)] -pub struct AllocateMiningJobToken<'decoder> { +pub struct AllocateMiningJobToken { /// Unconstrained sequence of bytes. Whatever is needed by the JDS to /// identify/authenticate the client. Additional restrictions can be imposed by the /// JDS. It is highly recommended that UTF-8 encoding is used. - pub user_identifier: Str0255<'decoder>, + pub user_identifier: Str0255, /// A unique identifier for pairing the response/request. pub request_id: u32, } -impl fmt::Display for AllocateMiningJobToken<'_> { +impl fmt::Display for AllocateMiningJobToken { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!( f, @@ -28,19 +28,19 @@ impl fmt::Display for AllocateMiningJobToken<'_> { /// Message used by JDS to accept [`AllocateMiningJobToken`] message. #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)] #[repr(C)] -pub struct AllocateMiningJobTokenSuccess<'decoder> { +pub struct AllocateMiningJobTokenSuccess { /// A unique identifier for pairing the response/request. /// /// This **must** be the same as the received [`AllocateMiningJobToken::request_id`]. pub request_id: u32, /// A token that makes the JDC eligible for committing a mining job for approval/transactions /// declaration or for identifying custom mining job on mining connection. - pub mining_job_token: B0255<'decoder>, + pub mining_job_token: B0255, /// Bitcoin transaction outputs added by JDS. - pub coinbase_outputs: B064K<'decoder>, + pub coinbase_outputs: B064K, } -impl fmt::Display for AllocateMiningJobTokenSuccess<'_> { +impl fmt::Display for AllocateMiningJobTokenSuccess { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!( f, diff --git a/sv2/subprotocols/job-declaration/src/declare_mining_job.rs b/sv2/subprotocols/job-declaration/src/declare_mining_job.rs index bbf4a2357b..dea7ddacf0 100644 --- a/sv2/subprotocols/job-declaration/src/declare_mining_job.rs +++ b/sv2/subprotocols/job-declaration/src/declare_mining_job.rs @@ -10,31 +10,31 @@ use core::convert::TryInto; /// [`Full Template`]: https://github.com/stratum-mining/sv2-spec/blob/main/06-Job-Declaration-Protocol.md#632-full-template-mode #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)] #[repr(C)] -pub struct DeclareMiningJob<'decoder> { +pub struct DeclareMiningJob { /// A unique identifier for this request. /// /// Used for pairing request/response. pub request_id: u32, /// Token received previously through [`crate::AllocateMiningJobTokenSuccess`] message. - pub mining_job_token: B0255<'decoder>, + pub mining_job_token: B0255, /// Header version field. pub version: u32, /// Serialized bytes representing the initial part of the coinbase transaction (not including /// extranonce) - pub coinbase_tx_prefix: B064K<'decoder>, + pub coinbase_tx_prefix: B064K, /// Serialized bytes representing the final part of the coinbase transaction (after extranonce) - pub coinbase_tx_suffix: B064K<'decoder>, + pub coinbase_tx_suffix: B064K, /// List of wtxid contained in the template. JDS checks the list against its /// mempool and requests missing txs via [`crate::ProvideMissingTransactions`]. /// /// This list Does not include the coinbase transaction (as there is no corresponding full data /// for it yet). - pub wtxid_list: Seq064K<'decoder, U256<'decoder>>, + pub wtxid_list: Seq064K, /// Extra data which the JDS may require to validate the work. - pub excess_data: B064K<'decoder>, + pub excess_data: B064K, } -impl fmt::Display for DeclareMiningJob<'_> { +impl fmt::Display for DeclareMiningJob { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!( f, @@ -58,7 +58,7 @@ impl fmt::Display for DeclareMiningJob<'_> { /// [`Full Template`]: https://github.com/stratum-mining/sv2-spec/blob/main/06-Job-Declaration-Protocol.md#632-full-template-mode #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)] #[repr(C)] -pub struct DeclareMiningJobSuccess<'decoder> { +pub struct DeclareMiningJobSuccess { /// A unique identifier for this request. /// /// Must be the same as the received [`DeclareMiningJob::request_id`]. @@ -67,10 +67,10 @@ pub struct DeclareMiningJobSuccess<'decoder> { /// to start mining on a non declared job. If the token is different (irrespective of if the /// downstream is already mining using it), the downstream **must** send a `SetCustomMiningJob` /// message on each connection which wishes to mine using the declared job. - pub new_mining_job_token: B0255<'decoder>, + pub new_mining_job_token: B0255, } -impl fmt::Display for DeclareMiningJobSuccess<'_> { +impl fmt::Display for DeclareMiningJobSuccess { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!( f, @@ -87,7 +87,7 @@ impl fmt::Display for DeclareMiningJobSuccess<'_> { /// mining. #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)] #[repr(C)] -pub struct DeclareMiningJobError<'decoder> { +pub struct DeclareMiningJobError { /// The unique identifier of the request. /// /// Must be the same as the received [`DeclareMiningJob::request_id`]. @@ -96,12 +96,12 @@ pub struct DeclareMiningJobError<'decoder> { /// /// - invalid-mining-job-token /// - invalid-job-param-value-{DeclareMiningJob::field} - pub error_code: Str0255<'decoder>, + pub error_code: Str0255, /// Optional details about the error. - pub error_details: B064K<'decoder>, + pub error_details: B064K, } -impl fmt::Display for DeclareMiningJobError<'_> { +impl fmt::Display for DeclareMiningJobError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!( f, diff --git a/sv2/subprotocols/job-declaration/src/provide_missing_transactions.rs b/sv2/subprotocols/job-declaration/src/provide_missing_transactions.rs index f707efca88..745304d67e 100644 --- a/sv2/subprotocols/job-declaration/src/provide_missing_transactions.rs +++ b/sv2/subprotocols/job-declaration/src/provide_missing_transactions.rs @@ -17,7 +17,7 @@ use core::convert::TryInto; /// [`Full Template`]: https://github.com/stratum-mining/sv2-spec/blob/main/06-Job-Declaration-Protocol.md#632-full-template-mode #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)] #[repr(C)] -pub struct ProvideMissingTransactions<'decoder> { +pub struct ProvideMissingTransactions { /// Unique Identifier. /// /// Must be the same as the received [`crate::DeclareMiningJob::request_id`]. @@ -25,10 +25,10 @@ pub struct ProvideMissingTransactions<'decoder> { /// A list of unrecognized transactions that need to be supplied by the JDC in full. They are /// specified by their position in the original [`crate::DeclareMiningJob`] message, 0-indexed /// not including the coinbase transaction transaction. - pub unknown_tx_position_list: Seq064K<'decoder, u16>, + pub unknown_tx_position_list: Seq064K, } -impl fmt::Display for ProvideMissingTransactions<'_> { +impl fmt::Display for ProvideMissingTransactions { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!( f, @@ -42,15 +42,15 @@ impl fmt::Display for ProvideMissingTransactions<'_> { /// list of transactions in the order they were requested by [`ProvideMissingTransactions`]. #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)] #[repr(C)] -pub struct ProvideMissingTransactionsSuccess<'decoder> { +pub struct ProvideMissingTransactionsSuccess { /// Unique Identifier. /// /// Must be the same as the received [`ProvideMissingTransactions::request_id`]. pub request_id: u32, /// List of full transactions as requested by [`ProvideMissingTransactions`]. - pub transaction_list: Seq064K<'decoder, B016M<'decoder>>, + pub transaction_list: Seq064K, } -impl fmt::Display for ProvideMissingTransactionsSuccess<'_> { +impl fmt::Display for ProvideMissingTransactionsSuccess { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!( f, diff --git a/sv2/subprotocols/job-declaration/src/push_solution.rs b/sv2/subprotocols/job-declaration/src/push_solution.rs index 25db4d7351..83be7c6dfd 100644 --- a/sv2/subprotocols/job-declaration/src/push_solution.rs +++ b/sv2/subprotocols/job-declaration/src/push_solution.rs @@ -14,11 +14,11 @@ use core::{convert::TryInto, fmt}; /// [`Full Template`]: https://github.com/stratum-mining/sv2-spec/blob/main/06-Job-Declaration-Protocol.md#632-full-template-mode #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)] #[repr(C)] -pub struct PushSolution<'decoder> { +pub struct PushSolution { /// Full extranonce that forms a valid submission. - pub extranonce: B032<'decoder>, + pub extranonce: B032, /// Previous block hash. - pub prev_hash: U256<'decoder>, + pub prev_hash: U256, /// Contains the time the block was constructed as a Unix timestamp. pub ntime: u32, /// Nonce of the block. @@ -36,7 +36,7 @@ pub struct PushSolution<'decoder> { pub version: u32, } -impl fmt::Display for PushSolution<'_> { +impl fmt::Display for PushSolution { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!( f, diff --git a/sv2/subprotocols/mining/src/close_channel.rs b/sv2/subprotocols/mining/src/close_channel.rs index d9c628d817..ad37cf47d0 100644 --- a/sv2/subprotocols/mining/src/close_channel.rs +++ b/sv2/subprotocols/mining/src/close_channel.rs @@ -9,14 +9,14 @@ use core::convert::TryInto; /// /// Upon receiving this message, upstream **must** stop sending messages for the channel. #[derive(Serialize, Deserialize, Debug, Clone)] -pub struct CloseChannel<'decoder> { +pub struct CloseChannel { /// Channel id of the channel to be closed. pub channel_id: u32, /// Reason for closing the channel. - pub reason_code: Str0255<'decoder>, + pub reason_code: Str0255, } -impl fmt::Display for CloseChannel<'_> { +impl fmt::Display for CloseChannel { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!( f, diff --git a/sv2/subprotocols/mining/src/lib.rs b/sv2/subprotocols/mining/src/lib.rs index d8433bde32..1ba94e613d 100644 --- a/sv2/subprotocols/mining/src/lib.rs +++ b/sv2/subprotocols/mining/src/lib.rs @@ -127,15 +127,15 @@ pub struct Extranonce { } // this function converts a U256 type in little endian to Extranonce type -impl<'a> From> for Extranonce { - fn from(v: U256<'a>) -> Self { +impl From for Extranonce { + fn from(v: U256) -> Self { let extranonce: alloc::vec::Vec = v.inner_as_ref().into(); Self { extranonce } } } // This function converts an Extranonce type to U256n little endian -impl From for U256<'_> { +impl From for U256 { fn from(v: Extranonce) -> Self { let inner = v.extranonce; debug_assert!(inner.len() <= 32); @@ -145,15 +145,15 @@ impl From for U256<'_> { } // this function converts an extranonce to the type B032 -impl<'a> From> for Extranonce { - fn from(v: B032<'a>) -> Self { +impl From for Extranonce { + fn from(v: B032) -> Self { let extranonce: alloc::vec::Vec = v.inner_as_ref().into(); Self { extranonce } } } // this function converts an Extranonce type in B032 in little endian -impl From for B032<'_> { +impl From for B032 { fn from(v: Extranonce) -> Self { let inner = v.extranonce.to_vec(); // below unwraps never panics @@ -197,13 +197,13 @@ impl Extranonce { Self { extranonce } } - pub fn into_b032(self) -> B032<'static> { + pub fn into_b032(self) -> B032 { self.into() } // B032 type is more used, this is why the output signature is not ExtendedExtranoncee the B032 // type is more used, this is why the output signature is not ExtendedExtranoncee #[allow(clippy::should_implement_trait)] - pub fn next(&mut self) -> Option> { + pub fn next(&mut self) -> Option { increment_bytes_be(&mut self.extranonce).ok()?; // below unwraps never panics Some(self.extranonce.clone().try_into().unwrap()) @@ -843,7 +843,7 @@ pub mod tests { input.resize(MAX_EXTRANONCE_LEN, 0); let extranonce_start = Extranonce::try_from(input.clone()).unwrap(); - let u256 = U256::<'static>::from(extranonce_start.clone()); + let u256 = U256::from(extranonce_start.clone()); let extranonce_final = Extranonce::from(u256); extranonce_start == extranonce_final } @@ -853,7 +853,7 @@ pub mod tests { fn test_extranonce_from_b032(mut input: Vec) -> bool { input.resize(MAX_EXTRANONCE_LEN, 0); let extranonce_start = Extranonce::try_from(input.clone()).unwrap(); - let b032 = B032::<'static>::from(extranonce_start.clone()); + let b032 = B032::from(extranonce_start.clone()); let extranonce_final = Extranonce::from(b032); extranonce_start == extranonce_final } diff --git a/sv2/subprotocols/mining/src/new_mining_job.rs b/sv2/subprotocols/mining/src/new_mining_job.rs index 9167be974e..3c8f3719e4 100644 --- a/sv2/subprotocols/mining/src/new_mining_job.rs +++ b/sv2/subprotocols/mining/src/new_mining_job.rs @@ -10,7 +10,7 @@ use core::{convert::TryInto, fmt}; /// and the only rollable bits are `version`, `nonce`, and `nTime` fields of the block header. #[allow(clippy::derive_partial_eq_without_eq)] #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)] -pub struct NewMiningJob<'decoder> { +pub struct NewMiningJob { /// Channel identifier for the channel that this job is valid for. /// /// This must be a Standard Channel. @@ -30,7 +30,7 @@ pub struct NewMiningJob<'decoder> { /// received [`SetNewPrevHash`] message. /// /// [`SetNewPrevHash`]: crate::SetNewPrevHash - pub min_ntime: Sv2Option<'decoder, u32>, + pub min_ntime: Sv2Option, /// Version field that reflects the current network consensus. /// /// As specified in [BIP320](https://github.com/bitcoin/bips/blob/master/bip-0320.mediawiki), @@ -43,10 +43,10 @@ pub struct NewMiningJob<'decoder> { /// Merkle root field as used in the bitcoin block header. /// /// Note that this field is fixed and cannot be modified by the downstream node. - pub merkle_root: U256<'decoder>, + pub merkle_root: U256, } -impl fmt::Display for NewMiningJob<'_> { +impl fmt::Display for NewMiningJob { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!( f, @@ -56,7 +56,7 @@ impl fmt::Display for NewMiningJob<'_> { } } -impl NewMiningJob<'_> { +impl NewMiningJob { pub fn is_future(&self) -> bool { self.min_ntime.clone().into_inner().is_none() } @@ -75,7 +75,7 @@ impl NewMiningJob<'_> { /// that they can implement various advanced use cases such as: translation between Stratum V1 and /// V2 protocols, difficulty aggregation and search space splitting. #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)] -pub struct NewExtendedMiningJob<'decoder> { +pub struct NewExtendedMiningJob { /// Identifier of the Extended Mining Channel that this job is valid for. /// /// For a Group Channel, the message is broadcasted to all standard channels belonging to the @@ -97,7 +97,7 @@ pub struct NewExtendedMiningJob<'decoder> { /// received [`SetNewPrevHash`] message. /// /// [`SetNewPrevHash`]: crate::SetNewPrevHash - pub min_ntime: Sv2Option<'decoder, u32>, + pub min_ntime: Sv2Option, /// Version field that reflects the current network consensus. /// /// As specified in [BIP320](https://github.com/bitcoin/bips/blob/master/bip-0320.mediawiki), @@ -114,14 +114,14 @@ pub struct NewExtendedMiningJob<'decoder> { /// defined by this message. pub version_rolling_allowed: bool, /// Merkle path hashes ordered from deepest. - pub merkle_path: Seq0255<'decoder, U256<'decoder>>, + pub merkle_path: Seq0255, /// Prefix part of the coinbase transaction. - pub coinbase_tx_prefix: B064K<'decoder>, + pub coinbase_tx_prefix: B064K, /// Suffix part of the coinbase transaction. - pub coinbase_tx_suffix: B064K<'decoder>, + pub coinbase_tx_suffix: B064K, } -impl fmt::Display for NewExtendedMiningJob<'_> { +impl fmt::Display for NewExtendedMiningJob { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!( f, @@ -138,7 +138,7 @@ impl fmt::Display for NewExtendedMiningJob<'_> { } } -impl NewExtendedMiningJob<'_> { +impl NewExtendedMiningJob { pub fn is_future(&self) -> bool { self.min_ntime.clone().into_inner().is_none() } diff --git a/sv2/subprotocols/mining/src/open_channel.rs b/sv2/subprotocols/mining/src/open_channel.rs index 6b0046d139..4ad7e5758a 100644 --- a/sv2/subprotocols/mining/src/open_channel.rs +++ b/sv2/subprotocols/mining/src/open_channel.rs @@ -7,13 +7,13 @@ use core::{convert::TryInto, fmt}; /// connection within a reasonable period, otherwise the upstream should close the connection for /// inactivity. #[derive(Serialize, Deserialize, Debug, Clone)] -pub struct OpenStandardMiningChannel<'decoder> { +pub struct OpenStandardMiningChannel { /// Specified by downstream role. /// /// Used for matching responses from upstream. /// /// The value must be connection-wide unique and is not interpreted by the upstream. - pub request_id: U32AsRef<'decoder>, + pub request_id: U32AsRef, /// Unconstrained sequence of bytes. /// /// Whatever is needed by upstream role to identify/authenticate the downstream, e.g. @@ -21,7 +21,7 @@ pub struct OpenStandardMiningChannel<'decoder> { /// /// Additional restrictions can be imposed by the upstream role (e.g. a pool). It is highly /// recommended to use UTF-8 encoding. - pub user_identity: Str0255<'decoder>, + pub user_identity: Str0255, /// Expected hash rate of the device (or cumulative hashrate on the channel if multiple devices /// are connected downstream) in h/s. /// @@ -33,10 +33,10 @@ pub struct OpenStandardMiningChannel<'decoder> { /// Maximum target which can be accepted by the connected device(s). /// /// Upstream must accept the target or respond by sending [`OpenMiningChannelError`] message. - pub max_target: U256<'decoder>, + pub max_target: U256, } -impl fmt::Display for OpenStandardMiningChannel<'_> { +impl fmt::Display for OpenStandardMiningChannel { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!( f, @@ -49,7 +49,7 @@ impl fmt::Display for OpenStandardMiningChannel<'_> { } } -impl OpenStandardMiningChannel<'_> { +impl OpenStandardMiningChannel { pub fn get_request_id_as_u32(&self) -> u32 { (&self.request_id).into() } @@ -67,26 +67,26 @@ impl OpenStandardMiningChannel<'_> { /// Message used by upstream to accept [`OpenStandardMiningChannel`] request from downstream. #[allow(clippy::derive_partial_eq_without_eq)] #[derive(Serialize, Deserialize, Debug, Clone, PartialEq)] -pub struct OpenStandardMiningChannelSuccess<'decoder> { +pub struct OpenStandardMiningChannelSuccess { /// Used for matching requests/responses. /// /// Specified by downstream role and should be extracted from the corresponding /// [`OpenStandardMiningChannel`] message. - pub request_id: U32AsRef<'decoder>, + pub request_id: U32AsRef, /// Newly assigned identifier of the channel, stable for the whole lifetime of the connection. /// /// This will also be used for broadcasting new jobs by [`crate::NewMiningJob`]. pub channel_id: u32, /// Initial target for the mining channel. - pub target: U256<'decoder>, + pub target: U256, /// Bytes used as implicit first part of extranonce for the scenario when the job is served by /// the downstream role for a set of standard channels that belong to the same group. - pub extranonce_prefix: B032<'decoder>, + pub extranonce_prefix: B032, /// Group channel into which the new channel belongs. See SetGroupChannel for details. pub group_channel_id: u32, } -impl fmt::Display for OpenStandardMiningChannelSuccess<'_> { +impl fmt::Display for OpenStandardMiningChannelSuccess { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!( f, @@ -100,7 +100,7 @@ impl fmt::Display for OpenStandardMiningChannelSuccess<'_> { } } -impl OpenStandardMiningChannelSuccess<'_> { +impl OpenStandardMiningChannelSuccess { pub fn get_request_id_as_u32(&self) -> u32 { (&self.request_id).into() } @@ -124,7 +124,7 @@ impl OpenStandardMiningChannelSuccess<'_> { /// by the upstream role based on the [`OpenExtendedMiningChannel::min_extranonce_size`] requested /// by the downstream. #[derive(Serialize, Deserialize, Debug, Clone, PartialEq)] -pub struct OpenExtendedMiningChannel<'decoder> { +pub struct OpenExtendedMiningChannel { /// Specified by downstream role. /// /// Used for matching responses from upstream. @@ -138,7 +138,7 @@ pub struct OpenExtendedMiningChannel<'decoder> { /// /// Additional restrictions can be imposed by the upstream role (e.g. a pool). It is highly /// recommended to use UTF-8 encoding. - pub user_identity: Str0255<'decoder>, + pub user_identity: Str0255, /// Expected hash rate of the device (or cumulative hashrate on the channel if multiple devices /// are connected downstream) in h/s. /// @@ -150,12 +150,12 @@ pub struct OpenExtendedMiningChannel<'decoder> { /// Maximum target which can be accepted by the connected device or devices. /// /// Upstream must accept the target or respond by sending [`OpenMiningChannelError`] message. - pub max_target: U256<'decoder>, + pub max_target: U256, /// Minimum size of extranonce needed by the downstream device/role. pub min_extranonce_size: u16, } -impl fmt::Display for OpenExtendedMiningChannel<'_> { +impl fmt::Display for OpenExtendedMiningChannel { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!( f, @@ -169,7 +169,7 @@ impl fmt::Display for OpenExtendedMiningChannel<'_> { } } -impl OpenExtendedMiningChannel<'_> { +impl OpenExtendedMiningChannel { pub fn get_request_id_as_u32(&self) -> u32 { self.request_id } @@ -177,7 +177,7 @@ impl OpenExtendedMiningChannel<'_> { /// Message used by upstream to accept [`OpenExtendedMiningChannel` request from downstream. #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)] -pub struct OpenExtendedMiningChannelSuccess<'decoder> { +pub struct OpenExtendedMiningChannelSuccess { /// Used for matching requests/responses. /// /// Specified by downstream role and should be extracted from the corresponding @@ -188,16 +188,16 @@ pub struct OpenExtendedMiningChannelSuccess<'decoder> { /// This will also be used for broadcasting new jobs by [`crate::NewExtendedMiningJob`]. pub channel_id: u32, /// Initial target for the mining channel. - pub target: U256<'decoder>, + pub target: U256, /// Extranonce size (in bytes) set for the channel. pub extranonce_size: u16, /// Bytes used as implicit first part of extranonce - pub extranonce_prefix: B032<'decoder>, + pub extranonce_prefix: B032, /// Group channel into which the new channel belongs. See SetGroupChannel for details. pub group_channel_id: u32, } -impl fmt::Display for OpenExtendedMiningChannelSuccess<'_> { +impl fmt::Display for OpenExtendedMiningChannelSuccess { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!( f, @@ -215,7 +215,7 @@ impl fmt::Display for OpenExtendedMiningChannelSuccess<'_> { /// Message used by upstream to reject [`OpenExtendedMiningChannel`] or /// [`OpenStandardMiningchannel`] request from downstream. #[derive(Serialize, Deserialize, Debug, Clone)] -pub struct OpenMiningChannelError<'decoder> { +pub struct OpenMiningChannelError { /// Used for matching requests/responses. /// /// Specified by downstream role and should be extracted from the corresponding @@ -227,10 +227,10 @@ pub struct OpenMiningChannelError<'decoder> { /// /// - ‘unknown-user’ /// - ‘max-target-out-of-range’ - pub error_code: Str0255<'decoder>, + pub error_code: Str0255, } -impl fmt::Display for OpenMiningChannelError<'_> { +impl fmt::Display for OpenMiningChannelError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!( f, @@ -241,7 +241,7 @@ impl fmt::Display for OpenMiningChannelError<'_> { } } -impl OpenMiningChannelError<'_> { +impl OpenMiningChannelError { pub fn new_max_target_out_of_range(request_id: u32) -> Self { Self { request_id, diff --git a/sv2/subprotocols/mining/src/set_custom_mining_job.rs b/sv2/subprotocols/mining/src/set_custom_mining_job.rs index c0cc8ed667..33ff65ee27 100644 --- a/sv2/subprotocols/mining/src/set_custom_mining_job.rs +++ b/sv2/subprotocols/mining/src/set_custom_mining_job.rs @@ -13,7 +13,7 @@ use core::convert::TryInto; /// Previously exchanged `SetupConnection::flags` must contain `REQUIRES_WORK_SELECTION` flag i.e., /// work selection feature was successfully negotiated. #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)] -pub struct SetCustomMiningJob<'decoder> { +pub struct SetCustomMiningJob { /// Extended mining channel identifier. pub channel_id: u32, /// Specified by downstream role. @@ -24,7 +24,7 @@ pub struct SetCustomMiningJob<'decoder> { pub request_id: u32, /// Provide the information for the upstream to authorize the custom job that has been or will /// be negotiated between the Job Declarator Client and Job Declarator Server. - pub token: B0255<'decoder>, + pub token: B0255, /// Version field that reflects the current network consensus. /// /// The general purpose bits (as specified in BIP320) can be freely manipulated by the @@ -32,7 +32,7 @@ pub struct SetCustomMiningJob<'decoder> { /// bits to any particular value. pub version: u32, /// Previous block’s hash. - pub prev_hash: U256<'decoder>, + pub prev_hash: U256, /// Smallest `nTime` value available for hashing. pub min_ntime: u32, /// Block header field. @@ -41,18 +41,18 @@ pub struct SetCustomMiningJob<'decoder> { pub coinbase_tx_version: u32, /// Up to 8 bytes (not including the length byte) which are to be placed at the beginning of /// the coinbase field in the coinbase transaction. - pub coinbase_prefix: B0255<'decoder>, + pub coinbase_prefix: B0255, /// The coinbase transaction input’s nSequence field. pub coinbase_tx_input_n_sequence: u32, /// All the outputs that will be included in the coinbase txs - pub coinbase_tx_outputs: B064K<'decoder>, + pub coinbase_tx_outputs: B064K, /// The `locktime` field in the coinbase transaction. pub coinbase_tx_locktime: u32, /// Merkle path hashes ordered from deepest. - pub merkle_path: Seq0255<'decoder, U256<'decoder>>, + pub merkle_path: Seq0255, } -impl fmt::Display for SetCustomMiningJob<'_> { +impl fmt::Display for SetCustomMiningJob { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "SetCustomMiningJob(channel_id={}, request_id={}, token={}, version=0x{:08x}, prev_hash={}, min_ntime={}, nbits=0x{:08x}, coinbase_tx_version=0x{:08x}, coinbase_prefix={}, coinbase_tx_input_n_sequence=0x{:08x}, coinbase_tx_outputs={}, coinbase_tx_locktime={}, merkle_path={})", self.channel_id, @@ -98,7 +98,7 @@ impl fmt::Display for SetCustomMiningJobSuccess { /// Message used by upstream to reject [`SetCustomMiningJob`] request. #[derive(Serialize, Deserialize, Debug, Clone)] -pub struct SetCustomMiningJobError<'decoder> { +pub struct SetCustomMiningJobError { /// Extended mining channel identifier. pub channel_id: u32, /// Request identifier set by the downstream role. @@ -109,10 +109,10 @@ pub struct SetCustomMiningJobError<'decoder> { /// - invalid-channel-id /// - invalid-mining-job-token /// - invalid-job-param-value-{field_name} - pub error_code: Str0255<'decoder>, + pub error_code: Str0255, } -impl fmt::Display for SetCustomMiningJobError<'_> { +impl fmt::Display for SetCustomMiningJobError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!( f, diff --git a/sv2/subprotocols/mining/src/set_extranonce_prefix.rs b/sv2/subprotocols/mining/src/set_extranonce_prefix.rs index 0f69243148..efda24b308 100644 --- a/sv2/subprotocols/mining/src/set_extranonce_prefix.rs +++ b/sv2/subprotocols/mining/src/set_extranonce_prefix.rs @@ -12,14 +12,14 @@ use core::convert::TryInto; /// Note that this message is applicable only for opened Standard or Extended Channels, not Group /// Channels. #[derive(Serialize, Deserialize, Debug, Clone)] -pub struct SetExtranoncePrefix<'decoder> { +pub struct SetExtranoncePrefix { /// Extended or Standard Channel identifier. pub channel_id: u32, /// New extranonce prefix. - pub extranonce_prefix: B032<'decoder>, + pub extranonce_prefix: B032, } -impl fmt::Display for SetExtranoncePrefix<'_> { +impl fmt::Display for SetExtranoncePrefix { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!( f, diff --git a/sv2/subprotocols/mining/src/set_group_channel.rs b/sv2/subprotocols/mining/src/set_group_channel.rs index 65b5dda14f..733fde3855 100644 --- a/sv2/subprotocols/mining/src/set_group_channel.rs +++ b/sv2/subprotocols/mining/src/set_group_channel.rs @@ -18,14 +18,14 @@ use core::convert::TryInto; /// This message can be sent only to connections that didnt set `REQUIRES_STANDARD_JOBS` flag in /// `SetupConnection` message. #[derive(Serialize, Deserialize, Debug, Clone)] -pub struct SetGroupChannel<'decoder> { +pub struct SetGroupChannel { /// Identifier of the group where the standard channel belongs. pub group_channel_id: u32, /// A sequence of opened standard channel IDs, for which the group channel is being redefined. - pub channel_ids: Seq064K<'decoder, u32>, + pub channel_ids: Seq064K, } -impl fmt::Display for SetGroupChannel<'_> { +impl fmt::Display for SetGroupChannel { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!( f, diff --git a/sv2/subprotocols/mining/src/set_new_prev_hash.rs b/sv2/subprotocols/mining/src/set_new_prev_hash.rs index ca2f2e1561..5521766c16 100644 --- a/sv2/subprotocols/mining/src/set_new_prev_hash.rs +++ b/sv2/subprotocols/mining/src/set_new_prev_hash.rs @@ -11,7 +11,7 @@ use core::{convert::TryInto, fmt}; /// When a downstream receives this message, only the job referenced by [`SetNewPrevHash::job_id`] /// is valid. Remaining jobs have to be dropped. #[derive(Serialize, Deserialize, Debug, Clone)] -pub struct SetNewPrevHash<'decoder> { +pub struct SetNewPrevHash { /// Group channel or channel that this prevhash is valid for. pub channel_id: u32, /// Job identfier that is to be used for mining. @@ -21,14 +21,14 @@ pub struct SetNewPrevHash<'decoder> { /// current block template). pub job_id: u32, /// Latest block hash observed by the Template Provider. - pub prev_hash: U256<'decoder>, + pub prev_hash: U256, /// Smallest `nTime` value available for hashing. pub min_ntime: u32, /// Block header field. pub nbits: u32, } -impl fmt::Display for SetNewPrevHash<'_> { +impl fmt::Display for SetNewPrevHash { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!( f, diff --git a/sv2/subprotocols/mining/src/set_target.rs b/sv2/subprotocols/mining/src/set_target.rs index b28f185a82..a88a4f0d0d 100644 --- a/sv2/subprotocols/mining/src/set_target.rs +++ b/sv2/subprotocols/mining/src/set_target.rs @@ -15,14 +15,14 @@ use core::convert::TryInto; /// When this message is sent to a group channel, the maximum target is applicable to all channels /// in the group. #[derive(Serialize, Deserialize, Debug, Clone)] -pub struct SetTarget<'decoder> { +pub struct SetTarget { /// Channel identifier. pub channel_id: u32, /// Maximum value of produced hash that will be accepted by a upstream to accept shares. - pub maximum_target: U256<'decoder>, + pub maximum_target: U256, } -impl fmt::Display for SetTarget<'_> { +impl fmt::Display for SetTarget { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!( f, diff --git a/sv2/subprotocols/mining/src/submit_shares.rs b/sv2/subprotocols/mining/src/submit_shares.rs index e11eb02a17..e4f03391ab 100644 --- a/sv2/subprotocols/mining/src/submit_shares.rs +++ b/sv2/subprotocols/mining/src/submit_shares.rs @@ -43,7 +43,7 @@ impl fmt::Display for SubmitSharesStandard { /// /// Only relevant for Extended Channels. #[derive(Serialize, Deserialize, Debug, Clone)] -pub struct SubmitSharesExtended<'decoder> { +pub struct SubmitSharesExtended { /// Channel identification. pub channel_id: u32, /// Unique sequential identifier of the submit within the channel. @@ -69,10 +69,10 @@ pub struct SubmitSharesExtended<'decoder> { /// /// The size of the provided extranonce must be equal to the negotiated extranonce size from /// channel opening flow. - pub extranonce: B032<'decoder>, + pub extranonce: B032, } -impl fmt::Display for SubmitSharesExtended<'_> { +impl fmt::Display for SubmitSharesExtended { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!( f, @@ -118,7 +118,7 @@ impl fmt::Display for SubmitSharesSuccess { /// soon as the result is known. This delayed validation can occur when a miner gets faster /// updates about a new `prevhash` than the upstream does. #[derive(Serialize, Deserialize, Debug, Clone)] -pub struct SubmitSharesError<'decoder> { +pub struct SubmitSharesError { /// Channel identification. pub channel_id: u32, /// Unique sequential identifier of the submit within the channel. @@ -131,10 +131,10 @@ pub struct SubmitSharesError<'decoder> { /// - stale-share /// - difficulty-too-low /// - invalid-job-id - pub error_code: Str0255<'decoder>, + pub error_code: Str0255, } -impl fmt::Display for SubmitSharesError<'_> { +impl fmt::Display for SubmitSharesError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!( f, @@ -146,7 +146,7 @@ impl fmt::Display for SubmitSharesError<'_> { } } -impl SubmitSharesError<'_> { +impl SubmitSharesError { pub fn invalid_channel_error_code() -> &'static str { "invalid-channel-id" } diff --git a/sv2/subprotocols/mining/src/update_channel.rs b/sv2/subprotocols/mining/src/update_channel.rs index 294a5c39f1..af458c57ec 100644 --- a/sv2/subprotocols/mining/src/update_channel.rs +++ b/sv2/subprotocols/mining/src/update_channel.rs @@ -9,7 +9,7 @@ use core::convert::TryInto; /// /// Only relevant for Extended Channels. #[derive(Serialize, Deserialize, Debug, Clone)] -pub struct UpdateChannel<'decoder> { +pub struct UpdateChannel { /// Channel identification. pub channel_id: u32, /// Expected hash rate of the device (or cumulative hashrate on the channel if multiple devices @@ -31,10 +31,10 @@ pub struct UpdateChannel<'decoder> { /// Upstream can change maximum target by sending [`SetTarget`] message. /// /// [`SetTarget`]: crate::SetTarget - pub maximum_target: U256<'decoder>, + pub maximum_target: U256, } -impl fmt::Display for UpdateChannel<'_> { +impl fmt::Display for UpdateChannel { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!( f, @@ -46,7 +46,7 @@ impl fmt::Display for UpdateChannel<'_> { /// Message used by upstream to notify downstream about an error in the [`UpdateChannel`] message. #[derive(Serialize, Deserialize, Debug, Clone)] -pub struct UpdateChannelError<'decoder> { +pub struct UpdateChannelError { /// Channel identification. pub channel_id: u32, /// Reason for channel update error. @@ -54,10 +54,10 @@ pub struct UpdateChannelError<'decoder> { /// Possible error codes: /// - max-target-out-of-range /// - invalid-channel-id - pub error_code: Str0255<'decoder>, + pub error_code: Str0255, } -impl fmt::Display for UpdateChannelError<'_> { +impl fmt::Display for UpdateChannelError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!( f, diff --git a/sv2/subprotocols/template-distribution/src/new_template.rs b/sv2/subprotocols/template-distribution/src/new_template.rs index 2206d885a1..202c8bf1f9 100644 --- a/sv2/subprotocols/template-distribution/src/new_template.rs +++ b/sv2/subprotocols/template-distribution/src/new_template.rs @@ -5,7 +5,7 @@ use core::convert::TryInto; /// Message used by an upstream(Template Provider) to provide a new template for downstream to mine /// on. #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)] -pub struct NewTemplate<'decoder> { +pub struct NewTemplate { /// Upstream’s identification of the template. /// /// Should be strictly increasing. @@ -30,7 +30,7 @@ pub struct NewTemplate<'decoder> { pub coinbase_tx_version: u32, /// Up to 8 bytes (not including the length byte) which are to be placed at the beginning of /// the coinbase field in the coinbase transaction. - pub coinbase_prefix: B0255<'decoder>, + pub coinbase_prefix: B0255, /// The coinbase transaction input’s `nSequence` field. pub coinbase_tx_input_sequence: u32, /// The value, in satoshis, available for spending in coinbase outputs added by the downstream. @@ -42,14 +42,14 @@ pub struct NewTemplate<'decoder> { /// Bitcoin transaction outputs to be included as the last outputs in the coinbase transaction. /// /// Note that those bytes will appear as is at the end of the coinbase transaction. - pub coinbase_tx_outputs: B064K<'decoder>, + pub coinbase_tx_outputs: B064K, /// The `locktime` field in the coinbase transaction. pub coinbase_tx_locktime: u32, /// Merkle path hashes ordered from deepest. - pub merkle_path: Seq0255<'decoder, U256<'decoder>>, + pub merkle_path: Seq0255, } -impl fmt::Display for NewTemplate<'_> { +impl fmt::Display for NewTemplate { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!( f, @@ -79,8 +79,8 @@ use quickcheck::{Arbitrary, Gen}; use alloc::vec; #[cfg(feature = "prop_test")] -impl Arbitrary for NewTemplate<'static> { - fn arbitrary(g: &mut Gen) -> NewTemplate<'static> { +impl Arbitrary for NewTemplate { + fn arbitrary(g: &mut Gen) -> NewTemplate { let coinbase_tx_version = (u32::arbitrary(g) % 2) + 1; let mut coinbase_prefix = vec::Vec::new(); let coinbase_prefix_len = match coinbase_tx_version { diff --git a/sv2/subprotocols/template-distribution/src/request_transaction_data.rs b/sv2/subprotocols/template-distribution/src/request_transaction_data.rs index e5f394743c..d3f58ff5f5 100644 --- a/sv2/subprotocols/template-distribution/src/request_transaction_data.rs +++ b/sv2/subprotocols/template-distribution/src/request_transaction_data.rs @@ -60,16 +60,16 @@ impl fmt::Display for RequestTransactionData { /// code-release to activation and there being in protocol(Template Declaration) signaling of /// support for the new fork (e.g. for soft-forks activated using [BIP 9]). #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)] -pub struct RequestTransactionDataSuccess<'decoder> { +pub struct RequestTransactionDataSuccess { /// The template_id corresponding to a NewTemplate/RequestTransactionData message. pub template_id: u64, /// Extra data which the Pool may require to validate the work. - pub excess_data: B064K<'decoder>, + pub excess_data: B064K, /// The transaction data, serialized as a series of B0_16M byte arrays. - pub transaction_list: Seq064K<'decoder, B016M<'decoder>>, + pub transaction_list: Seq064K, } -impl fmt::Display for RequestTransactionDataSuccess<'_> { +impl fmt::Display for RequestTransactionDataSuccess { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!( f, @@ -82,17 +82,17 @@ impl fmt::Display for RequestTransactionDataSuccess<'_> { /// Message used by an upstream(Template Provider) to respond with an error to a /// [`RequestTransactionData`] message. #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)] -pub struct RequestTransactionDataError<'decoder> { +pub struct RequestTransactionDataError { /// Identifier of the template that the downstream node is requesting transaction data for. pub template_id: u64, /// Reason why no transaction data has been provided. /// /// Possible error codes: /// - template-id-not-found - pub error_code: Str0255<'decoder>, + pub error_code: Str0255, } -impl fmt::Display for RequestTransactionDataError<'_> { +impl fmt::Display for RequestTransactionDataError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!( f, diff --git a/sv2/subprotocols/template-distribution/src/set_new_prev_hash.rs b/sv2/subprotocols/template-distribution/src/set_new_prev_hash.rs index f8305b2529..256f828150 100644 --- a/sv2/subprotocols/template-distribution/src/set_new_prev_hash.rs +++ b/sv2/subprotocols/template-distribution/src/set_new_prev_hash.rs @@ -11,13 +11,13 @@ use core::{convert::TryInto, fmt}; /// [`crate::NewTemplate::future_template`] flag set, the [`SetNewPrevHash::template_id`] field /// **should** be set to the [`crate::NewTemplate::template_id`]. #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)] -pub struct SetNewPrevHash<'decoder> { +pub struct SetNewPrevHash { /// Identifier of the template to mine on. /// /// This must be identical to previously sent [`crate::NewTemplate`] message. pub template_id: u64, /// Previous block’s hash, as it must appear in the next block’s header. - pub prev_hash: U256<'decoder>, + pub prev_hash: U256, /// `nTime` field in the block header at which the client should start (usually current time). /// /// This is **not** the minimum valid `nTime` value. @@ -27,10 +27,10 @@ pub struct SetNewPrevHash<'decoder> { /// The maximum double-SHA256 hash value which would represent a valid block. Note that this /// may be lower than the target implied by nBits in several cases, including weak-block based /// block propagation. - pub target: U256<'decoder>, + pub target: U256, } -impl fmt::Display for SetNewPrevHash<'_> { +impl fmt::Display for SetNewPrevHash { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!( f, diff --git a/sv2/subprotocols/template-distribution/src/submit_solution.rs b/sv2/subprotocols/template-distribution/src/submit_solution.rs index 95e640286c..b4dc96fa62 100644 --- a/sv2/subprotocols/template-distribution/src/submit_solution.rs +++ b/sv2/subprotocols/template-distribution/src/submit_solution.rs @@ -11,7 +11,7 @@ use core::convert::TryInto; /// Upon receiving this message, upstream(Template Provider) **must** immediately construct the /// corresponding full block and attempt to propagate it to the Bitcoin network. #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)] -pub struct SubmitSolution<'decoder> { +pub struct SubmitSolution { /// Identifies the template to which this solution corresponds. /// /// This is acquired from the [`crate::NewTemplate`] message. @@ -33,10 +33,10 @@ pub struct SubmitSolution<'decoder> { pub header_nonce: u32, /// Full serialized coinbase transaction, meeting all the requirements of the `NewMiningJob` or /// `NewExtendedMiningJob` message. - pub coinbase_tx: B064K<'decoder>, + pub coinbase_tx: B064K, } -impl fmt::Display for SubmitSolution<'_> { +impl fmt::Display for SubmitSolution { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!( f,