-
Notifications
You must be signed in to change notification settings - Fork 147
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Add SnifferSV1
to ITF
#1580
Open
jbesraa
wants to merge
5
commits into
stratum-mining:main
Choose a base branch
from
jbesraa:2025-03-13/sv1-sniffer
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Add SnifferSV1
to ITF
#1580
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
171 changes: 171 additions & 0 deletions
171
roles/roles-utils/network-helpers/src/sv1_connection.rs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,171 @@ | ||
use async_channel::{unbounded, Receiver, Sender}; | ||
use futures::{FutureExt, StreamExt}; | ||
use sv1_api::json_rpc; | ||
use tokio::{ | ||
io::{AsyncWriteExt, BufReader}, | ||
net::TcpStream, | ||
}; | ||
use tokio_util::codec::{FramedRead, LinesCodec}; | ||
|
||
/// Represents a connection between two roles communicating using SV1 protocol. | ||
/// | ||
/// This struct can be used read and write messages to the other side of the connection. The | ||
/// channel is unidirectional, so you will need two instances of this struct to communicate in both | ||
/// directions. | ||
#[derive(Debug)] | ||
pub struct ConnectionSV1 { | ||
receiver: Receiver<json_rpc::Message>, | ||
sender: Sender<json_rpc::Message>, | ||
} | ||
|
||
const MAX_LINE_LENGTH: usize = 2_usize.pow(16); | ||
|
||
impl ConnectionSV1 { | ||
/// Create a new connection set up to communicate with the other side of the given stream. | ||
/// | ||
/// Two tasks are spawned to handle reading and writing messages. The reading task will read | ||
/// messages from the stream and send them to the receiver channel. The writing task will read | ||
/// messages from the sender channel and write them to the stream. | ||
pub async fn new(stream: TcpStream) -> Self { | ||
let (reader_stream, mut writer_stream) = stream.into_split(); | ||
let (sender_incoming, receiver_incoming) = unbounded(); | ||
let (sender_outgoing, receiver_outgoing) = unbounded::<json_rpc::Message>(); | ||
|
||
// Read Job | ||
let sender_incoming_clone = sender_incoming.clone(); | ||
tokio::task::spawn(async move { | ||
let reader = BufReader::new(reader_stream); | ||
let mut messages = | ||
FramedRead::new(reader, LinesCodec::new_with_max_length(MAX_LINE_LENGTH)); | ||
loop { | ||
tokio::select! { | ||
res = messages.next().fuse() => { | ||
match res { | ||
Some(Ok(incoming)) => { | ||
let incoming: json_rpc::Message = serde_json::from_str(&incoming).unwrap(); | ||
if sender_incoming_clone | ||
.send(incoming) | ||
.await | ||
.is_err() | ||
{ | ||
break; | ||
} | ||
|
||
} | ||
Some(Err(e)) => { | ||
break tracing::error!("Error reading from stream: {:?}", e); | ||
} | ||
None => { | ||
dbg!("None"); | ||
} | ||
} | ||
}, | ||
_ = tokio::signal::ctrl_c().fuse() => { | ||
break; | ||
} | ||
}; | ||
} | ||
}); | ||
|
||
// Write Job | ||
tokio::task::spawn(async move { | ||
loop { | ||
tokio::select! { | ||
res = receiver_outgoing.recv().fuse() => { | ||
let to_send = res.unwrap(); | ||
let to_send = match serde_json::to_string(&to_send) { | ||
Ok(string) => format!("{}\n", string), | ||
Err(_e) => { | ||
break; | ||
} | ||
}; | ||
let _ = writer_stream | ||
.write_all(to_send.as_bytes()) | ||
.await; | ||
}, | ||
_ = tokio::signal::ctrl_c().fuse() => { | ||
break; | ||
} | ||
}; | ||
} | ||
}); | ||
Self { | ||
receiver: receiver_incoming, | ||
sender: sender_outgoing, | ||
} | ||
} | ||
|
||
/// Send a message to the other side of the connection. | ||
pub async fn send(&self, msg: json_rpc::Message) -> bool { | ||
self.sender.send(msg).await.is_ok() | ||
} | ||
|
||
/// Receive a message from the other side of the connection. | ||
pub async fn receive(&self) -> Option<json_rpc::Message> { | ||
self.receiver.recv().await.ok() | ||
} | ||
|
||
/// Get a clone of the receiver channel. | ||
pub fn receiver(&self) -> Receiver<json_rpc::Message> { | ||
self.receiver.clone() | ||
} | ||
|
||
/// Get a clone of the sender channel. | ||
pub fn sender(&self) -> Sender<json_rpc::Message> { | ||
self.sender.clone() | ||
} | ||
} | ||
|
||
#[cfg(test)] | ||
mod tests { | ||
use tokio::net::TcpListener; | ||
|
||
use super::*; | ||
|
||
#[tokio::test] | ||
async fn test_sv1_connection() { | ||
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); | ||
let addr = listener.local_addr().unwrap(); | ||
let downstream_stream = TcpStream::connect(addr).await.unwrap(); | ||
let (upstream_stream, _) = listener.accept().await.unwrap(); | ||
|
||
let upstream_connection = ConnectionSV1::new(upstream_stream).await; | ||
let downstream_connection = ConnectionSV1::new(downstream_stream).await; | ||
let message = json_rpc::Message::StandardRequest(json_rpc::StandardRequest { | ||
id: 1, | ||
method: "test".to_string(), | ||
params: serde_json::Value::Null, | ||
}); | ||
assert!(downstream_connection.send(message).await); | ||
let received_on_upstream = upstream_connection.receive().await.unwrap(); | ||
match received_on_upstream { | ||
json_rpc::Message::StandardRequest(received) => { | ||
assert_eq!(received.id, 1); | ||
assert_eq!(received.method, "test".to_string()); | ||
assert_eq!(received.params, serde_json::Value::Null); | ||
} | ||
_ => { | ||
panic!("Unexpected message type"); | ||
} | ||
} | ||
let upstream_response = json_rpc::Message::OkResponse(json_rpc::Response { | ||
id: 1, | ||
result: serde_json::Value::String("response".to_string()), | ||
error: None, | ||
}); | ||
assert!(upstream_connection.send(upstream_response).await); | ||
let received_upstream = downstream_connection.receive().await.unwrap(); | ||
match received_upstream { | ||
json_rpc::Message::OkResponse(received) => { | ||
assert_eq!(received.id, 1); | ||
assert_eq!( | ||
received.result, | ||
serde_json::Value::String("response".to_string()) | ||
); | ||
} | ||
_ => { | ||
panic!("Unexpected message type"); | ||
} | ||
} | ||
} | ||
} |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
this comment feels a bit confusing
with
sender
I can send, withreceiver
I can receive... therefore this is bidirectional?There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
from my understanding I think they say a single Channel instance only handles communication in one direction. But yes I agree that the statement could be clearer.