Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 4 additions & 3 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions fuzz/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

27 changes: 10 additions & 17 deletions fuzz/fuzz_targets/fuzz_noise_handshake_and_roundtrip_encryption.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,11 +23,9 @@ fn generate_key(rand_seed: u64) -> Keypair {
}

// Represents the relationship between the initiator and responder during the Noise handshake.
// This determines whether the initiator knows and trusts the responder's public key.
// This determines whether the key the initiator pins is the responder's.
#[derive(PartialEq, Arbitrary, Debug)]
enum PeerMode {
// Initiator does not know the responder's public key -> performs anonymous handshake
Unknown,
// Initiator knows and expects the responder's specific public key -> authenticated handshake
Known,
// Initiator knows a different peer's key (not the responder's) -> handshake should fail
Expand All @@ -38,7 +36,7 @@ enum PeerMode {
// Generated by the arbitrary crate from raw fuzz input bytes.
#[derive(Debug, Arbitrary)]
struct FuzzInput {
// Controls whether initiator knows responder's public key
// Controls which authority public key the initiator pins
peer_mode: PeerMode,
// Certificate validity duration in seconds (passed to responder)
cert_validity: u32,
Expand Down Expand Up @@ -83,27 +81,22 @@ fuzz_target!(|input: FuzzInput| {
let responder_kp = generate_key(input.rand_seed);
let responder_pk: XOnlyPublicKey = responder_kp.public_key().x_only_public_key().0;

// Determine if the initiator knows the responder's key
// This affects the Noise handshake pattern (anonymous vs authenticated)
// Pick the authority public key the initiator pins
let known_peer = match input.peer_mode {
// Initiator has no prior knowledge of responder -> performs anonymous handshake
PeerMode::Unknown => None,
// Initiator knows responder's exact public key -> authenticated handshake
PeerMode::Known => Some(responder_pk),
PeerMode::Known => responder_pk,
// Initiator knows a DIFFERENT peer's key -> handshake should fail
PeerMode::PeerDifferentFromResponder => Some(
generate_key(input.rand_seed ^ 0xcafe_babe)
.public_key()
.x_only_public_key()
.0,
),
PeerMode::PeerDifferentFromResponder => generate_key(input.rand_seed ^ 0xcafe_babe)
.public_key()
.x_only_public_key()
.0,
};

// Create initiator (client) - optionally knows the responder
// Create initiator (client) pinning that key
let mut initiator = Initiator::new(known_peer);

// Create responder (server) with the generated keypair and certificate validity
let mut responder = Responder::new(responder_kp, input.cert_validity);
let responder = Responder::new(responder_kp, input.cert_validity);

// ========== Handshake Phase ==========

Expand Down
6 changes: 3 additions & 3 deletions stratum-core/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "stratum-core"
version = "0.7.0"
version = "0.8.0"
authors = ["The Stratum V2 Developers"]
edition = "2021"
readme = "README.md"
Expand All @@ -14,10 +14,10 @@ keywords = ["stratum", "mining", "bitcoin", "protocol"]
[dependencies]
buffer_sv2 = { path = "../sv2/buffer-sv2", version = "^4.0.0" }
binary_sv2 = { path = "../sv2/binary-sv2", version = "^8.0.0" }
codec_sv2 = { path = "../sv2/codec-sv2", version = "^8.0.0", features = ["noise_sv2"]}
codec_sv2 = { path = "../sv2/codec-sv2", version = "^9.0.0", features = ["noise_sv2"]}
extensions_sv2 = { path = "../sv2/extensions-sv2", version = "^0.4.0" }
framing_sv2 = { path = "../sv2/framing-sv2", version = "^9.0.0" }
noise_sv2 = { path = "../sv2/noise-sv2", version = "^2.1.0" }
noise_sv2 = { path = "../sv2/noise-sv2", version = "^3.0.0" }
parsers_sv2 = { path = "../sv2/parsers-sv2", version = "^0.7.0" }
handlers_sv2 = { path = "../sv2/handlers-sv2", version = "^0.7.0" }
channels_sv2 = { path = "../sv2/channels-sv2", version = "^9.0.0" }
Expand Down
5 changes: 3 additions & 2 deletions sv2/codec-sv2/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "codec_sv2"
version = "8.1.0"
version = "9.0.0"
authors = ["The Stratum V2 Developers"]
edition = "2021"
readme = "README.md"
Expand All @@ -13,13 +13,14 @@ keywords = ["stratum", "mining", "bitcoin", "protocol"]

[dependencies]
framing_sv2 = { path = "../framing-sv2", version = "^9.0.0" }
noise_sv2 = { path = "../noise-sv2", default-features = false, optional = true, version = "^2.1.0" }
noise_sv2 = { path = "../noise-sv2", default-features = false, optional = true, version = "^3.0.0" }
binary_sv2 = { path = "../binary-sv2", version = "^8.0.0" }
buffer_sv2 = { path = "../buffer-sv2", version = "^4.0.0" }
rand = { workspace = true, default-features = false }

[dev-dependencies]
key-utils = { workspace = true }
secp256k1 = { workspace = true }
criterion = { workspace = true }
rayon-core = { workspace = true }
quickcheck = { workspace = true }
Expand Down
10 changes: 3 additions & 7 deletions sv2/codec-sv2/benches/common.rs
Original file line number Diff line number Diff line change
Expand Up @@ -57,19 +57,15 @@ mod noise {

const AUTHORITY_PUBLIC_K: &str = "9auqWEzQDVyd2oe1JVGFLMLHZtCo2FFqZwtKA5gd9xbuEu7PH72";
const AUTHORITY_PRIVATE_K: &str = "mkDLTBBRxdBv998612qipDYoTK3YUrqLe8uWw7gu3iXbSrn2n";
const CERT_VALIDITY: core::time::Duration = core::time::Duration::from_secs(3600);
const CERT_VALIDITY: u32 = 3600;

pub fn make_handshake_pair() -> (Handshake<Initiator>, Handshake<Responder>) {
let public_k: Secp256k1PublicKey = AUTHORITY_PUBLIC_K.to_string().try_into().unwrap();
let private_k: Secp256k1SecretKey = AUTHORITY_PRIVATE_K.to_string().try_into().unwrap();

let initiator = Initiator::from_raw_k(public_k.into_bytes()).unwrap();
let responder = Responder::from_authority_kp(
&public_k.into_bytes(),
&private_k.into_bytes(),
CERT_VALIDITY,
)
.unwrap();
let authority = private_k.0.keypair(&secp256k1::Secp256k1::signing_only());
let responder = Responder::new(authority, CERT_VALIDITY);

(
Handshake::initiator(initiator),
Expand Down
36 changes: 12 additions & 24 deletions sv2/codec-sv2/examples/encrypted.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ const AUTHORITY_PUBLIC_K: &str = "9auqWEzQDVyd2oe1JVGFLMLHZtCo2FFqZwtKA5gd9xbuEu
#[cfg(feature = "noise_sv2")]
const AUTHORITY_PRIVATE_K: &str = "mkDLTBBRxdBv998612qipDYoTK3YUrqLe8uWw7gu3iXbSrn2n";
#[cfg(feature = "noise_sv2")]
const CERT_VALIDITY: std::time::Duration = std::time::Duration::from_secs(3600);
const CERT_VALIDITY: u32 = 3600;

// Example message type.
// In practice, all Sv2 messages are defined in the following crates:
Expand Down Expand Up @@ -97,21 +97,19 @@ fn main() {
Initiator::from_raw_k_with_rng(authority_public_k.into_bytes(), &mut rand::thread_rng())
.expect("Failed to create initiator role from raw pub key");

let authority = authority_private_k
.0
.keypair(&secp256k1::Secp256k1::signing_only());
#[cfg(feature = "std")]
let responder = Responder::from_authority_kp(
&authority_public_k.into_bytes(),
&authority_private_k.into_bytes(),
CERT_VALIDITY,
)
.expect("Failed to initialize responder from pub/key pair and/or cert");
let responder = Responder::new(authority, CERT_VALIDITY);
#[cfg(not(feature = "std"))]
let responder = Responder::from_authority_kp_with_rng(
&authority_public_k.into_bytes(),
&authority_private_k.into_bytes(),
CERT_VALIDITY,
&mut rand::thread_rng(),
)
.expect("Failed to initialize responder from pub/key pair and/or cert");
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_secs() as u32;
#[cfg(not(feature = "std"))]
let responder =
Responder::new_with_now_rng(authority, CERT_VALIDITY, now, &mut rand::thread_rng());

let sender = Handshake::initiator(initiator);
let receiver = Handshake::responder(responder);
Expand All @@ -124,19 +122,9 @@ fn main() {
.try_into()
.expect("Handshake remote invlaid message");

#[cfg(feature = "std")]
let (second_message, receiver_transport) = receiver
.step_1(first_message)
.expect("Responder failed second step of handshake");
#[cfg(not(feature = "std"))]
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_secs() as u32;
#[cfg(not(feature = "std"))]
let (second_message, receiver_transport) = receiver
.step_1_with_now_rng(first_message, now, &mut rand::thread_rng())
.expect("Responder failed second step of handshake");
let second_message: [u8; INITIATOR_EXPECTED_HANDSHAKE_MESSAGE_SIZE] = second_message
.payload()
.try_into()
Expand Down
34 changes: 7 additions & 27 deletions sv2/codec-sv2/src/state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ impl ExpectsHandshakeMessage for Responder {
/// [`Handshake::step_0`] is the only thing that builds one, which is what stops a caller from
/// sending that first message twice.
#[derive(Debug)]
pub struct InitiatorSent(Initiator);
pub struct InitiatorSent(Box<Initiator>);

/// The codec state while the handshake runs, in the role `R`: [`Initiator`] before it has sent
/// its first message, [`InitiatorSent`] after, or [`Responder`]. Frames exchanged in this state
Expand All @@ -74,13 +74,10 @@ pub struct InitiatorSent(Initiator);
/// use noise_sv2::{Responder, ELLSWIFT_ENCODING_SIZE};
///
/// fn responder() -> Handshake<Responder> { unimplemented!() }
/// fn rng() -> rand::rngs::ThreadRng { unimplemented!() }
///
/// let responder = responder();
/// let (_first, _transport) = responder
/// .step_1_with_now_rng([0; ELLSWIFT_ENCODING_SIZE], 0, &mut rng())
/// .unwrap();
/// let _second = responder.step_1_with_now_rng([0; ELLSWIFT_ENCODING_SIZE], 0, &mut rng());
/// let (_first, _transport) = responder.step_1([0; ELLSWIFT_ENCODING_SIZE]).unwrap();
/// let _second = responder.step_1([0; ELLSWIFT_ENCODING_SIZE]);
/// ```
///
/// Nor does sending the first message twice, which would mix it into the transcript twice and
Expand Down Expand Up @@ -130,7 +127,7 @@ impl Handshake<Initiator> {
Ok((
HandshakeMessage::from_message(message),
Handshake {
role: Box::new(InitiatorSent(*self.role)),
role: Box::new(InitiatorSent(self.role)),
},
))
}
Expand All @@ -140,7 +137,7 @@ impl Handshake<InitiatorSent> {
/// Completes the handshake with the responder's reply, consuming the state.
#[cfg(feature = "std")]
pub fn step_2(
mut self,
self,
message: [u8; INITIATOR_EXPECTED_HANDSHAKE_MESSAGE_SIZE],
) -> Result<Transport> {
self.role
Expand All @@ -154,7 +151,7 @@ impl Handshake<InitiatorSent> {
/// another source of time.
#[inline]
pub fn step_2_with_now(
mut self,
self,
message: [u8; INITIATOR_EXPECTED_HANDSHAKE_MESSAGE_SIZE],
now: u32,
) -> Result<Transport> {
Expand All @@ -174,9 +171,8 @@ impl Handshake<Responder> {

/// Answers the initiator's public key, completing the handshake on this side and consuming
/// the state. The returned frame is what the initiator needs for its [`Handshake::step_2`].
#[cfg(feature = "std")]
pub fn step_1(
mut self,
self,
re_pub: [u8; ELLSWIFT_ENCODING_SIZE],
) -> Result<(HandshakeMessage, Transport)> {
let (message, engine) = self.role.step_1(re_pub)?;
Expand All @@ -185,22 +181,6 @@ impl Handshake<Responder> {
Transport::new(engine),
))
}

/// [`Self::step_1`] given the current time and a random number generator, for `no_std`
/// environments that have their own of each.
#[inline]
pub fn step_1_with_now_rng<G: rand::Rng + rand::CryptoRng>(
mut self,
re_pub: [u8; ELLSWIFT_ENCODING_SIZE],
now: u32,
rng: &mut G,
) -> Result<(HandshakeMessage, Transport)> {
let (message, engine) = self.role.step_1_with_now_rng(re_pub, now, rng)?;
Ok((
HandshakeMessage::from_message(message),
Transport::new(engine),
))
}
}

/// The codec state once the handshake is complete, where AEAD encryption and decryption are
Expand Down
9 changes: 3 additions & 6 deletions sv2/codec-sv2/src/test_utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,15 +9,14 @@ use crate::{
Buffer, SerializedFrame, TransportDecryptState, TransportEncryptState,
};
use buffer_sv2::Buffer as IsBuffer;
use core::time::Duration;
use key_utils::{Secp256k1PublicKey, Secp256k1SecretKey};
use noise_sv2::{
Initiator, Responder, ELLSWIFT_ENCODING_SIZE, INITIATOR_EXPECTED_HANDSHAKE_MESSAGE_SIZE,
};

pub(crate) const AUTHORITY_PUBLIC_K: &str = "9auqWEzQDVyd2oe1JVGFLMLHZtCo2FFqZwtKA5gd9xbuEu7PH72";
pub(crate) const AUTHORITY_PRIVATE_K: &str = "mkDLTBBRxdBv998612qipDYoTK3YUrqLe8uWw7gu3iXbSrn2n";
pub(crate) const CERT_VALIDITY: Duration = Duration::from_secs(3600);
pub(crate) const CERT_VALIDITY: u32 = 3600;

pub(crate) type Slice = <Buffer as IsBuffer>::Slice;

Expand All @@ -26,13 +25,11 @@ pub(crate) fn make_handshake_pair() -> (Handshake<Initiator>, Handshake<Responde
let pub_k: Secp256k1PublicKey = AUTHORITY_PUBLIC_K.to_string().try_into().unwrap();
let pub_k_bytes = pub_k.into_bytes();
let priv_k: Secp256k1SecretKey = AUTHORITY_PRIVATE_K.to_string().try_into().unwrap();
let priv_k_bytes = priv_k.into_bytes();
let authority = priv_k.0.keypair(&secp256k1::Secp256k1::signing_only());

(
Handshake::initiator(Initiator::from_raw_k(pub_k_bytes).unwrap()),
Handshake::responder(
Responder::from_authority_kp(&pub_k_bytes, &priv_k_bytes, CERT_VALIDITY).unwrap(),
),
Handshake::responder(Responder::new(authority, CERT_VALIDITY)),
)
}

Expand Down
2 changes: 1 addition & 1 deletion sv2/noise-sv2/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "noise_sv2"
version = "2.1.0"
version = "3.0.0"
authors = ["The Stratum V2 Developers"]
edition = "2021"
readme = "README.md"
Expand Down
2 changes: 1 addition & 1 deletion sv2/noise-sv2/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
`noise_sv2` is primarily intended to secure communication in the Stratum V2 (Sv2) protocol. It handles the necessary Noise handshakes, encrypts outgoing messages, and decrypts incoming responses, ensuring privacy and integrity across the communication link between Sv2 roles. See the [Protocol Security specification](https://github.com/stratum-mining/sv2-spec/blob/main/04-Protocol-Security.md) for more details.

## Key Capabilities
* **Secure Communication**: Provides encryption and authentication for messages exchanged between different Sv2 roles. The responder is only authenticated when the `Initiator` is given its authority public key; an `Initiator` built without one (`Initiator::without_pk`) yields an encrypted but unauthenticated session.
* **Secure Communication**: Provides encryption and authentication for messages exchanged between different Sv2 roles. Every `Initiator` pins the responder's authority public key and rejects a certificate that does not verify against it. A server that uses `Responder::new` signs a certificate for every connection it accepts, so the authority private key has to be on that server; this is for development and testing. In production, sign the certificate on a machine that holds the authority private key, and give the server only its static key and that certificate through `Responder::from_certificate`. `SignatureNoiseMessage` is that certificate's format, for whatever issues it.
* **Cipher Support**: Uses `ChaCha20-Poly1305` for authenticated encryption.
* **Handshake Roles**: Implements the `Initiator` and `Responder` roles required by the Noise handshake, allowing both sides of a connection to establish secure communication.
* **Cryptographic Helpers**: Facilitates the management of cryptographic state and encryption operations.
Expand Down
Loading
Loading