Skip to content

Commit

Permalink
Merge pull request #1179 from rrybarczyk/framing-sv2-doc-cmt-syntax-u…
Browse files Browse the repository at this point in the history
…pdate

`framing-sv2` doc cmts to conform to standard
  • Loading branch information
plebhash authored Dec 18, 2024
2 parents 6171b37 + 2c6a7e4 commit 367c55a
Show file tree
Hide file tree
Showing 7 changed files with 324 additions and 72 deletions.
7 changes: 6 additions & 1 deletion protocols/v2/framing-sv2/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,14 @@ const_sv2 = { version = "^3.0.0", path = "../../../protocols/v2/const-sv2"}
binary_sv2 = { version = "^1.0.0", path = "../../../protocols/v2/binary-sv2/binary-sv2" }
buffer_sv2 = { version = "^1.0.0", path = "../../../utils/buffer", optional=true }

[dev-dependencies]
noise_sv2 = { version = "1.0", path = "../../../protocols/v2/noise-sv2"}
rand = "0.8.3"
secp256k1 = { version = "0.28.2", default-features = false, features =["alloc","rand","rand-std"] }

[features]
with_serde = ["binary_sv2/with_serde", "serde", "buffer_sv2?/with_serde"]
with_buffer_pool = ["binary_sv2/with_buffer_pool", "buffer_sv2"]

[package.metadata.docs.rs]
all-features = true
all-features = true
71 changes: 69 additions & 2 deletions protocols/v2/framing-sv2/README.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,70 @@
# framing_sv2
# `framing_sv2`

`framing_sv2` is a Rust `no_std` crate
[![crates.io](https://img.shields.io/crates/v/framing_sv2.svg)](https://crates.io/crates/framing_sv2)
[![docs.rs](https://docs.rs/framing_sv2/badge.svg)](https://docs.rs/framing_sv2)
[![rustc+](https://img.shields.io/badge/rustc-1.75.0%2B-lightgrey.svg)](https://blog.rust-lang.org/2023/12/28/Rust-1.75.0.html)
[![license](https://img.shields.io/badge/license-MIT%2FApache--2.0-blue.svg)](https://github.com/stratum-mining/stratum/blob/main/LICENSE.md)
[![codecov](https://codecov.io/gh/stratum-mining/stratum/branch/main/graph/badge.svg?flag=framing_sv2-coverage)](https://codecov.io/gh/stratum-mining/stratum)

`framing_sv2` provides utilities for framing messages sent between Sv2 roles, handling both Sv2
message and Noise handshake frames.

The Sv2 protocol is binary, with fixed message framing. Each message begins with the extension
type, message type, and message length (six bytes in total), followed by a variable length
message. The message framing is outlined below ([according to Sv2 specs
](https://github.com/stratum-mining/sv2-spec/blob/main/03-Protocol-Overview.md#32-framing)):

| Field Name | Byte Length | Description |
|----------------|-------------|-------------|
| `extension_type` | `U16` | Unique identifier of the extension associated with this protocol message. |
| `msg_type` | `U8` | Unique identifier of this protocol message. |
| `msg_length` | `U24` | Length of the protocol message, not including this header. |
| `payload` | `BYTES` | Message-specific payload of length `msg_length`. If the MSB in `extension_type` (the `channel_msg` bit) is set the first four bytes are defined as a `U32` `"channel_id"`, though this definition is repeated in the message definitions below and these 4 bytes are included in `msg_length`. |

Some bits of the `extension_type` field can also be repurposed for signaling on how the frame
should be handled across channels.

The least significant bit of `extension_type` (i.e.bit 15, 0-indexed, aka `channel_msg`) indicates
a message which is specific to a channel, whereas if the most significant bit is unset, the message
is to be interpreted by the immediate receiving device.

Note that the `channel_msg` bit is ignored in the extension lookup, i.e.an `extension_type` of
`0x8ABC` is for the same "extension" as `0x0ABC`.

If the `channel_msg` bit is set, the first four bytes of the payload field is a `U32` representing
the `channel_id` this message is destined for (these bytes are repeated in the message framing
descriptions below).

Note that for the Job Declaration and Template Distribution Protocols the `channel_msg` bit is
always unset.

## Main Components

- **Header**: Defines the 6-byte Sv2 message header with information about the message payload,
including its extension type, if it is associated with a specific mining channel, the type of
message (e.g. `SetupConnection`, `NewMiningJob`, etc.) and the payload length.
- **Sv2 Framing**: Use for serializing Sv2 messages.
- **Noise Handshake Framing**: Use for serializing Noise protocol handshake messages.

## Usage

To include this crate in your project, run:

```bash
cargo add framing_sv2
```

This crate can be built with the following feature flags:

- `with_buffer_pool`: Enables buffer pooling for more efficient memory management.
- `with_serde`: builds [`binary_sv2`](https://crates.io/crates/binary_sv2) and
[`buffer_sv2`](https://crates.io/crates/buffer_sv2) crates with `serde`-based encoding and
decoding. Note that this feature flag is only used for the Message Generator, and deprecated
for any other kind of usage. It will likely be fully deprecated in the future.

### Examples

This crate provides an example demonstrating how to serialize and deserialize Sv2 message frames:

1. **[Sv2 Frame](https://github.com/stratum-mining/stratum/blob/main/protocols/v2/framing-sv2/examples/sv2_frame.rs)**:
Constructs, serializes, and deserialize a regular Sv2 message frame (`Sv2Frame`).
77 changes: 77 additions & 0 deletions protocols/v2/framing-sv2/examples/sv2_frame.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
// # Sv2 Frame Example
//
// This example demonstrates how to use the `framing_sv2` crate to construct, serialize, and
// deserialize a regular Sv2 message frame (`Sv2Frame`). It showcases how to:
//
// - Define a message payload and frame it using the Sv2 protocol.
// - Define a custom message type (`CustomMessage`) to be framed.
// - Construct an Sv2 frame with the custom message, message type, and extension type.
// - Serialize the frame into a byte array.
// - Deserialize the frame from the byte array back into an Sv2 frame.
//
// In the Sv2 protocol, these frames can then be encoded and transmitted between Sv2 roles.
//
// ## Run
//
// ```
// cargo run --example sv2_frame --features with_serde
// ```

#[cfg(feature = "with_serde")]
use binary_sv2::{GetSize, Serialize};
#[cfg(feature = "with_serde")]
use framing_sv2::framing::Sv2Frame;

// Example message type (e.g., SetupConnection)
#[cfg(feature = "with_serde")]
const MSG_TYPE: u8 = 1;
// Example extension type (e.g., a standard Sv2 message)
#[cfg(feature = "with_serde")]
const EXT_TYPE: u16 = 0x0001;

#[cfg(feature = "with_serde")]
#[derive(Serialize, Debug)]
struct CustomMessage {
pub data: u32,
}

// Implemented to help determine the size of the message when framing.
#[cfg(feature = "with_serde")]
impl GetSize for CustomMessage {
fn get_size(&self) -> usize {
4 // `data` is `u32`, which is 4 bytes
}
}

#[cfg(feature = "with_serde")]
fn main() {
// Create the message payload
let message = CustomMessage { data: 42 };

// Create the frame from the message
let frame: Sv2Frame<CustomMessage, Vec<u8>> =
Sv2Frame::from_message(message, MSG_TYPE, EXT_TYPE, false)
.expect("Failed to frame the message");

// How header information is accessed
let header = frame.get_header().expect("Frame has no header");
assert_eq!(header.msg_type(), MSG_TYPE);
assert_eq!(header.ext_type(), EXT_TYPE);

// Serialize the frame into a byte array for transmission
let mut serialized_frame = vec![0u8; frame.encoded_length()];
frame
.serialize(&mut serialized_frame)
.expect("Failed to serialize the frame");

// Deserialize the frame from bytes back into an Sv2Frame
let mut deserialized_frame = Sv2Frame::<CustomMessage, Vec<u8>>::from_bytes(serialized_frame)
.expect("Failed to deserialize frame");
assert_eq!(deserialized_frame.encoded_length(), 10); // 6 header bytes + 4 payload bytes
assert_eq!(deserialized_frame.payload(), [42, 0, 0, 0]);
}

#[cfg(not(feature = "with_serde"))]
fn main() {
eprintln!("Serde feature not enabled. Skipping example.");
}
5 changes: 5 additions & 0 deletions protocols/v2/framing-sv2/src/error.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,15 @@
//! # Error Handling
//!
//! This module defines error types and utilities for handling errors in the `framing_sv2` module.
// use crate::framing2::EitherFrame;
use core::fmt;

// pub type FramingResult<T> = core::result::Result<T, Error>;

#[derive(Debug, PartialEq, Eq)]
pub enum Error {
/// Binary Sv2 data format error.
BinarySv2Error(binary_sv2::Error),
ExpectedHandshakeFrame,
ExpectedSv2Frame,
Expand Down
Loading

0 comments on commit 367c55a

Please sign in to comment.