From 182f0259b0e8f0e410dd31dce5bd7b8f90a2c061 Mon Sep 17 00:00:00 2001 From: plebhash Date: Mon, 9 Nov 2026 13:03:28 -0300 Subject: [PATCH 1/9] refactor(stratum-apps): move the key_utils root out of its directory No content change. The module is split into submodules next, and git records a split as a rename only when the file that keeps most of the content leaves its path; with the root at key_utils.rs the split can move it into key_utils/keys.rs and put the index back at mod.rs. --- stratum-apps/src/{key_utils/mod.rs => key_utils.rs} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename stratum-apps/src/{key_utils/mod.rs => key_utils.rs} (100%) diff --git a/stratum-apps/src/key_utils/mod.rs b/stratum-apps/src/key_utils.rs similarity index 100% rename from stratum-apps/src/key_utils/mod.rs rename to stratum-apps/src/key_utils.rs From ac759eeb6b1b811b3ba83f9787a593f77842cc62 Mon Sep 17 00:00:00 2001 From: plebhash Date: Mon, 9 Nov 2026 14:55:17 -0300 Subject: [PATCH 2/9] refactor(stratum-apps): split key_utils into submodules One file held the key encodings, the Schnorr signature service and the error type. Give each its own module, re-exported from key_utils so every existing path still resolves, and drop the no_std attribute and alloc import that had no effect inside a module of a std crate. --- stratum-apps/src/key_utils/error.rs | 45 +++++++ .../src/{key_utils.rs => key_utils/keys.rs} | 118 ++---------------- stratum-apps/src/key_utils/mod.rs | 14 +++ stratum-apps/src/key_utils/signature.rs | 64 ++++++++++ 4 files changed, 130 insertions(+), 111 deletions(-) create mode 100644 stratum-apps/src/key_utils/error.rs rename stratum-apps/src/{key_utils.rs => key_utils/keys.rs} (62%) create mode 100644 stratum-apps/src/key_utils/mod.rs create mode 100644 stratum-apps/src/key_utils/signature.rs diff --git a/stratum-apps/src/key_utils/error.rs b/stratum-apps/src/key_utils/error.rs new file mode 100644 index 000000000..26f87c5d7 --- /dev/null +++ b/stratum-apps/src/key_utils/error.rs @@ -0,0 +1,45 @@ +//! Errors from decoding or checking keys. + +use bs58::decode::Error as Bs58DecodeError; +use core::fmt::Display; + +#[derive(Debug)] +pub enum Error { + Bs58Decode(Bs58DecodeError), + Secp256k1(secp256k1::Error), + KeyVersion(u16), + KeyLength, + Custom(String), +} + +impl Display for Error { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + match self { + Self::Bs58Decode(error) => write!(f, "Base58 code error: {error}"), + Self::Secp256k1(error) => write!(f, "Secp256k1 error: {error}"), + Self::KeyVersion(obtained) => { + write!(f, "Unknown public key version. version found: {obtained}") + } + Self::KeyLength => write!(f, "Bad key length"), + Self::Custom(error) => write!(f, "Custom error: {error}"), + } + } +} + +#[cfg(feature = "std")] +impl std::error::Error for Error {} +#[cfg(not(feature = "std"))] +#[rustversion::since(1.81)] +impl core::error::Error for Error {} + +impl From for Error { + fn from(e: Bs58DecodeError) -> Self { + Error::Bs58Decode(e) + } +} + +impl From for Error { + fn from(e: secp256k1::Error) -> Self { + Error::Secp256k1(e) + } +} diff --git a/stratum-apps/src/key_utils.rs b/stratum-apps/src/key_utils/keys.rs similarity index 62% rename from stratum-apps/src/key_utils.rs rename to stratum-apps/src/key_utils/keys.rs index 1e6cabb83..347820012 100644 --- a/stratum-apps/src/key_utils.rs +++ b/stratum-apps/src/key_utils/keys.rs @@ -1,60 +1,14 @@ -#![cfg_attr(not(feature = "std"), no_std)] +//! The secp256k1 keys Sv2 Noise uses, encoded as base58check strings. +//! +//! A secret key is the raw 32 bytes. A public key is the 32-byte x-only key prefixed with the +//! little-endian `u16` version `1`, the encoding Sv2 spec 4.7 defines for authority keys. -extern crate alloc; - -use alloc::{ - string::{String, ToString}, - vec::Vec, -}; -use bs58::{decode, decode::Error as Bs58DecodeError}; +use crate::key_utils::Error; +use bs58::decode; use core::{convert::TryFrom, fmt::Display, str::FromStr}; -use secp256k1::{ - Keypair, Message as SecpMessage, Secp256k1, SecretKey, SignOnly, VerifyOnly, XOnlyPublicKey, - schnorr::Signature, -}; +use secp256k1::{SecretKey, XOnlyPublicKey}; use serde::{Deserialize, Serialize}; -#[derive(Debug)] -pub enum Error { - Bs58Decode(Bs58DecodeError), - Secp256k1(secp256k1::Error), - KeyVersion(u16), - KeyLength, - Custom(String), -} - -impl Display for Error { - fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { - match self { - Self::Bs58Decode(error) => write!(f, "Base58 code error: {error}"), - Self::Secp256k1(error) => write!(f, "Secp256k1 error: {error}"), - Self::KeyVersion(obtained) => { - write!(f, "Unknown public key version. version found: {obtained}") - } - Self::KeyLength => write!(f, "Bad key length"), - Self::Custom(error) => write!(f, "Custom error: {error}"), - } - } -} - -#[cfg(feature = "std")] -impl std::error::Error for Error {} -#[cfg(not(feature = "std"))] -#[rustversion::since(1.81)] -impl core::error::Error for Error {} - -impl From for Error { - fn from(e: Bs58DecodeError) -> Self { - Error::Bs58Decode(e) - } -} - -impl From for Error { - fn from(e: secp256k1::Error) -> Self { - Error::Secp256k1(e) - } -} - #[derive(Debug, Copy, Clone, Serialize, Deserialize)] #[serde(into = "String", try_from = "String")] pub struct Secp256k1SecretKey(pub SecretKey); @@ -155,64 +109,6 @@ impl From for Secp256k1PublicKey { } } -pub struct SignatureService { - secp_sign: Secp256k1, - secp_verify: Secp256k1, -} - -impl SignatureService { - pub fn new() -> Self { - SignatureService { - secp_sign: Secp256k1::signing_only(), - secp_verify: Secp256k1::verification_only(), - } - } - - #[cfg(feature = "std")] - pub fn sign(&self, message: Vec, private_key: SecretKey) -> Signature { - self.sign_with_rng(message, private_key, &mut rand::thread_rng()) - } - - #[inline] - pub fn sign_with_rng( - &self, - message: Vec, - private_key: SecretKey, - rng: &mut R, - ) -> Signature { - let secret_key = private_key; - let kp = Keypair::from_secret_key(&self.secp_sign, &secret_key); - - self.secp_sign.sign_schnorr_with_rng( - &SecpMessage::from_digest_slice(&message).unwrap(), - &kp, - rng, - ) - } - - pub fn verify( - &self, - message: Vec, - signature: secp256k1::schnorr::Signature, - public_key: XOnlyPublicKey, - ) -> Result<(), secp256k1::Error> { - let x_only_public_key = public_key; - - // Verify signature - self.secp_verify.verify_schnorr( - &signature, - &secp256k1::Message::from_digest_slice(&message)?, - &x_only_public_key, - ) - } -} - -impl Default for SignatureService { - fn default() -> Self { - Self::new() - } -} - #[cfg(test)] mod test { use super::*; diff --git a/stratum-apps/src/key_utils/mod.rs b/stratum-apps/src/key_utils/mod.rs new file mode 100644 index 000000000..cdd0efc91 --- /dev/null +++ b/stratum-apps/src/key_utils/mod.rs @@ -0,0 +1,14 @@ +//! Keys and signatures for Sv2 Noise authentication. +//! +//! - [`crate::key_utils::keys`]: the authority and static keys, as the base58check strings +//! configuration uses. +//! - [`crate::key_utils::signature`]: Schnorr signing and verification over a digest. +//! - [`crate::key_utils::error`]: what can go wrong while decoding or checking them. + +pub mod error; +pub mod keys; +pub mod signature; + +pub use error::Error; +pub use keys::{Secp256k1PublicKey, Secp256k1SecretKey}; +pub use signature::SignatureService; diff --git a/stratum-apps/src/key_utils/signature.rs b/stratum-apps/src/key_utils/signature.rs new file mode 100644 index 000000000..b6ef45c08 --- /dev/null +++ b/stratum-apps/src/key_utils/signature.rs @@ -0,0 +1,64 @@ +//! Schnorr signing and verification over a 32-byte digest. + +use secp256k1::{ + Keypair, Message as SecpMessage, Secp256k1, SecretKey, SignOnly, VerifyOnly, XOnlyPublicKey, + schnorr::Signature, +}; + +pub struct SignatureService { + secp_sign: Secp256k1, + secp_verify: Secp256k1, +} + +impl SignatureService { + pub fn new() -> Self { + SignatureService { + secp_sign: Secp256k1::signing_only(), + secp_verify: Secp256k1::verification_only(), + } + } + + #[cfg(feature = "std")] + pub fn sign(&self, message: Vec, private_key: SecretKey) -> Signature { + self.sign_with_rng(message, private_key, &mut rand::thread_rng()) + } + + #[inline] + pub fn sign_with_rng( + &self, + message: Vec, + private_key: SecretKey, + rng: &mut R, + ) -> Signature { + let secret_key = private_key; + let kp = Keypair::from_secret_key(&self.secp_sign, &secret_key); + + self.secp_sign.sign_schnorr_with_rng( + &SecpMessage::from_digest_slice(&message).unwrap(), + &kp, + rng, + ) + } + + pub fn verify( + &self, + message: Vec, + signature: secp256k1::schnorr::Signature, + public_key: XOnlyPublicKey, + ) -> Result<(), secp256k1::Error> { + let x_only_public_key = public_key; + + // Verify signature + self.secp_verify.verify_schnorr( + &signature, + &secp256k1::Message::from_digest_slice(&message)?, + &x_only_public_key, + ) + } +} + +impl Default for SignatureService { + fn default() -> Self { + Self::new() + } +} From f7a8240037ee6016bacce63054ec374dfff953dd Mon Sep 17 00:00:00 2001 From: plebhash Date: Mon, 9 Nov 2026 13:04:06 -0300 Subject: [PATCH 3/9] feat(stratum-apps): add a Noise Certificate to key_utils A server that keeps its authority private key off the host needs a certificate issued for its static key somewhere else, and a way to check at startup that the certificate it was handed matches that key and that authority. Certificate is the 74-byte SIGNATURE_NOISE_MESSAGE (Sv2 spec 4.5.2) as one base58check string, the encoding the keys already use. Its layout, the digest it signs over the version, the validity window and the x-only static key (spec 4.5.3), and the clock tolerance Sv2 initiators apply all come from noise_sv2's SignatureNoiseMessage, which stratum-core re-exports, so the apps keep no copy of the format and the module needs the `core` feature. It exposes the window so operators can log when it expires and reports each check a certificate can fail with its own error. A certificate issued outside this code base is checked as a test vector. ref https://github.com/stratum-mining/stratum/issues/2437 --- stratum-apps/src/key_utils/certificate.rs | 325 ++++++++++++++++++++++ stratum-apps/src/key_utils/mod.rs | 6 + 2 files changed, 331 insertions(+) create mode 100644 stratum-apps/src/key_utils/certificate.rs diff --git a/stratum-apps/src/key_utils/certificate.rs b/stratum-apps/src/key_utils/certificate.rs new file mode 100644 index 000000000..74244e6bf --- /dev/null +++ b/stratum-apps/src/key_utils/certificate.rs @@ -0,0 +1,325 @@ +//! The certificate a Noise server presents, issued in advance where the authority key is kept. + +use crate::key_utils::{Secp256k1PublicKey, Secp256k1SecretKey}; +use bs58::decode; +use core::{convert::TryFrom, fmt::Display, str::FromStr}; +use secp256k1::{Keypair, Secp256k1}; +use serde::{Deserialize, Serialize}; +use stratum_core::noise_sv2::{ + CERTIFICATE_TIME_LEEWAY, CERTIFICATE_VERSION, SIGNATURE_NOISE_MESSAGE_SIZE, + SignatureNoiseMessage, +}; + +/// A Noise certificate issued in advance for a server's static key: the 74-byte +/// `SIGNATURE_NOISE_MESSAGE` of Sv2 spec 4.5.2, which the server sends verbatim during the +/// handshake. +/// +/// The format, the signature and the checks are `noise_sv2`'s [`SignatureNoiseMessage`], the type +/// Sv2 Noise initiators verify; the signature covers the version, the validity window and the +/// x-only static public key (spec 4.5.3), so a certificate is bound to one static key and one +/// authority. This type adds the base58check encoding used in configuration files and the +/// environment, like the keys. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(into = "String", try_from = "String")] +pub struct Certificate(pub [u8; SIGNATURE_NOISE_MESSAGE_SIZE]); + +/// Why a certificate string could not be decoded, or which check it failed. +#[derive(Debug)] +pub enum Error { + /// The base58check string does not decode. + Decode(decode::Error), + /// The string decoded to something other than the 74 bytes of a `SIGNATURE_NOISE_MESSAGE`. + Length(usize), + /// The certificate carries a version other than [`CERTIFICATE_VERSION`]. + Version(u16), + /// The signature does not verify for the given static and authority keys. + Signature, + /// The clock reading `now` falls outside the validity window. + Window { + valid_from: u32, + not_valid_after: u32, + now: u32, + }, +} + +impl Display for Error { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + match self { + Self::Decode(error) => write!(f, "Base58 code error: {error}"), + Self::Length(len) => write!( + f, + "certificate decodes to {len} bytes, expected {SIGNATURE_NOISE_MESSAGE_SIZE}" + ), + Self::Version(version) => write!( + f, + "certificate version {version} is not supported, expected {CERTIFICATE_VERSION}" + ), + Self::Signature => write!( + f, + "certificate signature does not verify for this static key and authority key" + ), + Self::Window { + valid_from, + not_valid_after, + now, + } => write!( + f, + "certificate is valid from {valid_from} until {not_valid_after} (unix time), \ + but the clock reads {now}" + ), + } + } +} + +impl core::error::Error for Error {} + +impl From for Error { + fn from(error: decode::Error) -> Self { + Error::Decode(error) + } +} + +impl TryFrom for Certificate { + type Error = Error; + + fn try_from(value: String) -> Result { + value.parse() + } +} + +impl FromStr for Certificate { + type Err = Error; + + fn from_str(value: &str) -> Result { + let decoded = decode(value).with_check(None).into_vec()?; + let bytes: [u8; SIGNATURE_NOISE_MESSAGE_SIZE] = decoded + .as_slice() + .try_into() + .map_err(|_| Error::Length(decoded.len()))?; + Ok(Certificate(bytes)) + } +} + +impl From for String { + fn from(certificate: Certificate) -> Self { + certificate.to_string() + } +} + +impl Display for Certificate { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + f.write_str(&bs58::encode(self.0).with_check().into_string()) + } +} + +impl Certificate { + /// Issues a certificate for `static_public_key`, signed by `authority_secret_key`, valid + /// between the two unix timestamps. + #[cfg(feature = "std")] + pub fn sign( + static_public_key: &Secp256k1PublicKey, + authority_secret_key: &Secp256k1SecretKey, + valid_from: u32, + not_valid_after: u32, + ) -> Self { + Self::sign_with_rng( + static_public_key, + authority_secret_key, + valid_from, + not_valid_after, + &mut rand::thread_rng(), + ) + } + + /// Like [`Self::sign`], with the random number generator the signature uses supplied by the + /// caller. + pub fn sign_with_rng( + static_public_key: &Secp256k1PublicKey, + authority_secret_key: &Secp256k1SecretKey, + valid_from: u32, + not_valid_after: u32, + rng: &mut R, + ) -> Self { + let authority = + Keypair::from_secret_key(&Secp256k1::signing_only(), &authority_secret_key.0); + Certificate( + SignatureNoiseMessage::sign_with_rng( + valid_from, + not_valid_after, + &static_public_key.0, + &authority, + rng, + ) + .into(), + ) + } + + /// Checks that this certificate was issued for `static_public_key` by the holder of + /// `authority_public_key`, and that `now` (unix time) falls inside its validity window, with + /// the same clock tolerance Sv2 Noise initiators apply. + pub fn verify( + &self, + static_public_key: &Secp256k1PublicKey, + authority_public_key: &Secp256k1PublicKey, + now: u32, + ) -> Result<(), Error> { + // The window is reported first, so a failure below can only be the signature. + self.check_validity(now)?; + if self + .message() + .verify_with_now(&static_public_key.0, &authority_public_key.0, now) + { + Ok(()) + } else { + Err(Error::Signature) + } + } + + /// The checks that need no authority key: the version is the supported one and `now` (unix + /// time) falls inside the validity window, with the same clock tolerance as [`Self::verify`]. + pub fn check_validity(&self, now: u32) -> Result<(), Error> { + let message = self.message(); + if message.version != CERTIFICATE_VERSION { + return Err(Error::Version(message.version)); + } + let (valid_from, not_valid_after) = (message.valid_from, message.not_valid_after); + if valid_from.saturating_sub(CERTIFICATE_TIME_LEEWAY) > now + || not_valid_after.saturating_add(CERTIFICATE_TIME_LEEWAY) < now + { + return Err(Error::Window { + valid_from, + not_valid_after, + now, + }); + } + Ok(()) + } + + /// Certificate format version. + pub fn version(&self) -> u16 { + self.message().version + } + + /// Start of the validity window (unix time). + pub fn valid_from(&self) -> u32 { + self.message().valid_from + } + + /// End of the validity window (unix time). + pub fn not_valid_after(&self) -> u32 { + self.message().not_valid_after + } + + fn message(&self) -> SignatureNoiseMessage { + SignatureNoiseMessage::from(self.0) + } +} + +#[cfg(test)] +mod test { + use super::*; + use secp256k1::SecretKey; + + #[test] + #[cfg(feature = "std")] + fn certificate_round_trips_and_verifies() { + let authority_secret: Secp256k1SecretKey = + "mkDLTBBRxdBv998612qipDYoTK3YUrqLe8uWw7gu3iXbSrn2n" + .parse() + .unwrap(); + let authority_public = Secp256k1PublicKey::from(authority_secret); + let static_secret: Secp256k1SecretKey = + "24Zfqe5i5LQVc8yV6okoMpiQn7DohfxTBRJSgBKeH65oS6Gtkd" + .parse() + .unwrap(); + let static_public = Secp256k1PublicKey::from(static_secret); + + let certificate = Certificate::sign(&static_public, &authority_secret, 1_000, 2_000); + assert_eq!(certificate.version(), CERTIFICATE_VERSION); + assert_eq!(certificate.valid_from(), 1_000); + assert_eq!(certificate.not_valid_after(), 2_000); + let encoded = certificate.to_string(); + assert_eq!(encoded.parse::().unwrap(), certificate); + + assert!( + certificate + .verify(&static_public, &authority_public, 1_500) + .is_ok() + ); + // The clock tolerance of Sv2 Noise initiators is honoured at both edges. + assert!( + certificate + .verify(&static_public, &authority_public, 995) + .is_ok() + ); + assert!( + certificate + .verify(&static_public, &authority_public, 2_005) + .is_ok() + ); + assert!(matches!( + certificate.verify(&static_public, &authority_public, 2_011), + Err(Error::Window { now: 2_011, .. }) + )); + assert!(certificate.check_validity(1_500).is_ok()); + assert!(matches!( + certificate.check_validity(989), + Err(Error::Window { now: 989, .. }) + )); + // Issued for another static key, or by another authority: the signature fails. + let other = Secp256k1PublicKey::from(Secp256k1SecretKey( + SecretKey::from_slice(&[7u8; 32]).unwrap(), + )); + assert!(matches!( + certificate.verify(&other, &authority_public, 1_500), + Err(Error::Signature) + )); + assert!(matches!( + certificate.verify(&static_public, &static_public, 1_500), + Err(Error::Signature) + )); + // A truncated string is reported as a length problem, not a checksum one. + let mut short = certificate.0.to_vec(); + short.pop(); + let short = bs58::encode(short).with_check().into_string(); + assert!(matches!( + short.parse::(), + Err(Error::Length(73)) + )); + let mut wrong_version = certificate; + wrong_version.0[0] = 1; + assert!(matches!( + wrong_version.verify(&static_public, &authority_public, 1_500), + Err(Error::Version(1)) + )); + } + + // Vector from stratum-mining/stratum#2437: a certificate issued outside this code base for + // the static key below, signed by the authority behind the shared test secret, valid from + // 2026-10-08T23:00:00Z to 2026-10-10T01:00:00Z. + #[test] + fn certificate_verification_matches_an_independent_issuer() { + let authority: Secp256k1PublicKey = "9auqWEzQDVyd2oe1JVGFLMLHZtCo2FFqZwtKA5gd9xbuEu7PH72" + .parse() + .unwrap(); + let static_secret: Secp256k1SecretKey = + "24Zfqe5i5LQVc8yV6okoMpiQn7DohfxTBRJSgBKeH65oS6Gtkd" + .parse() + .unwrap(); + let certificate: Certificate = "11Bq97W2YjA6HzQsudhPAFE93sqF6b23Uuo7gWvZY5HQH4U6f5iU7cuv5YPM2HKJgDZXZRoMR6t43aJWBRLjibkFqvHuWj8LTArMrmLSVq" + .parse() + .unwrap(); + assert_eq!(certificate.version(), 0); + assert_eq!(certificate.valid_from(), 1_791_500_400); + assert_eq!(certificate.not_valid_after(), 1_791_594_000); + assert!( + certificate + .verify( + &Secp256k1PublicKey::from(static_secret), + &authority, + 1_791_504_000 + ) + .is_ok() + ); + } +} diff --git a/stratum-apps/src/key_utils/mod.rs b/stratum-apps/src/key_utils/mod.rs index cdd0efc91..5fb13c039 100644 --- a/stratum-apps/src/key_utils/mod.rs +++ b/stratum-apps/src/key_utils/mod.rs @@ -2,13 +2,19 @@ //! //! - [`crate::key_utils::keys`]: the authority and static keys, as the base58check strings //! configuration uses. +//! - [`crate::key_utils::certificate`]: the certificate a server presents for its static key, +//! issued in advance (feature `core`, as its format is `noise_sv2`'s). //! - [`crate::key_utils::signature`]: Schnorr signing and verification over a digest. //! - [`crate::key_utils::error`]: what can go wrong while decoding or checking them. +#[cfg(feature = "core")] +pub mod certificate; pub mod error; pub mod keys; pub mod signature; +#[cfg(feature = "core")] +pub use certificate::Certificate; pub use error::Error; pub use keys::{Secp256k1PublicKey, Secp256k1SecretKey}; pub use signature::SignatureService; From f91b3df50ce21cc13dc179e9822c9c55f008f8bc Mon Sep 17 00:00:00 2001 From: plebhash Date: Mon, 9 Nov 2026 13:02:39 -0300 Subject: [PATCH 4/9] feat(stratum-apps)!: add ResponderCredentials for Noise servers Every server that accepts Noise connections builds its Responder from the authority keypair and a validity period, so it has to hold the authority private key and sign a certificate per handshake. ResponderCredentials names where a server's static key and certificate come from instead, one of: - a static private key and a certificate issued for it elsewhere, loaded once with the configuration; - the path of a TOML file holding the same, read before every handshake, so replacing the file (or the symlink it is) rotates the key without a restart and without touching open connections. Signing per handshake stays available on noise_sv2's Responder for library users, but no server built on stratum-apps does it: the authority secret key never belongs on a server, so the fields of that setup (authority_secret_key, cert_validity_sec) are refused with a reason instead of being ignored. It deserializes from flat fields, so application configs embed it with #[serde(flatten)] and the same fields work from the environment. Inline fields win over the file. A pre-issued certificate is checked for version and validity window before every handshake, and against the authority public key when one is configured, so a bad rotation is reported with a reason instead of as rejected handshakes. network_helpers::Error gains a variant for those refusals, which breaks exhaustive matches on it. ref https://github.com/stratum-mining/stratum/issues/2437 --- Cargo.lock | 1 + stratum-apps/Cargo.toml | 1 + stratum-apps/src/network_helpers/mod.rs | 12 +- .../src/network_helpers/noise_connection.rs | 27 +- .../network_helpers/responder_credentials.rs | 515 ++++++++++++++++++ 5 files changed, 542 insertions(+), 14 deletions(-) create mode 100644 stratum-apps/src/network_helpers/responder_credentials.rs diff --git a/Cargo.lock b/Cargo.lock index ad00fc915..b3f9d05b5 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4499,6 +4499,7 @@ dependencies = [ "stratum-core", "tokio", "tokio-util", + "toml 0.8.23", "tower", "tracing", "tracing-subscriber", diff --git a/stratum-apps/Cargo.toml b/stratum-apps/Cargo.toml index f3368e547..280d998c6 100644 --- a/stratum-apps/Cargo.toml +++ b/stratum-apps/Cargo.toml @@ -23,6 +23,7 @@ bitcoin-core-sv2 = { package = "bitcoin_core_sv2", version = "0.7.0", path = ".. # External dependencies needed by the modules # Network helpers dependencies async-channel = { version = "1.8.0" } +toml = { version = "0.8", default-features = false, features = ["parse"] } tokio = { version = "1.44.1", features = ["full"] } futures = { version = "0.3.28" } tokio-util = { version = "0.7.10", default-features = false, features = ["codec", "rt"], optional = true } diff --git a/stratum-apps/src/network_helpers/mod.rs b/stratum-apps/src/network_helpers/mod.rs index 3b47f6460..e3d9e5758 100644 --- a/stratum-apps/src/network_helpers/mod.rs +++ b/stratum-apps/src/network_helpers/mod.rs @@ -4,7 +4,8 @@ //! for Stratum V2 applications. It includes support for: //! //! - Noise-encrypted connections ([`crate::network_helpers::noise_connection`], -//! [`crate::network_helpers::noise_stream`]) +//! [`crate::network_helpers::noise_stream`]), with the server's static key and certificate +//! coming from [`crate::network_helpers::ResponderCredentials`] //! - SV1 protocol connections (`sv1_connection`) - when `sv1` feature is enabled //! - Hostname resolution ([`crate::network_helpers::resolve_hostname`]) //! @@ -13,11 +14,13 @@ pub mod noise_connection; pub mod noise_stream; pub mod resolve_hostname; +pub mod responder_credentials; #[cfg(feature = "sv1")] pub mod sv1_connection; pub use resolve_hostname::{ResolveError, resolve_host, resolve_host_port}; +pub use responder_credentials::ResponderCredentials; use async_channel::{RecvError, SendError}; use std::{fmt, time::Duration}; @@ -49,6 +52,9 @@ pub enum Error { HandshakeTimeout, /// Invalid key provided to construct an Initiator or Responder InvalidKey, + /// The server's static key and certificate are misconfigured, unreadable, or do not match + /// the authority they are checked against. See [`ResponderCredentials`]. + InvalidResponderCredentials(String), /// DNS resolution failed for a hostname DnsResolutionFailed(String), } @@ -72,6 +78,10 @@ impl fmt::Display for Error { Error::InvalidKey => write!(f, "Invalid key provided for handshake"), + Error::InvalidResponderCredentials(msg) => { + write!(f, "Invalid responder credentials: {msg}") + } + Error::DnsResolutionFailed(msg) => write!(f, "DNS resolution failed: {msg}"), } } diff --git a/stratum-apps/src/network_helpers/noise_connection.rs b/stratum-apps/src/network_helpers/noise_connection.rs index df54f5ae9..f311f4e2a 100644 --- a/stratum-apps/src/network_helpers/noise_connection.rs +++ b/stratum-apps/src/network_helpers/noise_connection.rs @@ -167,18 +167,16 @@ impl Connection { #[cfg(test)] mod tests { use super::*; - use crate::key_utils::{Secp256k1PublicKey, Secp256k1SecretKey}; - use std::time::Duration; + use crate::network_helpers::ResponderCredentials; use stratum_core::{ - codec_sv2::MessageFrame, - noise_sv2::{Initiator, Responder}, - parsers_sv2::AnyMessageOwned, + codec_sv2::MessageFrame, noise_sv2::Initiator, parsers_sv2::AnyMessageOwned, }; use tokio::net::TcpListener; - // same test authority keypair used by the integration tests - const PUB_KEY: &str = "9auqWEzQDVyd2oe1JVGFLMLHZtCo2FFqZwtKA5gd9xbuEu7PH72"; - const PRV_KEY: &str = "mkDLTBBRxdBv998612qipDYoTK3YUrqLe8uWw7gu3iXbSrn2n"; + // A throwaway static key and a certificate over it from the development authority, valid + // until the year 2106. The initiator below pins nothing, so any valid certificate does. + const STATIC_KEY: &str = "2Zdzjqd9c7EB4C9FBuqyDNzErruL4DNrJHoL5jhdE6QVArUTR8"; + const CERTIFICATE: &str = "11HpWbvGUzBwSTTVZMX6Dc1bVAupxFfvzkFqWfcQzXwVWWeCFQ6rQTDtrNbv4ncSx11gBb1trRbuhuCuXNptqbQBHnyx4VJKULV9e4AWew"; #[tokio::test] async fn cancellation_shuts_down_connection() { @@ -187,11 +185,14 @@ mod tests { let responder_task = tokio::spawn(async move { let (stream, _) = listener.accept().await.unwrap(); - let pub_key = PUB_KEY.parse::().unwrap().into_bytes(); - let prv_key = PRV_KEY.parse::().unwrap().into_bytes(); - let responder = - Responder::from_authority_kp(&pub_key, &prv_key, Duration::from_secs(10_000)) - .unwrap(); + let responder = ResponderCredentials::PreIssued { + static_private_key: STATIC_KEY.parse().unwrap(), + certificate: CERTIFICATE.parse().unwrap(), + authority_public_key: None, + } + .responder() + .await + .unwrap(); Connection::accept::>( stream, responder, diff --git a/stratum-apps/src/network_helpers/responder_credentials.rs b/stratum-apps/src/network_helpers/responder_credentials.rs new file mode 100644 index 000000000..caf098b1f --- /dev/null +++ b/stratum-apps/src/network_helpers/responder_credentials.rs @@ -0,0 +1,515 @@ +//! Where a Noise responder gets the static key and the certificate it presents to initiators. + +use std::{ + path::PathBuf, + time::{SystemTime, UNIX_EPOCH}, +}; + +use secp256k1::{Keypair, Secp256k1}; +use serde::{Deserialize, Deserializer, de}; +use stratum_core::noise_sv2::Responder; + +use crate::{ + key_utils::{Certificate, Secp256k1PublicKey, Secp256k1SecretKey}, + network_helpers::Error, +}; + +/// How a Noise server authenticates to initiators: where its static key and the certificate +/// over it come from. +/// +/// It deserializes from flat fields, so an application config embeds it with +/// `#[serde(flatten)]`. Each field can come from the configuration file or from the environment +/// through the config loader, which overrides field by field. On the merged fields, in order: +/// +/// 1. `static_private_key` and `certificate` set: [`Self::PreIssued`]. `active_static_key` is +/// ignored if also set. +/// 2. Otherwise `active_static_key` set: [`Self::File`]. +/// 3. Neither: refused. +/// +/// Because the loader merges first, an inline pair in the file still wins over an +/// `active_static_key` from the environment: the environment overrides fields, not the choice +/// between inline and file. Half an inline pair is refused. The authority secret key never +/// belongs on a server, so `authority_secret_key` and `cert_validity_sec`, the fields of the +/// former sign-per-handshake setup, are refused instead of being ignored. An optional +/// `authority_public_key` applies to whichever source is used. +#[derive(Debug, Clone, Deserialize)] +#[serde(try_from = "ResponderCredentialsConfig")] +pub enum ResponderCredentials { + /// A static key and a certificate issued for it where the authority private key is kept, + /// loaded once with the configuration. Rotating the key means restarting the process. + PreIssued { + /// The static key the certificate was issued for. + static_private_key: Secp256k1SecretKey, + /// Sent verbatim in every handshake. + certificate: Certificate, + /// When present, the certificate's signature is checked against it at startup and before + /// every handshake; its version and validity window are checked either way. Without it, + /// a certificate from another authority is only noticed when pinning initiators reject + /// the handshake: it is the initiators that authenticate this server, not this check. + authority_public_key: Option, + }, + /// A static key and certificate read from a TOML file before every handshake, so rotation + /// means replacing the file (or the symlink it is) and touches neither the process nor its + /// open connections. The file holds `static_private_key`, `certificate` and optionally + /// `authority_public_key`, with the same encodings as the configuration. + /// + /// The file's contents are parsed and dropped per handshake without wiping memory, the + /// same posture the configuration loader has for the keys it holds; what this variant keeps + /// off the host is the authority private key. + File { + /// The file to read before every handshake; `~` and environment variables expand. + path: PathBuf, + /// When present, every certificate read from the file is checked against it, in + /// addition to any `authority_public_key` the file itself names. + authority_public_key: Option, + }, +} + +// The flat fields `ResponderCredentials` is built from. See there for which combinations are +// accepted. +#[derive(Deserialize)] +struct ResponderCredentialsConfig { + #[serde(default)] + authority_public_key: Option, + // Only their presence matters, so the values are not parsed: a secret key that fails to + // parse must not reach the error message either. + #[serde(default)] + authority_secret_key: Option, + #[serde(default)] + cert_validity_sec: Option, + #[serde(default)] + static_private_key: Option, + #[serde(default)] + certificate: Option, + #[serde(default, deserialize_with = "opt_expanded_path")] + active_static_key: Option, +} + +impl TryFrom for ResponderCredentials { + type Error = Error; + + fn try_from(config: ResponderCredentialsConfig) -> Result { + if config.authority_secret_key.is_some() || config.cert_validity_sec.is_some() { + return Err(Error::InvalidResponderCredentials( + "authority_secret_key and cert_validity_sec are not accepted: a server never \ + holds the authority secret key. Issue a certificate where that key is kept \ + and set static_private_key and certificate, or active_static_key" + .into(), + )); + } + match (config.static_private_key, config.certificate) { + (Some(static_private_key), Some(certificate)) => Ok(Self::PreIssued { + static_private_key, + certificate, + authority_public_key: config.authority_public_key, + }), + (None, None) => match config.active_static_key { + Some(path) => Ok(Self::File { + path, + authority_public_key: config.authority_public_key, + }), + None => Err(Error::InvalidResponderCredentials( + "no server keys configured: set static_private_key and certificate, or \ + active_static_key" + .into(), + )), + }, + _ => Err(Error::InvalidResponderCredentials( + "static_private_key and certificate must be set together".into(), + )), + } + } +} + +// Expands `~` and environment variables in a path, like the other path fields in app configs. +// A copy of `config_helpers::opt_path_from_toml`: that module is behind the `config` feature, +// which the `network` feature this type lives under does not imply. +fn opt_expanded_path<'de, D: Deserializer<'de>>( + deserializer: D, +) -> Result, D::Error> { + Option::::deserialize(deserializer)? + .map(|raw| { + shellexpand::full(&raw) + .map(|expanded| PathBuf::from(expanded.as_ref())) + .map_err(de::Error::custom) + }) + .transpose() +} + +// The TOML file a [`ResponderCredentials::File`] points at. Unknown keys are refused so a +// misspelled `authority_public_key` cannot silently skip the signature check. +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct StaticKeyFile { + static_private_key: Secp256k1SecretKey, + certificate: Certificate, + #[serde(default)] + authority_public_key: Option, +} + +impl ResponderCredentials { + /// Builds the responder for one handshake. + /// + /// For [`Self::File`] this reads the file, so a rotated file takes effect on the next + /// connection. A pre-issued certificate is checked for version and validity window, and + /// verified against every authority public key known for it, so a certificate that does not + /// match fails here with a reason instead of as a rejected handshake on the initiator's side + /// only. + pub async fn responder(&self) -> Result, Error> { + let (static_private_key, certificate) = self.resolve().await?; + let keypair = Keypair::from_secret_key(&Secp256k1::signing_only(), &static_private_key.0); + Ok(Responder::from_certificate(keypair, certificate.0.into())) + } + + /// Startup check: the loading and validation [`Self::responder`] does for a handshake, so a + /// missing file, an unreadable key or a certificate that does not match surfaces before the + /// server accepts connections. + pub async fn check(&self) -> Result<(), Error> { + self.resolve().await.map(|_| ()) + } + + // Loads the static key and its certificate, reading the file for [`Self::File`], and + // validates them: the version and validity window always, the signature against every + // authority public key known. + async fn resolve(&self) -> Result<(Secp256k1SecretKey, Certificate), Error> { + let (static_private_key, certificate, authorities) = match self { + Self::PreIssued { + static_private_key, + certificate, + authority_public_key, + } => ( + *static_private_key, + *certificate, + [*authority_public_key, None], + ), + Self::File { + path, + authority_public_key, + } => { + let raw = tokio::fs::read_to_string(path).await.map_err(|e| { + Error::InvalidResponderCredentials(format!( + "cannot read {}: {e}", + path.display() + )) + })?; + // Only the message: the full error quotes the offending line, which for a + // malformed `static_private_key` is the key itself. + let file: StaticKeyFile = toml::from_str(&raw).map_err(|e| { + Error::InvalidResponderCredentials(format!( + "cannot parse {}: {}", + path.display(), + e.message() + )) + })?; + ( + file.static_private_key, + file.certificate, + [*authority_public_key, file.authority_public_key], + ) + } + }; + fn invalid(e: impl ToString) -> Error { + Error::InvalidResponderCredentials(e.to_string()) + } + let now = SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap_or_default() + .as_secs() as u32; + certificate.check_validity(now).map_err(invalid)?; + let static_public_key = Secp256k1PublicKey::from(static_private_key); + for authority in authorities.into_iter().flatten() { + certificate + .verify(&static_public_key, &authority, now) + .map_err(invalid)?; + } + Ok((static_private_key, certificate)) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::network_helpers::{ + NOISE_HANDSHAKE_TIMEOUT, connect_with_noise, noise_stream::NoiseTcpStream, + }; + use tokio::net::{TcpListener, TcpStream}; + + const AUTHORITY_PUBLIC: &str = "9auqWEzQDVyd2oe1JVGFLMLHZtCo2FFqZwtKA5gd9xbuEu7PH72"; + const AUTHORITY_SECRET: &str = "mkDLTBBRxdBv998612qipDYoTK3YUrqLe8uWw7gu3iXbSrn2n"; + const STATIC_SECRET: &str = "24Zfqe5i5LQVc8yV6okoMpiQn7DohfxTBRJSgBKeH65oS6Gtkd"; + + fn now() -> u32 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap() + .as_secs() as u32 + } + + // A certificate for `static_secret` issued by `authority_secret`, valid around now. + fn issue(static_secret: &str, authority_secret: &str) -> Certificate { + let authority: Secp256k1SecretKey = authority_secret.parse().unwrap(); + let static_key: Secp256k1SecretKey = static_secret.parse().unwrap(); + Certificate::sign( + &Secp256k1PublicKey::from(static_key), + &authority, + now() - 60, + now() + 3600, + ) + } + + #[derive(Deserialize)] + struct AppConfig { + listen_address: String, + #[serde(flatten)] + credentials: ResponderCredentials, + } + + fn parse(extra: &str) -> Result { + toml::from_str::(&format!("listen_address = \"0.0.0.0:1\"\n{extra}")).map(|c| { + // The sibling field must survive the flattening untouched. + assert_eq!(c.listen_address, "0.0.0.0:1"); + c.credentials + }) + } + + #[test] + fn config_fields_select_the_variant() { + let certificate = issue(STATIC_SECRET, AUTHORITY_SECRET); + let inline = + format!("static_private_key = \"{STATIC_SECRET}\"\ncertificate = \"{certificate}\"\n"); + assert!(matches!( + parse(&inline).unwrap(), + ResponderCredentials::PreIssued { + authority_public_key: None, + .. + } + )); + assert!(matches!( + parse(&format!( + "{inline}authority_public_key = \"{AUTHORITY_PUBLIC}\"\n" + )) + .unwrap(), + ResponderCredentials::PreIssued { + authority_public_key: Some(_), + .. + } + )); + + assert!(matches!( + parse("active_static_key = \"./keys/active.toml\"\n").unwrap(), + ResponderCredentials::File { path, .. } if path == PathBuf::from("./keys/active.toml") + )); + // Inline fields win over the file. + assert!(matches!( + parse(&format!( + "{inline}active_static_key = \"./keys/active.toml\"\n" + )) + .unwrap(), + ResponderCredentials::PreIssued { .. } + )); + + // Half of a pair, nothing at all, or the fields of the former sign-per-handshake setup + // are refused, the last without parsing the secret key. + assert!(parse(&format!("static_private_key = \"{STATIC_SECRET}\"\n")).is_err()); + assert!(parse("").is_err()); + assert!(parse(&format!("authority_public_key = \"{AUTHORITY_PUBLIC}\"\n")).is_err()); + let dev = format!( + "authority_public_key = \"{AUTHORITY_PUBLIC}\"\nauthority_secret_key = \ + \"{AUTHORITY_SECRET}\"\ncert_validity_sec = 3600\n" + ); + assert!( + parse(&dev) + .unwrap_err() + .to_string() + .contains("authority_secret_key") + ); + assert!( + parse(&format!( + "{inline}authority_secret_key = \"{AUTHORITY_SECRET}\"\n" + )) + .is_err() + ); + assert!( + parse("active_static_key = \"./keys/active.toml\"\ncert_validity_sec = 3600\n") + .is_err() + ); + assert!(parse("authority_secret_key = \"not a key\"\n").is_err()); + } + + // Accepts one connection with `credentials` and reports whether the handshake succeeded. + async fn serve_one(listener: &TcpListener, credentials: &ResponderCredentials) -> bool { + let (stream, _) = listener.accept().await.unwrap(); + match credentials.responder().await { + Ok(responder) => NoiseTcpStream::accept(stream, responder, NOISE_HANDSHAKE_TIMEOUT) + .await + .is_ok(), + Err(_) => false, + } + } + + // Connects once, pinning the test authority, and reports whether the handshake succeeded. + async fn connect_once(addr: std::net::SocketAddr) -> bool { + let stream = TcpStream::connect(addr).await.unwrap(); + connect_with_noise(stream, Some(AUTHORITY_PUBLIC.parse().unwrap())) + .await + .is_ok() + } + + #[tokio::test] + async fn pre_issued_certificate_satisfies_a_pinning_initiator() { + let credentials = parse(&format!( + "static_private_key = \"{STATIC_SECRET}\"\ncertificate = \"{}\"\n", + issue(STATIC_SECRET, AUTHORITY_SECRET) + )) + .unwrap(); + credentials.check().await.unwrap(); + + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap(); + let (served, connected) = + tokio::join!(serve_one(&listener, &credentials), connect_once(addr)); + assert!(served && connected); + + // With the authority named, a certificate from another authority is refused up front. + let other_authority = + Secp256k1SecretKey(secp256k1::SecretKey::from_slice(&[9u8; 32]).unwrap()); + let foreign = parse(&format!( + "static_private_key = \"{STATIC_SECRET}\"\ncertificate = \"{}\"\nauthority_public_key = \ + \"{AUTHORITY_PUBLIC}\"\n", + issue(STATIC_SECRET, &other_authority.to_string()) + )) + .unwrap(); + assert!(matches!( + foreign.check().await, + Err(Error::InvalidResponderCredentials(_)) + )); + + // Without an authority key the window is still checked, so an expired certificate is + // refused here instead of by every initiator. + let static_key: Secp256k1SecretKey = STATIC_SECRET.parse().unwrap(); + let authority: Secp256k1SecretKey = AUTHORITY_SECRET.parse().unwrap(); + let expired = ResponderCredentials::PreIssued { + static_private_key: static_key, + certificate: Certificate::sign( + &Secp256k1PublicKey::from(static_key), + &authority, + now() - 7200, + now() - 3600, + ), + authority_public_key: None, + }; + assert!(matches!( + expired.check().await, + Err(Error::InvalidResponderCredentials(msg)) if msg.contains("valid from") + )); + } + + #[tokio::test] + async fn an_authority_key_in_the_key_file_is_checked_too() { + let path = std::env::temp_dir().join(format!( + "sv2-static-key-authority-{}-{}.toml", + std::process::id(), + now() + )); + let write = |authority_secret: &str| { + std::fs::write( + &path, + format!( + "static_private_key = \"{STATIC_SECRET}\"\ncertificate = \"{}\"\n\ + authority_public_key = \"{AUTHORITY_PUBLIC}\"\n", + issue(STATIC_SECRET, authority_secret) + ), + ) + .unwrap() + }; + let credentials = parse(&format!("active_static_key = \"{}\"\n", path.display())).unwrap(); + + write(AUTHORITY_SECRET); + credentials.check().await.unwrap(); + + let other_authority = + Secp256k1SecretKey(secp256k1::SecretKey::from_slice(&[9u8; 32]).unwrap()); + write(&other_authority.to_string()); + assert!(matches!( + credentials.check().await, + Err(Error::InvalidResponderCredentials(_)) + )); + + std::fs::remove_file(&path).unwrap(); + } + + #[tokio::test] + async fn rotating_the_key_file_takes_effect_on_the_next_connection() { + let dir = + std::env::temp_dir().join(format!("sv2-static-key-{}-{}", std::process::id(), now())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("active_static_key.toml"); + let write = |static_secret: &str, certificate: Certificate| { + std::fs::write( + &path, + format!( + "static_private_key = \"{static_secret}\"\ncertificate = \"{certificate}\"\n" + ), + ) + .unwrap() + }; + + let credentials = parse(&format!( + "active_static_key = \"{}\"\nauthority_public_key = \"{AUTHORITY_PUBLIC}\"\n", + path.display() + )) + .unwrap(); + // The file is not there yet: startup must refuse. + assert!(credentials.check().await.is_err()); + + write(STATIC_SECRET, issue(STATIC_SECRET, AUTHORITY_SECRET)); + credentials.check().await.unwrap(); + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap(); + let (served, connected) = + tokio::join!(serve_one(&listener, &credentials), connect_once(addr)); + assert!(served && connected); + + // Rotate to a new static key, certified by the same authority: no restart needed. + let new_static = + Secp256k1SecretKey(secp256k1::SecretKey::from_slice(&[5u8; 32]).unwrap()).to_string(); + write(&new_static, issue(&new_static, AUTHORITY_SECRET)); + let (served, connected) = + tokio::join!(serve_one(&listener, &credentials), connect_once(addr)); + assert!(served && connected); + + // A key file with a corrupted static key is refused without the key reaching the error + // message, which the servers log. + let mut corrupted = new_static.clone(); + corrupted.pop(); + corrupted.push('1'); + std::fs::write( + &path, + format!( + "static_private_key = \"{corrupted}\"\ncertificate = \"{}\"\n", + issue(&new_static, AUTHORITY_SECRET) + ), + ) + .unwrap(); + match credentials.check().await { + Err(Error::InvalidResponderCredentials(msg)) => { + assert!(!msg.contains(&corrupted[..20]), "{msg}") + } + other => panic!("expected a refusal, got {other:?}"), + } + + // A rotation to a certificate from another authority is caught by the configured + // authority_public_key before the handshake. + let other_authority = + Secp256k1SecretKey(secp256k1::SecretKey::from_slice(&[9u8; 32]).unwrap()); + write( + &new_static, + issue(&new_static, &other_authority.to_string()), + ); + let (served, connected) = + tokio::join!(serve_one(&listener, &credentials), connect_once(addr)); + assert!(!served && !connected); + + std::fs::remove_dir_all(&dir).unwrap(); + } +} From 917ee45e659f417a37357c008f345c1f9880c668 Mon Sep 17 00:00:00 2001 From: plebhash Date: Mon, 9 Nov 2026 13:12:19 -0300 Subject: [PATCH 5/9] feat!: let Pool, JDS and JDC present a pre-issued certificate The three servers read authority_public_key, authority_secret_key and cert_validity_sec and passed them to every accepted connection through accept_noise_connection, so the authority private key had to sit in each server's configuration. accept_noise_connection now takes a ResponderCredentials, and the servers' configs flatten one in place of those fields: a server sets static_private_key and certificate, or active_static_key pointing at a file that is re-read per handshake; authority_public_key stays as the optional key to check the certificate against, and the other two are refused with a reason. JDS embedded in a Pool inherits the Pool's credentials as it inherited its keys. Each downstream server checks its credentials once before binding, so a misconfiguration fails startup with a reason. The programmatic constructors take the credentials directly: Pool's AuthorityConfig and JDC's PoolConfig held nothing else and are gone, and ConnectionConfig no longer carries a certificate validity. The test harness, including the sniffer that stands in for a server, presents a throwaway static key with a certificate from the shared test authority valid until the year 2106, so the harness no longer holds that authority's secret key. ref https://github.com/stratum-mining/stratum/issues/2437 --- integration-tests/lib/mod.rs | 66 +++++----------- integration-tests/lib/utils.rs | 22 ++---- miner-apps/jd-client/src/args.rs | 74 +++++++++++++++++- .../jd-client/src/lib/channel_manager/mod.rs | 11 ++- .../template_message_handler.rs | 20 ++--- miner-apps/jd-client/src/lib/config.rs | 55 +++----------- miner-apps/jd-client/src/lib/jdc_runtime.rs | 4 +- pool-apps/jd-server/src/lib/config.rs | 45 +++-------- .../jd-server/src/lib/job_declarator/mod.rs | 18 ++--- pool-apps/pool/src/args.rs | 76 ++++++++++++++++++- pool-apps/pool/src/lib/channel_manager/mod.rs | 13 ++-- pool-apps/pool/src/lib/config.rs | 62 ++++----------- pool-apps/pool/src/lib/pool_runtime.rs | 8 +- stratum-apps/src/network_helpers/mod.rs | 25 ++---- 14 files changed, 245 insertions(+), 254 deletions(-) diff --git a/integration-tests/lib/mod.rs b/integration-tests/lib/mod.rs index 4beb04cfa..165ca0ed3 100644 --- a/integration-tests/lib/mod.rs +++ b/integration-tests/lib/mod.rs @@ -11,9 +11,8 @@ use std::{ net::{Ipv4Addr, SocketAddr}, }; use stratum_apps::{ - bitcoin_core_sv2::runtime_api::BitcoinCoreVersion, - config_helpers::CoinbaseRewardScript, - key_utils::{Secp256k1PublicKey, Secp256k1SecretKey}, + bitcoin_core_sv2::runtime_api::BitcoinCoreVersion, config_helpers::CoinbaseRewardScript, + key_utils::Secp256k1PublicKey, network_helpers::ResponderCredentials, tp_type::TemplateProviderType, }; use tracing::Level; @@ -119,6 +118,17 @@ pub fn start_sniffer( (sniffer, listening_address) } +/// What servers under test present in the Noise handshake: a throwaway static key and the +/// certificate the shared test authority issued for it, valid until the year 2106. The clients +/// under test pin that authority's public key; no test holds its secret key. +pub fn test_responder_credentials() -> ResponderCredentials { + ResponderCredentials::PreIssued { + static_private_key: "2Zdzjqd9c7EB4C9FBuqyDNzErruL4DNrJHoL5jhdE6QVArUTR8".parse().unwrap(), + certificate: "11HpWbvGUzBwSTTVZMX6Dc1bVAupxFfvzkFqWfcQzXwVWWeCFQ6rQTDtrNbv4ncSx11gBb1trRbuhuCuXNptqbQBHnyx4VJKULV9e4AWew".parse().unwrap(), + authority_public_key: Some("9auqWEzQDVyd2oe1JVGFLMLHZtCo2FFqZwtKA5gd9xbuEu7PH72".parse().unwrap()), + } +} + pub async fn start_pool( template_provider_config: TemplateProviderType, supported_extensions: Vec, @@ -127,25 +137,11 @@ pub async fn start_pool( ) -> (PoolSv2, SocketAddr, Option) { use pool_sv2::config::PoolConfig; let listening_address = get_available_address(); - let authority_public_key = Secp256k1PublicKey::try_from( - "9auqWEzQDVyd2oe1JVGFLMLHZtCo2FFqZwtKA5gd9xbuEu7PH72".to_string(), - ) - .expect("failed"); - let authority_secret_key = Secp256k1SecretKey::try_from( - "mkDLTBBRxdBv998612qipDYoTK3YUrqLe8uWw7gu3iXbSrn2n".to_string(), - ) - .expect("failed"); - let cert_validity_sec = 3600; let coinbase_reward_script = CoinbaseRewardScript::from_descriptor(POOL_COINBASE_REWARD_DESCRIPTOR).unwrap(); let pool_signature = "Stratum V2 SRI Pool".to_string(); - let connection_config = pool_sv2::config::ConnectionConfig::new( - listening_address, - cert_validity_sec, - pool_signature, - ); - let authority_config = - pool_sv2::config::AuthorityConfig::new(authority_public_key, authority_secret_key); + let connection_config = + pool_sv2::config::ConnectionConfig::new(listening_address, pool_signature); let share_batch_size = 1; let monitoring_address = if enable_monitoring { Some(get_available_address()) @@ -156,7 +152,7 @@ pub async fn start_pool( let config = PoolConfig::new( connection_config, template_provider_config, - authority_config, + test_responder_credentials(), coinbase_reward_script, SHARES_PER_MINUTE, share_batch_size, @@ -252,16 +248,8 @@ pub fn start_jdc_with_user_identities( jdc_mode: Option, jdc_signature: &str, ) -> (JobDeclaratorClient, SocketAddr, Option) { - use jd_client_sv2::config::{JobDeclaratorClientConfig, PoolConfig, ProtocolConfig, Upstream}; + use jd_client_sv2::config::{JobDeclaratorClientConfig, ProtocolConfig, Upstream}; let jdc_address = get_available_address(); - let authority_public_key = Secp256k1PublicKey::try_from( - "9auqWEzQDVyd2oe1JVGFLMLHZtCo2FFqZwtKA5gd9xbuEu7PH72".to_string(), - ) - .unwrap(); - let authority_secret_key = Secp256k1SecretKey::try_from( - "mkDLTBBRxdBv998612qipDYoTK3YUrqLe8uWw7gu3iXbSrn2n".to_string(), - ) - .unwrap(); let coinbase_reward_script = CoinbaseRewardScript::from_descriptor(JDC_COINBASE_REWARD_DESCRIPTOR).unwrap(); let authority_pubkey = Secp256k1PublicKey::try_from( @@ -281,7 +269,6 @@ pub fn start_jdc_with_user_identities( ) }) .collect(); - let pool_config = PoolConfig::new(authority_public_key, authority_secret_key); let protocol_config = ProtocolConfig::new(2, 2, coinbase_reward_script); let monitoring_address = if enable_monitoring { Some(get_available_address()) @@ -294,8 +281,7 @@ pub fn start_jdc_with_user_identities( protocol_config, 10.0, 1, - pool_config, - 3600, + test_responder_credentials(), template_provider_config, upstreams, jdc_signature.to_string(), @@ -322,20 +308,11 @@ pub async fn start_pool_with_jds( required_extensions: Vec, enable_monitoring: bool, ) -> (PoolSv2, SocketAddr, SocketAddr, Option) { - use pool_sv2::config::{AuthorityConfig, ConnectionConfig, JDSPartialConfig, PoolConfig}; + use pool_sv2::config::{ConnectionConfig, JDSPartialConfig, PoolConfig}; let pool_address = get_available_address(); let jds_address = get_available_address(); - let authority_public_key = Secp256k1PublicKey::try_from( - "9auqWEzQDVyd2oe1JVGFLMLHZtCo2FFqZwtKA5gd9xbuEu7PH72".to_string(), - ) - .expect("failed"); - let authority_secret_key = Secp256k1SecretKey::try_from( - "mkDLTBBRxdBv998612qipDYoTK3YUrqLe8uWw7gu3iXbSrn2n".to_string(), - ) - .expect("failed"); - let cert_validity_sec = 3600; let coinbase_reward_script = CoinbaseRewardScript::from_descriptor(POOL_COINBASE_REWARD_DESCRIPTOR).unwrap(); @@ -346,8 +323,7 @@ pub async fn start_pool_with_jds( ); let pool_signature = "Stratum V2 SRI Pool".to_string(); - let connection_config = ConnectionConfig::new(pool_address, cert_validity_sec, pool_signature); - let authority_config = AuthorityConfig::new(authority_public_key, authority_secret_key); + let connection_config = ConnectionConfig::new(pool_address, pool_signature); let share_batch_size = 1; let monitoring_address = if enable_monitoring { Some(get_available_address()) @@ -358,7 +334,7 @@ pub async fn start_pool_with_jds( let config = PoolConfig::new( connection_config, template_provider_config, - authority_config, + test_responder_credentials(), coinbase_reward_script.clone(), SHARES_PER_MINUTE, share_batch_size, diff --git a/integration-tests/lib/utils.rs b/integration-tests/lib/utils.rs index f215db542..c00b23f38 100644 --- a/integration-tests/lib/utils.rs +++ b/integration-tests/lib/utils.rs @@ -16,11 +16,10 @@ use std::{ time::{Duration, Instant}, }; use stratum_apps::{ - key_utils::{Secp256k1PublicKey, Secp256k1SecretKey}, network_helpers::noise_connection::Connection, stratum_core::{ framing_sv2::framing::MessageFrame, - noise_sv2::{Initiator, Responder}, + noise_sv2::Initiator, parsers_sv2::{ AnyMessage, AnyMessageOwned, ExtensionsNegotiationOwned, ExtensionsOwned, IsSv2Message, Tlv, message_type_to_name, parse_message_frame_with_tlvs, @@ -245,19 +244,12 @@ pub async fn wait_for_client(listen_socket: SocketAddr) -> tokio::net::TcpStream pub async fn create_downstream( stream: tokio::net::TcpStream, ) -> Option<(Receiver, Sender)> { - let pub_key = "9auqWEzQDVyd2oe1JVGFLMLHZtCo2FFqZwtKA5gd9xbuEu7PH72" - .to_string() - .parse::() - .unwrap() - .into_bytes(); - let prv_key = "mkDLTBBRxdBv998612qipDYoTK3YUrqLe8uWw7gu3iXbSrn2n" - .to_string() - .parse::() - .unwrap() - .into_bytes(); - let responder = - Responder::from_authority_kp(&pub_key, &prv_key, std::time::Duration::from_secs(10000)) - .unwrap(); + // The sniffer stands in for the server its client pins, so it presents what the servers + // under test present. + let responder = crate::test_responder_credentials() + .responder() + .await + .unwrap(); if let Ok((receiver_from_client, sender_to_client)) = Connection::accept::(stream, responder, CancellationToken::new()).await diff --git a/miner-apps/jd-client/src/args.rs b/miner-apps/jd-client/src/args.rs index 980c7cce1..2ac38db35 100644 --- a/miner-apps/jd-client/src/args.rs +++ b/miner-apps/jd-client/src/args.rs @@ -67,10 +67,13 @@ mod tests { "9auqWEzQDVyd2oe1JVGFLMLHZtCo2FFqZwtKA5gd9xbuEu7PH72", ), ( - "JDC__AUTHORITY_SECRET_KEY", - "mkDLTBBRxdBv998612qipDYoTK3YUrqLe8uWw7gu3iXbSrn2n", + "JDC__STATIC_PRIVATE_KEY", + "2Zdzjqd9c7EB4C9FBuqyDNzErruL4DNrJHoL5jhdE6QVArUTR8", + ), + ( + "JDC__CERTIFICATE", + "11HpWbvGUzBwSTTVZMX6Dc1bVAupxFfvzkFqWfcQzXwVWWeCFQ6rQTDtrNbv4ncSx11gBb1trRbuhuCuXNptqbQBHnyx4VJKULV9e4AWew", ), - ("JDC__CERT_VALIDITY_SEC", "3600"), ( "JDC__COINBASE_REWARD_SCRIPT", "addr(tb1qa0sm0hxzj0x25rh8gw5xlzwlsfvvyz8u96w3p8)", @@ -126,4 +129,69 @@ mod tests { unsafe { std::env::remove_var(key) }; } } + + /// The pre-issued certificate fields reach `ResponderCredentials` from the environment + /// through the flattened struct. Own prefix, so this does not race the test above on the + /// process environment. + #[test] + fn jdc_config_loads_pre_issued_credentials_from_env() { + use stratum_apps::network_helpers::ResponderCredentials; + + let vars = [ + ("JDC_PREISSUED__LISTENING_ADDRESS", "0.0.0.0:34265"), + ("JDC_PREISSUED__MAX_SUPPORTED_VERSION", "2"), + ("JDC_PREISSUED__MIN_SUPPORTED_VERSION", "2"), + ( + "JDC_PREISSUED__STATIC_PRIVATE_KEY", + "2Zdzjqd9c7EB4C9FBuqyDNzErruL4DNrJHoL5jhdE6QVArUTR8", + ), + ( + "JDC_PREISSUED__CERTIFICATE", + "11HpWbvGUzBwSTTVZMX6Dc1bVAupxFfvzkFqWfcQzXwVWWeCFQ6rQTDtrNbv4ncSx11gBb1trRbuhuCuXNptqbQBHnyx4VJKULV9e4AWew", + ), + ( + "JDC_PREISSUED__COINBASE_REWARD_SCRIPT", + "addr(tb1qa0sm0hxzj0x25rh8gw5xlzwlsfvvyz8u96w3p8)", + ), + ("JDC_PREISSUED__JDC_SIGNATURE", "Sv2MinerSignature"), + ("JDC_PREISSUED__SHARES_PER_MINUTE", "6.0"), + ("JDC_PREISSUED__SHARE_BATCH_SIZE", "10"), + ( + "JDC_PREISSUED__TEMPLATE_PROVIDER_TYPE__SV2TP__ADDRESS", + "127.0.0.1:8442", + ), + ( + "JDC_PREISSUED__UPSTREAM_01__AUTHORITY_PUBKEY", + "9auqWEzQDVyd2oe1JVGFLMLHZtCo2FFqZwtKA5gd9xbuEu7PH72", + ), + ("JDC_PREISSUED__UPSTREAM_01__POOL_ADDRESS", "127.0.0.1"), + ("JDC_PREISSUED__UPSTREAM_01__POOL_PORT", "34254"), + ("JDC_PREISSUED__UPSTREAM_01__JDS_ADDRESS", "127.0.0.1"), + ("JDC_PREISSUED__UPSTREAM_01__JDS_PORT", "34264"), + ("JDC_PREISSUED__UPSTREAM_01__USER_IDENTITY", "user"), + ]; + for (key, value) in vars { + unsafe { std::env::set_var(key, value) }; + } + + let config: JobDeclaratorClientConfig = load_config( + "jdc-config-does-not-exist.toml", + "JDC_PREISSUED", + LIST_KEYS, + ENUM_KEYS, + ) + .expect("load JobDeclaratorClientConfig from env only"); + + for (key, _) in vars { + unsafe { std::env::remove_var(key) }; + } + + assert!(matches!( + config.responder_credentials(), + ResponderCredentials::PreIssued { + authority_public_key: None, + .. + } + )); + } } diff --git a/miner-apps/jd-client/src/lib/channel_manager/mod.rs b/miner-apps/jd-client/src/lib/channel_manager/mod.rs index db80947f7..555350aba 100644 --- a/miner-apps/jd-client/src/lib/channel_manager/mod.rs +++ b/miner-apps/jd-client/src/lib/channel_manager/mod.rs @@ -23,8 +23,7 @@ use stratum_apps::{ channel_utils::ReceiverCleanup, coinbase_output_constraints::coinbase_output_constraints_message, fallback_coordinator::FallbackCoordinator, - key_utils::{Secp256k1PublicKey, Secp256k1SecretKey}, - network_helpers::accept_noise_connection, + network_helpers::{ResponderCredentials, accept_noise_connection}, stratum_core::{ bitcoin::{Amount, Target, TxOut, consensus}, channels_sv2::{ @@ -1087,9 +1086,7 @@ impl ChannelManager { #[allow(clippy::too_many_arguments)] pub async fn start_downstream_server( self, - authority_public_key: Secp256k1PublicKey, - authority_secret_key: Secp256k1SecretKey, - cert_validity_sec: u64, + credentials: ResponderCredentials, listening_address: SocketAddr, task_manager: Arc, cancellation_token: CancellationToken, @@ -1107,6 +1104,7 @@ impl ChannelManager { // propagate. Everything after this point (waiting for the first template, then accepting) // runs in a background task, so bootstrap is never held hostage by the Template Provider. info!("Starting downstream server at {listening_address}"); + credentials.check().await.map_err(JDCError::shutdown)?; let server = TcpListener::bind(listening_address).await.map_err(|e| { error!(error = ?e, "Failed to bind downstream server at {listening_address}"); JDCError::shutdown(e) @@ -1180,6 +1178,7 @@ impl ChannelManager { supported_downstream_extensions.clone(); let required_extensions_inner = required_downstream_extensions.clone(); + let credentials_inner = credentials.clone(); // Tracked from the handshake on, so a connection accepted by this // generation is never set up after fallback has completed; the @@ -1195,7 +1194,7 @@ impl ChannelManager { info!("Fallback received during handshake, dropping connection"); return; } - result = accept_noise_connection(stream, authority_public_key, authority_secret_key, cert_validity_sec) => { + result = accept_noise_connection(stream, &credentials_inner) => { match result { Ok(r) => r, Err(e) => { diff --git a/miner-apps/jd-client/src/lib/channel_manager/template_message_handler.rs b/miner-apps/jd-client/src/lib/channel_manager/template_message_handler.rs index 56c6e5725..98348a9ad 100644 --- a/miner-apps/jd-client/src/lib/channel_manager/template_message_handler.rs +++ b/miner-apps/jd-client/src/lib/channel_manager/template_message_handler.rs @@ -696,7 +696,7 @@ mod tests { use stratum_apps::{ coinbase_output_constraints::coinbase_output_constraints_message, config_helpers::CoinbaseRewardScript, - key_utils::{Secp256k1PublicKey, Secp256k1SecretKey}, + network_helpers::ResponderCredentials, stratum_core::{ binary_sv2::B0255Owned, bitcoin::{ @@ -731,7 +731,7 @@ mod tests { MAX_CONSECUTIVE_DECLARATION_REFUSALS, MAX_REQUESTED_TEMPLATES, MAX_WAITING_FOR_TOKEN, MiningJobTokens, OutputSets, SOLO_FULL_EXTRANONCE_SIZE, }, - config::{ConfigJDCMode, JobDeclaratorClientConfig, PoolConfig, ProtocolConfig}, + config::{ConfigJDCMode, JobDeclaratorClientConfig, ProtocolConfig}, downstream::Downstream, error::Action, jd_mode::JDMode, @@ -770,17 +770,11 @@ mod tests { ), 10.0, 1, - PoolConfig::new( - Secp256k1PublicKey::try_from( - "9auqWEzQDVyd2oe1JVGFLMLHZtCo2FFqZwtKA5gd9xbuEu7PH72".to_string(), - ) - .unwrap(), - Secp256k1SecretKey::try_from( - "mkDLTBBRxdBv998612qipDYoTK3YUrqLe8uWw7gu3iXbSrn2n".to_string(), - ) - .unwrap(), - ), - 60, + ResponderCredentials::PreIssued { + static_private_key: "2Zdzjqd9c7EB4C9FBuqyDNzErruL4DNrJHoL5jhdE6QVArUTR8".parse().unwrap(), + certificate: "11HpWbvGUzBwSTTVZMX6Dc1bVAupxFfvzkFqWfcQzXwVWWeCFQ6rQTDtrNbv4ncSx11gBb1trRbuhuCuXNptqbQBHnyx4VJKULV9e4AWew".parse().unwrap(), + authority_public_key: None, + }, TemplateProviderType::Sv2Tp { address: "127.0.0.1:0".to_string(), public_key: None, diff --git a/miner-apps/jd-client/src/lib/config.rs b/miner-apps/jd-client/src/lib/config.rs index 91ea95e4a..27f614f67 100644 --- a/miner-apps/jd-client/src/lib/config.rs +++ b/miner-apps/jd-client/src/lib/config.rs @@ -6,7 +6,8 @@ use std::{ }; use stratum_apps::{ config_helpers::{CoinbaseRewardScript, opt_path_from_toml}, - key_utils::{Secp256k1PublicKey, Secp256k1SecretKey}, + key_utils::Secp256k1PublicKey, + network_helpers::ResponderCredentials, stratum_core::bitcoin::{Amount, TxOut}, tp_type::TemplateProviderType, utils::types::{SharesBatchSize, SharesPerMinute}, @@ -21,12 +22,10 @@ pub struct JobDeclaratorClientConfig { max_supported_version: u16, // The minimum supported SV2 protocol version. min_supported_version: u16, - // The public key used by this JDC for noise encryption. - authority_public_key: Secp256k1PublicKey, - /// The secret key used by this JDC for noise encryption. - authority_secret_key: Secp256k1SecretKey, - /// The validity period (in seconds) for the certificate used in noise. - cert_validity_sec: u64, + /// Static key and certificate presented to downstreams in the Noise handshake; see + /// [`ResponderCredentials`] for the fields that select it. + #[serde(flatten)] + credentials: ResponderCredentials, /// The template provider type that this JDC will use. template_provider_type: TemplateProviderType, /// A list of upstream Job Declarator Servers (JDS) that this JDC can connect to. @@ -106,8 +105,7 @@ impl JobDeclaratorClientConfig { protocol_config: ProtocolConfig, shares_per_minute: SharesPerMinute, shares_batch_size: SharesBatchSize, - pool_config: PoolConfig, - cert_validity_sec: u64, + credentials: ResponderCredentials, template_provider_type: TemplateProviderType, upstreams: Vec, jdc_signature: String, @@ -125,9 +123,7 @@ impl JobDeclaratorClientConfig { max_past_jobs: None, max_supported_version: protocol_config.max_supported_version, min_supported_version: protocol_config.min_supported_version, - authority_public_key: pool_config.authority_public_key, - authority_secret_key: pool_config.authority_secret_key, - cert_validity_sec, + credentials, template_provider_type, upstreams, coinbase_reward_script: protocol_config.coinbase_reward_script, @@ -178,19 +174,9 @@ impl JobDeclaratorClientConfig { &self.upstreams } - /// Returns the authority public key. - pub fn authority_public_key(&self) -> &Secp256k1PublicKey { - &self.authority_public_key - } - - /// Returns the authority secret key. - pub fn authority_secret_key(&self) -> &Secp256k1SecretKey { - &self.authority_secret_key - } - - /// Returns the certificate validity in seconds. - pub fn cert_validity_sec(&self) -> u64 { - self.cert_validity_sec + /// Static key and certificate presented to downstreams in the Noise handshake. + pub fn responder_credentials(&self) -> &ResponderCredentials { + &self.credentials } /// Returns the template provider type. @@ -313,25 +299,6 @@ where ConfigJDCMode::from_str(&s).map_err(serde::de::Error::custom) } -/// Represents pool specific encryption keys. -pub struct PoolConfig { - authority_public_key: Secp256k1PublicKey, - authority_secret_key: Secp256k1SecretKey, -} - -impl PoolConfig { - /// Creates a new instance of [`PoolConfig`]. - pub fn new( - authority_public_key: Secp256k1PublicKey, - authority_secret_key: Secp256k1SecretKey, - ) -> Self { - Self { - authority_public_key, - authority_secret_key, - } - } -} - /// Represent protocol versioning the JDC supports. pub struct ProtocolConfig { // The maximum supported SV2 protocol version. diff --git a/miner-apps/jd-client/src/lib/jdc_runtime.rs b/miner-apps/jd-client/src/lib/jdc_runtime.rs index 7ceebc4c6..a59a31b41 100644 --- a/miner-apps/jd-client/src/lib/jdc_runtime.rs +++ b/miner-apps/jd-client/src/lib/jdc_runtime.rs @@ -221,9 +221,7 @@ impl JdcRuntime { channel_manager .start_downstream_server( - *config.authority_public_key(), - *config.authority_secret_key(), - config.cert_validity_sec(), + config.responder_credentials().clone(), *config.listening_address(), task_manager, cancellation_token.clone(), diff --git a/pool-apps/jd-server/src/lib/config.rs b/pool-apps/jd-server/src/lib/config.rs index 557e881f6..f05a5f29c 100644 --- a/pool-apps/jd-server/src/lib/config.rs +++ b/pool-apps/jd-server/src/lib/config.rs @@ -9,15 +9,12 @@ //! - Validating and converting coinbase outputs use std::net::SocketAddr; -use stratum_apps::{ - config_helpers::CoinbaseRewardScript, - key_utils::{Secp256k1PublicKey, Secp256k1SecretKey}, -}; +use stratum_apps::{config_helpers::CoinbaseRewardScript, network_helpers::ResponderCredentials}; /// Partial configuration deserialized from the `[jds]` TOML section, when embedded in Pool. /// -/// Contains only JDS-specific fields. Shared fields (authority keys, cert validity, -/// coinbase script) are inherited from the parent Pool config. +/// Contains only JDS-specific fields. Shared fields (Noise credentials, coinbase script) are +/// inherited from the parent Pool config. #[derive(Clone, Debug, serde::Deserialize)] pub struct JDSPartialConfig { listen_address: SocketAddr, @@ -34,9 +31,7 @@ pub struct JDSPartialConfig { #[derive(Clone, Debug)] pub struct JDSConfig { listen_address: SocketAddr, - authority_public_key: Secp256k1PublicKey, - authority_secret_key: Secp256k1SecretKey, - cert_validity_sec: u64, + credentials: ResponderCredentials, coinbase_reward_script: CoinbaseRewardScript, supported_extensions: Vec, required_extensions: Vec, @@ -62,18 +57,14 @@ impl JDSConfig { #[allow(clippy::too_many_arguments)] pub fn new( listen_address: SocketAddr, - authority_public_key: Secp256k1PublicKey, - authority_secret_key: Secp256k1SecretKey, - cert_validity_sec: u64, + credentials: ResponderCredentials, coinbase_reward_script: CoinbaseRewardScript, supported_extensions: Vec, required_extensions: Vec, ) -> Self { Self { listen_address, - authority_public_key, - authority_secret_key, - cert_validity_sec, + credentials, coinbase_reward_script, supported_extensions, required_extensions, @@ -87,16 +78,12 @@ impl JDSConfig { #[allow(clippy::too_many_arguments)] pub fn from_partial( partial: JDSPartialConfig, - authority_public_key: Secp256k1PublicKey, - authority_secret_key: Secp256k1SecretKey, - cert_validity_sec: u64, + credentials: ResponderCredentials, coinbase_reward_script: CoinbaseRewardScript, ) -> Self { Self { listen_address: partial.listen_address, - authority_public_key, - authority_secret_key, - cert_validity_sec, + credentials, coinbase_reward_script, supported_extensions: partial.supported_extensions, required_extensions: partial.required_extensions, @@ -108,19 +95,9 @@ impl JDSConfig { &self.listen_address } - /// Authority public key used for the Noise handshake with downstreams. - pub fn authority_public_key(&self) -> &Secp256k1PublicKey { - &self.authority_public_key - } - - /// Authority secret key used for the Noise handshake with downstreams. - pub fn authority_secret_key(&self) -> &Secp256k1SecretKey { - &self.authority_secret_key - } - - /// Validity period (seconds) for the Noise certificate. - pub fn cert_validity_sec(&self) -> u64 { - self.cert_validity_sec + /// Static key and certificate presented to downstreams in the Noise handshake. + pub fn responder_credentials(&self) -> &ResponderCredentials { + &self.credentials } /// Script included in `AllocateMiningJobTokenSuccess.coinbase_outputs`. diff --git a/pool-apps/jd-server/src/lib/job_declarator/mod.rs b/pool-apps/jd-server/src/lib/job_declarator/mod.rs index 48257b17d..a3dc81a93 100644 --- a/pool-apps/jd-server/src/lib/job_declarator/mod.rs +++ b/pool-apps/jd-server/src/lib/job_declarator/mod.rs @@ -26,8 +26,7 @@ use std::{ use stratum_apps::{ bitcoin_core_sv2::CancellationToken, config_helpers::CoinbaseRewardScript, - key_utils::{Secp256k1PublicKey, Secp256k1SecretKey}, - network_helpers::accept_noise_connection, + network_helpers::{ResponderCredentials, accept_noise_connection}, stratum_core::{ handlers_sv2::HandleJobDeclarationMessagesFromClientOwnedAsync, mining_sv2::{ @@ -189,9 +188,7 @@ impl JobDeclarator { #[allow(clippy::too_many_arguments)] pub async fn start_downstream_server( self, - authority_public_key: Secp256k1PublicKey, - authority_secret_key: Secp256k1SecretKey, - cert_validity_sec: u64, + credentials: ResponderCredentials, listening_address: SocketAddr, task_manager: Arc, cancellation_token: CancellationToken, @@ -199,6 +196,9 @@ impl JobDeclarator { required_extensions: Vec, ) -> JDSResult<(), error::JobDeclarator> { info!("Starting downstream server at {listening_address}"); + credentials.check().await.map_err(|e| { + JDSError::shutdown(crate::error::JDSErrorKind::InvalidConfig(e.to_string())) + })?; let server = TcpListener::bind(listening_address) .await .map_err(|e| { @@ -226,15 +226,11 @@ impl JobDeclarator { let task_manager_inner = task_manager_clone.clone(); let supported_extensions_inner = supported_extensions.clone(); let required_extensions_inner = required_extensions.clone(); + let credentials_inner = credentials.clone(); task_manager_clone.spawn(async move { let noise_stream = tokio::select! { - result = accept_noise_connection( - stream, - authority_public_key, - authority_secret_key, - cert_validity_sec, - ) => { + result = accept_noise_connection(stream, &credentials_inner) => { match result { Ok(r) => r, Err(e) => { diff --git a/pool-apps/pool/src/args.rs b/pool-apps/pool/src/args.rs index 281bd09e8..11765ed9d 100644 --- a/pool-apps/pool/src/args.rs +++ b/pool-apps/pool/src/args.rs @@ -69,10 +69,13 @@ mod tests { "9auqWEzQDVyd2oe1JVGFLMLHZtCo2FFqZwtKA5gd9xbuEu7PH72", ), ( - "POOL__AUTHORITY_SECRET_KEY", - "mkDLTBBRxdBv998612qipDYoTK3YUrqLe8uWw7gu3iXbSrn2n", + "POOL__STATIC_PRIVATE_KEY", + "2Zdzjqd9c7EB4C9FBuqyDNzErruL4DNrJHoL5jhdE6QVArUTR8", + ), + ( + "POOL__CERTIFICATE", + "11HpWbvGUzBwSTTVZMX6Dc1bVAupxFfvzkFqWfcQzXwVWWeCFQ6rQTDtrNbv4ncSx11gBb1trRbuhuCuXNptqbQBHnyx4VJKULV9e4AWew", ), - ("POOL__CERT_VALIDITY_SEC", "3600"), ( "POOL__COINBASE_REWARD_SCRIPT", "addr(tb1qa0sm0hxzj0x25rh8gw5xlzwlsfvvyz8u96w3p8)", @@ -120,4 +123,71 @@ mod tests { unsafe { std::env::remove_var(key) }; } } + + /// The pre-issued certificate fields reach `ResponderCredentials` from the environment + /// through the flattened struct, both inline and as a key file path. Own prefix, so this + /// does not race the test above on the process environment. + #[test] + fn pool_config_loads_pre_issued_credentials_from_env() { + use stratum_apps::network_helpers::ResponderCredentials; + + let base = [ + ("POOL_PREISSUED__LISTEN_ADDRESS", "0.0.0.0:3333"), + ( + "POOL_PREISSUED__COINBASE_REWARD_SCRIPT", + "addr(tb1qa0sm0hxzj0x25rh8gw5xlzwlsfvvyz8u96w3p8)", + ), + ("POOL_PREISSUED__POOL_SIGNATURE", "Stratum V2 SRI Pool"), + ("POOL_PREISSUED__SHARES_PER_MINUTE", "6.0"), + ("POOL_PREISSUED__SHARE_BATCH_SIZE", "10"), + ( + "POOL_PREISSUED__TEMPLATE_PROVIDER_TYPE__SV2TP__ADDRESS", + "127.0.0.1:8442", + ), + ]; + let inline = [ + ( + "POOL_PREISSUED__STATIC_PRIVATE_KEY", + "2Zdzjqd9c7EB4C9FBuqyDNzErruL4DNrJHoL5jhdE6QVArUTR8", + ), + ( + "POOL_PREISSUED__CERTIFICATE", + "11HpWbvGUzBwSTTVZMX6Dc1bVAupxFfvzkFqWfcQzXwVWWeCFQ6rQTDtrNbv4ncSx11gBb1trRbuhuCuXNptqbQBHnyx4VJKULV9e4AWew", + ), + ( + "POOL_PREISSUED__AUTHORITY_PUBLIC_KEY", + "9auqWEzQDVyd2oe1JVGFLMLHZtCo2FFqZwtKA5gd9xbuEu7PH72", + ), + ]; + let file = [("POOL_PREISSUED__ACTIVE_STATIC_KEY", "~/keys/active.toml")]; + let load = |extra: &[(&str, &str)]| { + for (key, value) in base.iter().chain(extra) { + unsafe { std::env::set_var(key, value) }; + } + let config: PoolConfig = load_config( + "pool-config-does-not-exist.toml", + "POOL_PREISSUED", + LIST_KEYS, + ENUM_KEYS, + ) + .expect("load PoolConfig from env only"); + for (key, _) in base.iter().chain(extra) { + unsafe { std::env::remove_var(key) }; + } + config.responder_credentials().clone() + }; + + assert!(matches!( + load(&inline), + ResponderCredentials::PreIssued { + authority_public_key: Some(_), + .. + } + )); + // `~` is expanded like the other path fields. + assert!(matches!( + load(&file), + ResponderCredentials::File { path, .. } if !path.starts_with("~") + )); + } } diff --git a/pool-apps/pool/src/lib/channel_manager/mod.rs b/pool-apps/pool/src/lib/channel_manager/mod.rs index 61e2bd694..6b612d0d2 100644 --- a/pool-apps/pool/src/lib/channel_manager/mod.rs +++ b/pool-apps/pool/src/lib/channel_manager/mod.rs @@ -17,8 +17,7 @@ use stratum_apps::{ channel_utils::ReceiverCleanup, coinbase_output_constraints::coinbase_output_constraints_message_with_offset, config_helpers::CoinbaseRewardScript, - key_utils::{Secp256k1PublicKey, Secp256k1SecretKey}, - network_helpers::accept_noise_connection, + network_helpers::{ResponderCredentials, accept_noise_connection}, stratum_core::{ bitcoin::{Amount, TxOut}, channels_sv2::{ @@ -272,9 +271,7 @@ impl ChannelManager { #[allow(clippy::too_many_arguments)] pub async fn start_downstream_server( self, - authority_public_key: Secp256k1PublicKey, - authority_secret_key: Secp256k1SecretKey, - cert_validity_sec: u64, + credentials: ResponderCredentials, listening_address: SocketAddr, task_manager: Arc, cancellation_token: CancellationToken, @@ -287,6 +284,9 @@ impl ChannelManager { // propagate. Everything after this point (waiting for the first template, then accepting) // runs in a background task, so bootstrap is never held hostage by the Template Provider. info!("Starting downstream server at {listening_address}"); + credentials.check().await.map_err(|e| { + PoolError::shutdown(crate::error::PoolErrorKind::Configuration(e.to_string())) + })?; let server = TcpListener::bind(listening_address) .await .map_err(|e| { @@ -349,6 +349,7 @@ impl ChannelManager { let cancellation_token_inner = cancellation_token_clone.clone(); let channel_manager_sender_inner = channel_manager_sender.clone(); let task_manager_inner = task_manager_clone.clone(); + let credentials_inner = credentials.clone(); task_manager_clone.spawn(async move { let cancellation_token_clone = cancellation_token_inner.clone(); @@ -358,7 +359,7 @@ impl ChannelManager { info!("Shutdown received during handshake, dropping connection"); return; } - result = accept_noise_connection(stream, authority_public_key, authority_secret_key, cert_validity_sec) => { + result = accept_noise_connection(stream, &credentials_inner) => { match result { Ok(r) => r, Err(e) => { diff --git a/pool-apps/pool/src/lib/config.rs b/pool-apps/pool/src/lib/config.rs index 00076fc03..00cfe6b05 100644 --- a/pool-apps/pool/src/lib/config.rs +++ b/pool-apps/pool/src/lib/config.rs @@ -5,7 +5,7 @@ //! //! This module handles: //! - Initializing [`PoolConfig`] -//! - Managing [`TemplateProviderType`], [`AuthorityConfig`], [`CoinbaseRewardScript`], and +//! - Managing [`TemplateProviderType`], [`ResponderCredentials`], [`CoinbaseRewardScript`], and //! [`ConnectionConfig`] //! - Validating and converting coinbase outputs use std::{ @@ -16,7 +16,7 @@ use std::{ pub use jd_server_sv2::config::{JDSConfig, JDSPartialConfig}; use stratum_apps::{ config_helpers::{CoinbaseRewardScript, opt_path_from_toml}, - key_utils::{Secp256k1PublicKey, Secp256k1SecretKey}, + network_helpers::ResponderCredentials, stratum_core::bitcoin::{Amount, TxOut}, tp_type::TemplateProviderType, utils::types::{SharesBatchSize, SharesPerMinute}, @@ -24,14 +24,15 @@ use stratum_apps::{ use crate::error::PoolErrorKind; -/// Configuration for the Pool, including connection, authority, and coinbase settings. +/// Configuration for the Pool, including connection, Noise credentials, and coinbase settings. #[derive(Clone, Debug, serde::Deserialize)] pub struct PoolConfig { listen_address: SocketAddr, template_provider_type: TemplateProviderType, - authority_public_key: Secp256k1PublicKey, - authority_secret_key: Secp256k1SecretKey, - cert_validity_sec: u64, + /// Static key and certificate presented to downstreams in the Noise handshake; see + /// [`ResponderCredentials`] for the fields that select it. + #[serde(flatten)] + credentials: ResponderCredentials, coinbase_reward_script: CoinbaseRewardScript, pool_signature: String, shares_per_minute: SharesPerMinute, @@ -72,7 +73,7 @@ impl PoolConfig { pub fn new( pool_connection: ConnectionConfig, template_provider_type: TemplateProviderType, - authority_config: AuthorityConfig, + credentials: ResponderCredentials, coinbase_reward_script: CoinbaseRewardScript, shares_per_minute: SharesPerMinute, share_batch_size: SharesBatchSize, @@ -86,9 +87,7 @@ impl PoolConfig { Self { listen_address: pool_connection.listen_address, template_provider_type, - authority_public_key: authority_config.public_key, - authority_secret_key: authority_config.secret_key, - cert_validity_sec: pool_connection.cert_validity_sec, + credentials, coinbase_reward_script, pool_signature: pool_connection.signature, shares_per_minute, @@ -114,19 +113,9 @@ impl PoolConfig { &self.listen_address } - /// Returns the authority public key. - pub fn authority_public_key(&self) -> &Secp256k1PublicKey { - &self.authority_public_key - } - - /// Returns the authority secret key. - pub fn authority_secret_key(&self) -> &Secp256k1SecretKey { - &self.authority_secret_key - } - - /// Returns the certificate validity in seconds. - pub fn cert_validity_sec(&self) -> u64 { - self.cert_validity_sec + /// Static key and certificate presented to downstreams in the Noise handshake. + pub fn responder_credentials(&self) -> &ResponderCredentials { + &self.credentials } /// Returns the Pool signature. @@ -220,9 +209,7 @@ impl PoolConfig { let jds_config = JDSConfig::from_partial( jds_partial, - self.authority_public_key, - self.authority_secret_key, - self.cert_validity_sec, + self.credentials.clone(), self.coinbase_reward_script.clone(), ); @@ -230,33 +217,16 @@ impl PoolConfig { } } -/// Pool's authority public and secret keys. -pub struct AuthorityConfig { - pub public_key: Secp256k1PublicKey, - pub secret_key: Secp256k1SecretKey, -} - -impl AuthorityConfig { - pub fn new(public_key: Secp256k1PublicKey, secret_key: Secp256k1SecretKey) -> Self { - Self { - public_key, - secret_key, - } - } -} - /// Connection settings for the Pool listener. pub struct ConnectionConfig { listen_address: SocketAddr, - cert_validity_sec: u64, signature: String, } impl ConnectionConfig { - pub fn new(listen_address: SocketAddr, cert_validity_sec: u64, signature: String) -> Self { + pub fn new(listen_address: SocketAddr, signature: String) -> Self { Self { listen_address, - cert_validity_sec, signature, } } @@ -278,9 +248,9 @@ mod tests { format!( r#" listen_address = "0.0.0.0:34254" +static_private_key = "2Zdzjqd9c7EB4C9FBuqyDNzErruL4DNrJHoL5jhdE6QVArUTR8" +certificate = "11HpWbvGUzBwSTTVZMX6Dc1bVAupxFfvzkFqWfcQzXwVWWeCFQ6rQTDtrNbv4ncSx11gBb1trRbuhuCuXNptqbQBHnyx4VJKULV9e4AWew" authority_public_key = "9auqWEzQDVyd2oe1JVGFLMLHZtCo2FFqZwtKA5gd9xbuEu7PH72" -authority_secret_key = "mkDLTBBRxdBv998612qipDYoTK3YUrqLe8uWw7gu3iXbSrn2n" -cert_validity_sec = 3600 coinbase_reward_script = "addr(tb1qa0sm0hxzj0x25rh8gw5xlzwlsfvvyz8u96w3p8)" pool_signature = "test" shares_per_minute = 6.0 diff --git a/pool-apps/pool/src/lib/pool_runtime.rs b/pool-apps/pool/src/lib/pool_runtime.rs index a0b34004b..7367ad3a5 100644 --- a/pool-apps/pool/src/lib/pool_runtime.rs +++ b/pool-apps/pool/src/lib/pool_runtime.rs @@ -320,9 +320,7 @@ impl PoolRuntime { match jd .clone() .start_downstream_server( - *jds_config.authority_public_key(), - *jds_config.authority_secret_key(), - jds_config.cert_validity_sec(), + jds_config.responder_credentials().clone(), *jds_config.listen_address(), self.task_manager.clone(), cancellation_token.clone(), @@ -597,9 +595,7 @@ impl PoolRuntime { .channel_manager .clone() .start_downstream_server( - *self.pool.config.authority_public_key(), - *self.pool.config.authority_secret_key(), - self.pool.config.cert_validity_sec(), + self.pool.config.responder_credentials().clone(), *self.pool.config.listen_address(), self.task_manager.clone(), cancellation_token.clone(), diff --git a/stratum-apps/src/network_helpers/mod.rs b/stratum-apps/src/network_helpers/mod.rs index e3d9e5758..46906da90 100644 --- a/stratum-apps/src/network_helpers/mod.rs +++ b/stratum-apps/src/network_helpers/mod.rs @@ -24,16 +24,10 @@ pub use responder_credentials::ResponderCredentials; use async_channel::{RecvError, SendError}; use std::{fmt, time::Duration}; -use stratum_core::{ - codec_sv2::Error as CodecError, - noise_sv2::{Initiator, Responder}, -}; +use stratum_core::{codec_sv2::Error as CodecError, noise_sv2::Initiator}; use tokio::net::TcpStream; -use crate::{ - key_utils::{Secp256k1PublicKey, Secp256k1SecretKey}, - network_helpers::noise_stream::NoiseTcpStream, -}; +use crate::{key_utils::Secp256k1PublicKey, network_helpers::noise_stream::NoiseTcpStream}; /// Networking errors that can occur in SV2 connections #[derive(Debug)] @@ -144,20 +138,13 @@ pub async fn connect_with_noise( /// The handshake timeout is opinionated and fixed at `NOISE_HANDSHAKE_TIMEOUT`. If you need a /// custom timeout, use [`noise_stream::NoiseTcpStream::new`] directly. /// -/// `cert_validity` controls how long the generated Noise certificate is valid, -/// which is independent of the handshake timeout. +/// The static key and certificate the server presents come from `credentials`, resolved for +/// this one handshake (see [`ResponderCredentials::responder`]). pub async fn accept_noise_connection( stream: TcpStream, - pub_key: Secp256k1PublicKey, - prv_key: Secp256k1SecretKey, - cert_validity: u64, + credentials: &ResponderCredentials, ) -> Result { - let responder = Responder::from_authority_kp( - &pub_key.into_bytes(), - &prv_key.into_bytes(), - Duration::from_secs(cert_validity), - ) - .map_err(|_| Error::InvalidKey)?; + let responder = credentials.responder().await?; let stream = noise_stream::NoiseTcpStream::accept(stream, responder, NOISE_HANDSHAKE_TIMEOUT).await?; Ok(stream) From 55e0db1d05e26568e3286b78f2bb6307b63346c4 Mon Sep 17 00:00:00 2001 From: plebhash Date: Mon, 9 Nov 2026 13:16:59 -0300 Subject: [PATCH 6/9] feat(stratum-apps): add the sv2-certificate tool A server configured with a pre-issued certificate needs someone to issue it, on the machine that holds the authority secret key rather than on the server. sv2-certificate does that in three commands: keygen for an authority or static keypair, issue-certificate to certify a static key (generated on the spot unless given) over a chosen validity window, and inspect-certificate to read a certificate's window back. issue-certificate prints the result and, on request, writes it as the TOML file a server's active_static_key points at and/or as a .env file of __* variables for the config loader. Those files hold a private key, so they are created owner-readable only and never overwrite an existing file: a rotation writes a new file and moves a symlink. If one of the files cannot be written, the ones already created by that run are removed. ref https://github.com/stratum-mining/stratum/issues/2437 --- Cargo.lock | 2 + stratum-apps/Cargo.toml | 10 + stratum-apps/README.md | 50 ++++ stratum-apps/src/bin/sv2-certificate.rs | 309 ++++++++++++++++++++++++ 4 files changed, 371 insertions(+) create mode 100644 stratum-apps/src/bin/sv2-certificate.rs diff --git a/Cargo.lock b/Cargo.lock index b3f9d05b5..2a62b91f2 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4482,6 +4482,8 @@ dependencies = [ "axum", "bitcoin_core_sv2", "bs58", + "chrono", + "clap", "config", "dashmap", "dirs", diff --git a/stratum-apps/Cargo.toml b/stratum-apps/Cargo.toml index 280d998c6..64e63682f 100644 --- a/stratum-apps/Cargo.toml +++ b/stratum-apps/Cargo.toml @@ -57,6 +57,10 @@ utoipa-swagger-ui = { version = "10.0.2", features = ["axum", "vendored"], optio shellexpand = "3.1.1" dashmap = "6.1.0" +# `sv2-certificate` binary +clap = { version = "4.5", features = ["derive", "env"], optional = true } +chrono = { version = "0.4", default-features = false, features = ["alloc"], optional = true } + [features] default = ["network", "fallback-coordinator", "config", "std"] @@ -68,6 +72,7 @@ payout = ["config", "core"] monitoring = ["serde_json", "axum", "prometheus", "utoipa", "utoipa-swagger-ui"] asic-rs-telemetry = ["monitoring", "dep:asic-rs"] std = ["bs58/std", "secp256k1/rand-std", "rand/std", "rand/std_rng"] +cli = ["dep:clap", "dep:chrono", "std", "core"] core = ["stratum-core"] # Protocol features passed through to stratum-core @@ -93,5 +98,10 @@ name = "generate-openapi" path = "src/bin/generate-openapi.rs" required-features = ["monitoring"] +[[bin]] +name = "sv2-certificate" +path = "src/bin/sv2-certificate.rs" +required-features = ["cli"] + [package.metadata.docs.rs] features = ["pool", "jd_client", "jd_server", "translator", "sv1", "monitoring", "asic-rs-telemetry"] diff --git a/stratum-apps/README.md b/stratum-apps/README.md index f67cdb8ed..4523e7a9d 100644 --- a/stratum-apps/README.md +++ b/stratum-apps/README.md @@ -43,6 +43,7 @@ use stratum_apps::{network_helpers, config_helpers}; - `monitoring` - HTTP and Prometheus monitoring helpers (optional) - Uses vendored Swagger UI assets to support offline/sandboxed documentation builds - `std` - Standard-library support for key and random utilities (enabled by default) +- `cli` - The `sv2-certificate` binary, which issues the static key and certificate a Noise server presents (optional) - `core` - Re-export and enable `stratum-core` - `bitcoin-core-sv2` - Re-export and enable `bitcoin_core_sv2` @@ -85,3 +86,52 @@ let connection = // Use configuration let config: PoolConfig = config_helpers::parse_config("pool.toml")?; ``` + +## sv2-certificate + +A Noise server (Pool, JDS, JDC) authenticates to its clients with a certificate over its static +key, signed by the authority key the clients pin. `sv2-certificate` issues that certificate. Run +it where the authority secret key is kept, never on the server: the server needs only the static +private key and the certificate this tool writes, plus the authority public key to check them +against. + +Build it with the `cli` feature: + +```bash +cargo build -p stratum-apps --features cli --bin sv2-certificate +``` + +Generate a keypair, either the authority's (publish the public key, keep the secret key off every +server) or a server's static key: + +```bash +sv2-certificate keygen +``` + +Issue a certificate. The authority secret key is read from `SV2_AUTHORITY_SECRET_KEY`; typed at a +silent prompt it stays out of the shell history and of `ps` output. A fresh static key is +generated unless `--static-private-key` is given. `--valid-from` defaults to now; start the window +before the key goes live and let it outlast the next rotation by a margin, so a late rotation never +breaks handshakes: + +```bash +read -rs SV2_AUTHORITY_SECRET_KEY && export SV2_AUTHORITY_SECRET_KEY +sv2-certificate issue-certificate --valid-for 93600 \ + --toml /etc/sv2/key_2.toml \ + --env /etc/sv2/key_2.env --env-prefix POOL +``` + +`--toml` writes the file a server's `active_static_key` points at. `--env` writes +`__STATIC_PRIVATE_KEY`, `__CERTIFICATE` and `__AUTHORITY_PUBLIC_KEY` for +the application's config loader, with the prefix the application uses (`POOL` or `JDC`). The two +files look alike inside, so their names must end in `.toml` and `.env`. Both are created readable +by their owner only and never overwrite an existing file: rotate by writing a new file and moving +the symlink. Without either flag the values are printed instead. + +Read a certificate's version and validity window back: + +```bash +sv2-certificate inspect-certificate +``` + +How a server consumes these files is described in the Pool and JDC READMEs under "Server keys". diff --git a/stratum-apps/src/bin/sv2-certificate.rs b/stratum-apps/src/bin/sv2-certificate.rs new file mode 100644 index 000000000..226019b5f --- /dev/null +++ b/stratum-apps/src/bin/sv2-certificate.rs @@ -0,0 +1,309 @@ +//! Issues the static key and certificate an Sv2 Noise server presents to its clients. +//! +//! Run it where the authority private key is kept, never on the server: the server only needs +//! the static private key and the certificate this tool writes, and the authority public key to +//! check them against. +//! +//! ```sh +//! cargo run --features cli --bin sv2-certificate -- keygen +//! SV2_AUTHORITY_SECRET_KEY= cargo run --features cli --bin sv2-certificate -- \ +//! issue-certificate --valid-for 93600 --toml /etc/sv2/key_2.toml --env /etc/sv2/key_2.env \ +//! --env-prefix POOL +//! cargo run --features cli --bin sv2-certificate -- inspect-certificate +//! ``` + +use std::{ + io::Write, + path::{Path, PathBuf}, + process::ExitCode, + time::{SystemTime, UNIX_EPOCH}, +}; + +use clap::{Parser, Subcommand}; +use stratum_apps::key_utils::{Certificate, Secp256k1PublicKey, Secp256k1SecretKey}; + +#[derive(Parser)] +#[command( + about = "Issue the static key and certificate an Sv2 Noise server presents", + long_about = "Run this where the authority private key is kept, not on the server. The \ + server needs only the static private key and the certificate written here, \ + plus the authority public key to check them against." +)] +struct Args { + #[command(subcommand)] + command: Command, +} + +#[derive(Subcommand)] +enum Command { + /// Generate a keypair: an authority key to keep offline, or a static key for a server. + Keygen, + /// Issue a certificate for a static key, generating the static key unless one is given. + IssueCertificate { + /// The authority's secret key (base58check), which signs the certificate. Prefer the + /// environment variable: a flag lands in the shell history and in `ps` output. + // Kept as a string and parsed in `run`: clap echoes a value it fails to parse, and a + // secret with one mistyped character is still a secret. + #[arg(long, env = "SV2_AUTHORITY_SECRET_KEY", hide_env_values = true)] + authority_secret_key: String, + /// Static private key to certify (base58check). A fresh one is generated when absent. + // A string for the same reason as the authority secret key. + #[arg(long)] + static_private_key: Option, + /// Start of the validity window, unix time. Defaults to now. Set it before the moment + /// the key goes live so the certificate is already valid then. + #[arg(long)] + valid_from: Option, + /// Length of the validity window in seconds, from valid_from. Make it outlast the next + /// rotation by a margin so a late rotation does not break handshakes. + #[arg(long, value_parser = clap::value_parser!(u32).range(1..))] + valid_for: u32, + /// Write the result as the TOML file a server's `active_static_key` points at; the name + /// must end in `.toml`. + #[arg(long, value_parser = path_with_extension("toml"))] + toml: Option, + /// Write the result as a `.env` file of `__*` variables; the name must end in + /// `.env`. Needs --env-prefix. + #[arg(long, requires = "env_prefix", value_parser = path_with_extension("env"))] + env: Option, + /// Variable prefix for --env: the application's, e.g. POOL or JDC. + #[arg(long, requires = "env", value_parser = clap::builder::NonEmptyStringValueParser::new())] + env_prefix: Option, + }, + /// Show a certificate's version and validity window. + InspectCertificate { + /// The certificate (base58check). + certificate: Certificate, + }, +} + +fn main() -> ExitCode { + match run(Args::parse()) { + Ok(()) => ExitCode::SUCCESS, + Err(e) => { + eprintln!("error: {e}"); + ExitCode::FAILURE + } + } +} + +fn run(args: Args) -> Result<(), String> { + match args.command { + Command::Keygen => { + let secret = fresh_secret_key(); + println!("secret_key = \"{secret}\""); + println!("public_key = \"{}\"", Secp256k1PublicKey::from(secret)); + Ok(()) + } + Command::IssueCertificate { + authority_secret_key, + static_private_key, + valid_from, + valid_for, + toml, + env, + env_prefix, + } => { + // Flat errors: the parse error quotes checksums computed from the typed value. + let authority_secret_key: Secp256k1SecretKey = authority_secret_key + .parse() + .map_err(|_| "authority secret key: not a valid base58check secret key")?; + let static_private_key = match static_private_key { + Some(raw) => raw + .parse() + .map_err(|_| "static private key: not a valid base58check secret key")?, + None => fresh_secret_key(), + }; + let static_public_key = Secp256k1PublicKey::from(static_private_key); + let authority_public_key = Secp256k1PublicKey::from(authority_secret_key); + let valid_from = valid_from.unwrap_or_else(now); + let not_valid_after = valid_from + .checked_add(valid_for) + .ok_or("valid_from + valid_for does not fit a u32 unix time")?; + let certificate = Certificate::sign( + &static_public_key, + &authority_secret_key, + valid_from, + not_valid_after, + ); + + let (from, until) = (when(valid_from), when(not_valid_after)); + let mut outputs = Vec::new(); + if let Some(path) = &toml { + outputs.push(( + path, + format!( + "# Static key and certificate for an Sv2 Noise server, valid from \ + {from} until {until}.\n# Point the \ + server's `active_static_key` at this file (through a symlink, so a \ + rotation is one atomic rename),\n# or copy the values into its \ + configuration.\nstatic_private_key = \"{static_private_key}\"\n\ + certificate = \"{certificate}\"\nauthority_public_key = \ + \"{authority_public_key}\"\n" + ), + )); + } + if let (Some(path), Some(prefix)) = (&env, &env_prefix) { + let prefix = prefix.to_uppercase(); + outputs.push(( + path, + format!( + "# Static key and certificate for an Sv2 Noise server, valid from \ + {from} until {until}.\n\ + {prefix}__STATIC_PRIVATE_KEY={static_private_key}\n\ + {prefix}__CERTIFICATE={certificate}\n\ + {prefix}__AUTHORITY_PUBLIC_KEY={authority_public_key}\n" + ), + )); + } + write_secret_files(&outputs)?; + // Reported only once everything succeeded, so a failure is the whole output. + println!("# certificate for static public key {static_public_key}"); + println!("# valid from {from} until {until}"); + println!("# signed by authority public key {authority_public_key}"); + for (path, _) in &outputs { + println!("# wrote {}", path.display()); + } + if outputs.is_empty() { + println!("static_private_key = \"{static_private_key}\""); + println!("certificate = \"{certificate}\""); + println!("authority_public_key = \"{authority_public_key}\""); + } + Ok(()) + } + Command::InspectCertificate { certificate } => { + let (valid_from, not_valid_after) = + (certificate.valid_from(), certificate.not_valid_after()); + println!("version = {}", certificate.version()); + println!("valid_from = {valid_from} # {}", date(valid_from)); + println!( + "not_valid_after = {not_valid_after} # {}", + date(not_valid_after) + ); + // Only the version and the validity window, clock leeway included: the signature + // cannot be checked without the static and authority public keys. + let now = now(); + match certificate.check_validity(now) { + Ok(()) => println!( + "# within its validity window, expires in {} seconds; signature not verified", + not_valid_after.saturating_sub(now) + ), + Err(e) => println!("# rejected now: {e}"), + } + Ok(()) + } + } +} + +// The two output files look alike inside, so the name is what tells an operator which is which. +fn path_with_extension( + extension: &'static str, +) -> impl Fn(&str) -> Result + Clone { + move |raw| { + let path = PathBuf::from(raw); + if path.extension().is_some_and(|e| e == extension) { + Ok(path) + } else { + Err(format!("the file name must end in .{extension}")) + } + } +} + +// A unix time as a UTC date, for humans; the config fields keep the number. +fn date(unix: u32) -> String { + chrono::DateTime::from_timestamp(unix.into(), 0) + .map(|t| t.format("%Y-%m-%d %H:%M:%S UTC").to_string()) + .unwrap_or_default() +} + +fn when(unix: u32) -> String { + format!("{unix} ({})", date(unix)) +} + +fn fresh_secret_key() -> Secp256k1SecretKey { + Secp256k1SecretKey(secp256k1::SecretKey::new(&mut rand::thread_rng())) +} + +fn now() -> u32 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|d| d.as_secs() as u32) + .unwrap_or_default() +} + +// The file holds a private key, so it is created readable by its owner only and never +// overwrites an existing file: a rotation writes a new file and moves a symlink. +// Writes every output or none: when one cannot be created or written, the ones this call +// already created are removed. `create_secret_file` only opens a name that did not exist, so +// that never removes a file that was there before. +fn write_secret_files(outputs: &[(&PathBuf, String)]) -> Result<(), String> { + let mut created = Vec::new(); + let result = outputs.iter().try_for_each(|(path, contents)| { + let mut file = create_secret_file(path)?; + created.push(path); + file.write_all(contents.as_bytes()) + .map_err(|e| format!("cannot write {}: {e}", path.display())) + }); + result.map_err(|mut error| { + for path in created { + if let Err(e) = std::fs::remove_file(path) { + error.push_str(&format!("; could not remove {}: {e}", path.display())); + } + } + error + }) +} + +fn create_secret_file(path: &Path) -> Result { + let mut options = std::fs::OpenOptions::new(); + options.write(true).create_new(true); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + options.mode(0o600); + } + options + .open(path) + .map_err(|e| format!("cannot create {}: {e}", path.display())) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn output_paths_must_carry_their_extension() { + assert!(path_with_extension("toml")("/etc/sv2/key_2.toml").is_ok()); + assert!(path_with_extension("env")("key_2.env").is_ok()); + assert!(path_with_extension("env")("key_2.toml").is_err()); + assert!(path_with_extension("toml")("test").is_err()); + assert!(path_with_extension("env")(".env").is_err()); + } + + #[test] + fn a_failed_output_leaves_no_new_file_and_keeps_existing_ones() { + let dir = std::env::temp_dir().join(format!("sv2-certificate-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir(&dir).unwrap(); + let (toml, env) = (dir.join("key.toml"), dir.join("key.env")); + std::fs::write(&env, "existing").unwrap(); + + let outputs = [(&toml, "new".to_string()), (&env, "new".to_string())]; + assert!(write_secret_files(&outputs).is_err()); + + assert!(!toml.exists()); + assert_eq!(std::fs::read_to_string(&env).unwrap(), "existing"); + + std::fs::remove_file(&env).unwrap(); + assert!(write_secret_files(&outputs).is_ok()); + assert_eq!(std::fs::read_to_string(&toml).unwrap(), "new"); + assert_eq!(std::fs::read_to_string(&env).unwrap(), "new"); + std::fs::remove_dir_all(&dir).unwrap(); + } + + #[test] + fn dates_are_utc_and_cover_the_whole_u32_range() { + assert_eq!(date(0), "1970-01-01 00:00:00 UTC"); + assert_eq!(date(u32::MAX), "2106-02-07 06:28:15 UTC"); + } +} From 6208f8383bce7bf610c7fb1ad670eb274181c2ea Mon Sep 17 00:00:00 2001 From: plebhash Date: Mon, 9 Nov 2026 13:16:59 -0300 Subject: [PATCH 7/9] docs: ship a throwaway certificate in the example configs Every config example and env file carried the shared test authority secret key next to the server's listen address, and the servers no longer accept it. Give them instead a throwaway static key and the certificate the development authority issued for it, valid until the year 2106, the end of the certificate's 32-bit clock, so they still start out of the box, and say where the keys are set that this proves nothing to anyone: that authority's secret key is public. Name the file alternative re-read per handshake and the tool that issues real certificates, and give the Pool and JDC READMEs a "Server keys" section with the rotation workflow. ref https://github.com/stratum-mining/stratum/issues/2437 --- docker/docker_env.example | 17 ++++-- miner-apps/jd-client/README.md | 57 +++++++++++++++++- ...bitcoin-core-ipc-hosted-infra-example.toml | 19 +++++- ...-bitcoin-core-ipc-local-infra-example.toml | 19 +++++- .../jdc-config-hosted-infra-example.toml | 19 +++++- .../jdc-config-local-infra-example.toml | 19 +++++- .../jdc-config-solo-mining-example.toml | 19 +++++- ...-bitcoin-core-ipc-local-infra-example.toml | 19 +++++- .../jdc-config-local-infra-example.toml | 19 +++++- ...bitcoin-core-ipc-hosted-infra-example.toml | 19 +++++- ...-bitcoin-core-ipc-local-infra-example.toml | 19 +++++- .../jdc-config-hosted-infra-example.toml | 19 +++++- .../jdc-config-local-infra-example.toml | 19 +++++- pool-apps/pool/README.md | 58 ++++++++++++++++++- .../pool-config-bitcoin-core-ipc-example.toml | 21 ++++++- .../pool-config-hosted-sv2-tp-example.toml | 19 +++++- .../pool-config-local-sv2-tp-example.toml | 19 +++++- ...l-jds-config-bitcoin-core-ipc-example.toml | 21 ++++++- .../pool-config-bitcoin-core-ipc-example.toml | 21 ++++++- .../pool-config-local-sv2-tp-example.toml | 19 +++++- ...l-jds-config-bitcoin-core-ipc-example.toml | 21 ++++++- .../pool-config-bitcoin-core-ipc-example.toml | 21 ++++++- .../pool-config-hosted-sv2-tp-example.toml | 19 +++++- .../pool-config-local-sv2-tp-example.toml | 19 +++++- ...l-jds-config-bitcoin-core-ipc-example.toml | 21 ++++++- 25 files changed, 505 insertions(+), 57 deletions(-) diff --git a/docker/docker_env.example b/docker/docker_env.example index 31c71e3cf..e522a6b74 100644 --- a/docker/docker_env.example +++ b/docker/docker_env.example @@ -24,9 +24,15 @@ BITCOIN_SOCKET_PATH=/absolute/path/to/your/node.sock # Pool (pool_sv2) # ----------------------------------------------------------------------------- POOL__LISTEN_ADDRESS=0.0.0.0:3333 +# A throwaway static key and a certificate for it from the development authority, whose secret +# key is public: for trying the stack only. In production replace these three with the output of +# `sv2-certificate issue-certificate --valid-for --env --env-prefix POOL`, run where the +# authority secret key is kept (see pool-apps/pool/README.md, "Server keys"). To use a key file +# re-read per handshake instead, drop these two and set POOL__ACTIVE_STATIC_KEY=: while they +# are set, they are used and the file is ignored. +POOL__STATIC_PRIVATE_KEY=2Zdzjqd9c7EB4C9FBuqyDNzErruL4DNrJHoL5jhdE6QVArUTR8 +POOL__CERTIFICATE=11HpWbvGUzBwSTTVZMX6Dc1bVAupxFfvzkFqWfcQzXwVWWeCFQ6rQTDtrNbv4ncSx11gBb1trRbuhuCuXNptqbQBHnyx4VJKULV9e4AWew POOL__AUTHORITY_PUBLIC_KEY=9auqWEzQDVyd2oe1JVGFLMLHZtCo2FFqZwtKA5gd9xbuEu7PH72 -POOL__AUTHORITY_SECRET_KEY=mkDLTBBRxdBv998612qipDYoTK3YUrqLe8uWw7gu3iXbSrn2n -POOL__CERT_VALIDITY_SEC=3600 POOL__COINBASE_REWARD_SCRIPT=addr(tb1qa0sm0hxzj0x25rh8gw5xlzwlsfvvyz8u96w3p8) POOL__SERVER_ID=1 POOL__POOL_SIGNATURE=Stratum V2 SRI Pool @@ -52,9 +58,12 @@ POOL__JDS__LISTEN_ADDRESS=0.0.0.0:3334 JDC__LISTENING_ADDRESS=0.0.0.0:34265 JDC__MAX_SUPPORTED_VERSION=2 JDC__MIN_SUPPORTED_VERSION=2 +# The same throwaway key and certificate, and the same rules, as for the Pool above; in production use the output of +# `sv2-certificate issue-certificate --valid-for --env --env-prefix JDC` instead (see +# miner-apps/jd-client/README.md, "Server keys"). +JDC__STATIC_PRIVATE_KEY=2Zdzjqd9c7EB4C9FBuqyDNzErruL4DNrJHoL5jhdE6QVArUTR8 +JDC__CERTIFICATE=11HpWbvGUzBwSTTVZMX6Dc1bVAupxFfvzkFqWfcQzXwVWWeCFQ6rQTDtrNbv4ncSx11gBb1trRbuhuCuXNptqbQBHnyx4VJKULV9e4AWew JDC__AUTHORITY_PUBLIC_KEY=9auqWEzQDVyd2oe1JVGFLMLHZtCo2FFqZwtKA5gd9xbuEu7PH72 -JDC__AUTHORITY_SECRET_KEY=mkDLTBBRxdBv998612qipDYoTK3YUrqLe8uWw7gu3iXbSrn2n -JDC__CERT_VALIDITY_SEC=3600 JDC__SHARES_PER_MINUTE=6.0 JDC__SHARE_BATCH_SIZE=10 JDC__MODE=FULLTEMPLATE diff --git a/miner-apps/jd-client/README.md b/miner-apps/jd-client/README.md index 93016cc19..45e5ed24f 100644 --- a/miner-apps/jd-client/README.md +++ b/miner-apps/jd-client/README.md @@ -71,7 +71,7 @@ The configuration file contains the following information: 1. The downstream socket information, which includes the listening IP address (`downstream_address`) and port (`downstream_port`). 2. The maximum and minimum protocol versions (`max_supported_version` and `min_supported_version`) with size as (`min_extranonce2_size`) -3. The authentication keys used for the downstream connections (`authority_public_key`, `authority_secret_key`) +3. The keys JDC presents to downstreams in the Noise handshake, see [Server keys](#server-keys). 4. The `template_provider_type` section, which determines how the pool obtains block templates. There are two options: - `[template_provider_type.Sv2Tp]` - Connects to an SV2 Template Provider, with the following parameters: - `address` - The Template Provider's network address @@ -182,6 +182,57 @@ JDC negotiates protocol extensions on both of its sides, with a pair of settings All four are empty by default. +### Server keys + +A downstream verifies the JDC by the authority public key it pins (`authority_pubkey` in its +upstream config). The JDC proves it holds that identity with a certificate over its static key, +issued where the authority secret key is kept: the JDC host never sees that key. It gets the +certificate in one of two ways: + +- `static_private_key` and `certificate` in its configuration, loaded once at startup. +- `active_static_key` pointing at a TOML file holding the same fields. The file is read before + every handshake, so replacing it (or the symlink it is) rotates the static key without a restart + and without disturbing open connections. + +An optional `authority_public_key` makes the JDC check the certificate against it at startup and +before every handshake, so a wrong file fails with a reason. For the file, an +`authority_public_key` inside the file is checked as well. + +Precedence. Each of these fields can come from the TOML file or from the environment +(`JDC__STATIC_PRIVATE_KEY`, `JDC__CERTIFICATE`, `JDC__ACTIVE_STATIC_KEY`, +`JDC__AUTHORITY_PUBLIC_KEY`), and the environment overrides the TOML field by field, as for +every other setting. On the merged result: + +1. `static_private_key` and `certificate` set: they are used, and `active_static_key` is ignored. +2. Otherwise `active_static_key` set: the file is used. +3. Neither: the JDC refuses to start. + +So an inline pair in the TOML still wins over `JDC__ACTIVE_STATIC_KEY` from the environment: +the environment overrides fields, not the choice between inline and file. To use the file, leave the +inline pair unset in both places. Half an inline pair, and `authority_secret_key` or +`cert_validity_sec` anywhere, are refused with a reason. + +The example configs ship a throwaway static key with a certificate from the development authority +`9auqWEzQDVyd2oe1JVGFLMLHZtCo2FFqZwtKA5gd9xbuEu7PH72`, whose secret key is public, so they start out of the +box and prove nothing to anyone else. Issue your own on the machine that holds your authority +secret key with the `sv2-certificate` binary from `stratum-apps`: + +```bash +# once: an authority keypair; publish the public key, keep the secret key off every server +cargo run -p stratum-apps --features cli --bin sv2-certificate -- keygen +# per rotation: a fresh static key and a certificate over it, as the file `active_static_key` +# points at and/or as `JDC__*` environment variables. The authority secret key is read from +# SV2_AUTHORITY_SECRET_KEY; typed at a silent prompt it stays out of the shell history and of +# `ps` output +read -rs SV2_AUTHORITY_SECRET_KEY && export SV2_AUTHORITY_SECRET_KEY +cargo run -p stratum-apps --features cli --bin sv2-certificate -- issue-certificate --valid-for 93600 \ + --toml key_2.toml --env key_2.env --env-prefix JDC +cargo run -p stratum-apps --features cli --bin sv2-certificate -- inspect-certificate +``` + +Make a certificate valid from before the moment it goes live and until after the next rotation, +so a late rotation never breaks handshakes. + ### Environment Variables Every configuration value can also be supplied through the environment. Variables are prefixed @@ -194,6 +245,10 @@ source, JDC exits with an error. ```bash JDC__LISTENING_ADDRESS=0.0.0.0:34265 +# Server keys (see above); `sv2-certificate issue-certificate --env --env-prefix JDC` writes these three: +JDC__STATIC_PRIVATE_KEY=... +JDC__CERTIFICATE=... +JDC__AUTHORITY_PUBLIC_KEY=... # Tagged enums (template_provider_type) take the variant as a path segment, # matched case-insensitively. If the file selects a different variant, the # environment's variant replaces it; set only one variant in the environment: diff --git a/miner-apps/jd-client/config-examples/mainnet/jdc-config-bitcoin-core-ipc-hosted-infra-example.toml b/miner-apps/jd-client/config-examples/mainnet/jdc-config-bitcoin-core-ipc-hosted-infra-example.toml index 55486bfed..9a83e5eb2 100644 --- a/miner-apps/jd-client/config-examples/mainnet/jdc-config-bitcoin-core-ipc-hosted-infra-example.toml +++ b/miner-apps/jd-client/config-examples/mainnet/jdc-config-bitcoin-core-ipc-hosted-infra-example.toml @@ -6,9 +6,24 @@ max_supported_version = 2 min_supported_version = 2 # Auth keys for open encrypted connection downstream +# A throwaway static key and the certificate the development authority +# 9auqWEzQDVyd2oe1JVGFLMLHZtCo2FFqZwtKA5gd9xbuEu7PH72 issued for it, valid until the year 2106. +# That authority's secret key is public, so anyone can mint certificates for it: these are for +# trying the examples and for tests, and prove nothing to anyone else. For a real deployment keep +# your authority secret key on another machine, issue a certificate there with +# `sv2-certificate issue-certificate` (see "Server keys" in the README), and give this server only +# its static key and that certificate, either inline as below or through a file read before every +# handshake, so replacing it (or the symlink it is) rotates the key without a restart: +# +# active_static_key = "/etc/sv2/active_static_key.toml" +# +# To use the file, leave static_private_key and certificate unset, both here and in the environment: +# when that pair is set, it is used and the file is ignored. The full precedence is under +# "Server keys" in the README. +static_private_key = "2Zdzjqd9c7EB4C9FBuqyDNzErruL4DNrJHoL5jhdE6QVArUTR8" +certificate = "11HpWbvGUzBwSTTVZMX6Dc1bVAupxFfvzkFqWfcQzXwVWWeCFQ6rQTDtrNbv4ncSx11gBb1trRbuhuCuXNptqbQBHnyx4VJKULV9e4AWew" +# Optional: the certificate is checked against it at startup and before every handshake. authority_public_key = "9auqWEzQDVyd2oe1JVGFLMLHZtCo2FFqZwtKA5gd9xbuEu7PH72" -authority_secret_key = "mkDLTBBRxdBv998612qipDYoTK3YUrqLe8uWw7gu3iXbSrn2n" -cert_validity_sec = 3600 # How many shares we expect to receive in a minute (determines difficulty targets) shares_per_minute = 6.0 diff --git a/miner-apps/jd-client/config-examples/mainnet/jdc-config-bitcoin-core-ipc-local-infra-example.toml b/miner-apps/jd-client/config-examples/mainnet/jdc-config-bitcoin-core-ipc-local-infra-example.toml index 84ff1db1d..eb46be0ee 100644 --- a/miner-apps/jd-client/config-examples/mainnet/jdc-config-bitcoin-core-ipc-local-infra-example.toml +++ b/miner-apps/jd-client/config-examples/mainnet/jdc-config-bitcoin-core-ipc-local-infra-example.toml @@ -6,9 +6,24 @@ max_supported_version = 2 min_supported_version = 2 # Auth keys for open encrypted connection downstream +# A throwaway static key and the certificate the development authority +# 9auqWEzQDVyd2oe1JVGFLMLHZtCo2FFqZwtKA5gd9xbuEu7PH72 issued for it, valid until the year 2106. +# That authority's secret key is public, so anyone can mint certificates for it: these are for +# trying the examples and for tests, and prove nothing to anyone else. For a real deployment keep +# your authority secret key on another machine, issue a certificate there with +# `sv2-certificate issue-certificate` (see "Server keys" in the README), and give this server only +# its static key and that certificate, either inline as below or through a file read before every +# handshake, so replacing it (or the symlink it is) rotates the key without a restart: +# +# active_static_key = "/etc/sv2/active_static_key.toml" +# +# To use the file, leave static_private_key and certificate unset, both here and in the environment: +# when that pair is set, it is used and the file is ignored. The full precedence is under +# "Server keys" in the README. +static_private_key = "2Zdzjqd9c7EB4C9FBuqyDNzErruL4DNrJHoL5jhdE6QVArUTR8" +certificate = "11HpWbvGUzBwSTTVZMX6Dc1bVAupxFfvzkFqWfcQzXwVWWeCFQ6rQTDtrNbv4ncSx11gBb1trRbuhuCuXNptqbQBHnyx4VJKULV9e4AWew" +# Optional: the certificate is checked against it at startup and before every handshake. authority_public_key = "9auqWEzQDVyd2oe1JVGFLMLHZtCo2FFqZwtKA5gd9xbuEu7PH72" -authority_secret_key = "mkDLTBBRxdBv998612qipDYoTK3YUrqLe8uWw7gu3iXbSrn2n" -cert_validity_sec = 3600 # How many shares we expect to receive in a minute (determines difficulty targets) shares_per_minute = 6.0 diff --git a/miner-apps/jd-client/config-examples/mainnet/jdc-config-hosted-infra-example.toml b/miner-apps/jd-client/config-examples/mainnet/jdc-config-hosted-infra-example.toml index 97eab0ce6..619c9ee38 100644 --- a/miner-apps/jd-client/config-examples/mainnet/jdc-config-hosted-infra-example.toml +++ b/miner-apps/jd-client/config-examples/mainnet/jdc-config-hosted-infra-example.toml @@ -6,9 +6,24 @@ max_supported_version = 2 min_supported_version = 2 # Auth keys for open encrypted connection downstream +# A throwaway static key and the certificate the development authority +# 9auqWEzQDVyd2oe1JVGFLMLHZtCo2FFqZwtKA5gd9xbuEu7PH72 issued for it, valid until the year 2106. +# That authority's secret key is public, so anyone can mint certificates for it: these are for +# trying the examples and for tests, and prove nothing to anyone else. For a real deployment keep +# your authority secret key on another machine, issue a certificate there with +# `sv2-certificate issue-certificate` (see "Server keys" in the README), and give this server only +# its static key and that certificate, either inline as below or through a file read before every +# handshake, so replacing it (or the symlink it is) rotates the key without a restart: +# +# active_static_key = "/etc/sv2/active_static_key.toml" +# +# To use the file, leave static_private_key and certificate unset, both here and in the environment: +# when that pair is set, it is used and the file is ignored. The full precedence is under +# "Server keys" in the README. +static_private_key = "2Zdzjqd9c7EB4C9FBuqyDNzErruL4DNrJHoL5jhdE6QVArUTR8" +certificate = "11HpWbvGUzBwSTTVZMX6Dc1bVAupxFfvzkFqWfcQzXwVWWeCFQ6rQTDtrNbv4ncSx11gBb1trRbuhuCuXNptqbQBHnyx4VJKULV9e4AWew" +# Optional: the certificate is checked against it at startup and before every handshake. authority_public_key = "9auqWEzQDVyd2oe1JVGFLMLHZtCo2FFqZwtKA5gd9xbuEu7PH72" -authority_secret_key = "mkDLTBBRxdBv998612qipDYoTK3YUrqLe8uWw7gu3iXbSrn2n" -cert_validity_sec = 3600 # How many shares we expect to receive in a minute (determines difficulty targets) shares_per_minute = 6.0 diff --git a/miner-apps/jd-client/config-examples/mainnet/jdc-config-local-infra-example.toml b/miner-apps/jd-client/config-examples/mainnet/jdc-config-local-infra-example.toml index 7cc77f796..b284e8b4f 100644 --- a/miner-apps/jd-client/config-examples/mainnet/jdc-config-local-infra-example.toml +++ b/miner-apps/jd-client/config-examples/mainnet/jdc-config-local-infra-example.toml @@ -6,9 +6,24 @@ max_supported_version = 2 min_supported_version = 2 # Auth keys for open encrypted connection downstream +# A throwaway static key and the certificate the development authority +# 9auqWEzQDVyd2oe1JVGFLMLHZtCo2FFqZwtKA5gd9xbuEu7PH72 issued for it, valid until the year 2106. +# That authority's secret key is public, so anyone can mint certificates for it: these are for +# trying the examples and for tests, and prove nothing to anyone else. For a real deployment keep +# your authority secret key on another machine, issue a certificate there with +# `sv2-certificate issue-certificate` (see "Server keys" in the README), and give this server only +# its static key and that certificate, either inline as below or through a file read before every +# handshake, so replacing it (or the symlink it is) rotates the key without a restart: +# +# active_static_key = "/etc/sv2/active_static_key.toml" +# +# To use the file, leave static_private_key and certificate unset, both here and in the environment: +# when that pair is set, it is used and the file is ignored. The full precedence is under +# "Server keys" in the README. +static_private_key = "2Zdzjqd9c7EB4C9FBuqyDNzErruL4DNrJHoL5jhdE6QVArUTR8" +certificate = "11HpWbvGUzBwSTTVZMX6Dc1bVAupxFfvzkFqWfcQzXwVWWeCFQ6rQTDtrNbv4ncSx11gBb1trRbuhuCuXNptqbQBHnyx4VJKULV9e4AWew" +# Optional: the certificate is checked against it at startup and before every handshake. authority_public_key = "9auqWEzQDVyd2oe1JVGFLMLHZtCo2FFqZwtKA5gd9xbuEu7PH72" -authority_secret_key = "mkDLTBBRxdBv998612qipDYoTK3YUrqLe8uWw7gu3iXbSrn2n" -cert_validity_sec = 3600 # How many shares we expect to receive in a minute (determines difficulty targets) shares_per_minute = 6.0 diff --git a/miner-apps/jd-client/config-examples/mainnet/jdc-config-solo-mining-example.toml b/miner-apps/jd-client/config-examples/mainnet/jdc-config-solo-mining-example.toml index 1a75a1385..316ebe880 100644 --- a/miner-apps/jd-client/config-examples/mainnet/jdc-config-solo-mining-example.toml +++ b/miner-apps/jd-client/config-examples/mainnet/jdc-config-solo-mining-example.toml @@ -11,9 +11,24 @@ max_supported_version = 2 min_supported_version = 2 # Auth keys for open encrypted connection downstream +# A throwaway static key and the certificate the development authority +# 9auqWEzQDVyd2oe1JVGFLMLHZtCo2FFqZwtKA5gd9xbuEu7PH72 issued for it, valid until the year 2106. +# That authority's secret key is public, so anyone can mint certificates for it: these are for +# trying the examples and for tests, and prove nothing to anyone else. For a real deployment keep +# your authority secret key on another machine, issue a certificate there with +# `sv2-certificate issue-certificate` (see "Server keys" in the README), and give this server only +# its static key and that certificate, either inline as below or through a file read before every +# handshake, so replacing it (or the symlink it is) rotates the key without a restart: +# +# active_static_key = "/etc/sv2/active_static_key.toml" +# +# To use the file, leave static_private_key and certificate unset, both here and in the environment: +# when that pair is set, it is used and the file is ignored. The full precedence is under +# "Server keys" in the README. +static_private_key = "2Zdzjqd9c7EB4C9FBuqyDNzErruL4DNrJHoL5jhdE6QVArUTR8" +certificate = "11HpWbvGUzBwSTTVZMX6Dc1bVAupxFfvzkFqWfcQzXwVWWeCFQ6rQTDtrNbv4ncSx11gBb1trRbuhuCuXNptqbQBHnyx4VJKULV9e4AWew" +# Optional: the certificate is checked against it at startup and before every handshake. authority_public_key = "9auqWEzQDVyd2oe1JVGFLMLHZtCo2FFqZwtKA5gd9xbuEu7PH72" -authority_secret_key = "mkDLTBBRxdBv998612qipDYoTK3YUrqLe8uWw7gu3iXbSrn2n" -cert_validity_sec = 3600 # How many shares we expect to receive in a minute (determines difficulty targets) shares_per_minute = 6.0 diff --git a/miner-apps/jd-client/config-examples/signet/jdc-config-bitcoin-core-ipc-local-infra-example.toml b/miner-apps/jd-client/config-examples/signet/jdc-config-bitcoin-core-ipc-local-infra-example.toml index 1fb8a0340..82ce03956 100644 --- a/miner-apps/jd-client/config-examples/signet/jdc-config-bitcoin-core-ipc-local-infra-example.toml +++ b/miner-apps/jd-client/config-examples/signet/jdc-config-bitcoin-core-ipc-local-infra-example.toml @@ -6,9 +6,24 @@ max_supported_version = 2 min_supported_version = 2 # Auth keys for open encrypted connection downstream +# A throwaway static key and the certificate the development authority +# 9auqWEzQDVyd2oe1JVGFLMLHZtCo2FFqZwtKA5gd9xbuEu7PH72 issued for it, valid until the year 2106. +# That authority's secret key is public, so anyone can mint certificates for it: these are for +# trying the examples and for tests, and prove nothing to anyone else. For a real deployment keep +# your authority secret key on another machine, issue a certificate there with +# `sv2-certificate issue-certificate` (see "Server keys" in the README), and give this server only +# its static key and that certificate, either inline as below or through a file read before every +# handshake, so replacing it (or the symlink it is) rotates the key without a restart: +# +# active_static_key = "/etc/sv2/active_static_key.toml" +# +# To use the file, leave static_private_key and certificate unset, both here and in the environment: +# when that pair is set, it is used and the file is ignored. The full precedence is under +# "Server keys" in the README. +static_private_key = "2Zdzjqd9c7EB4C9FBuqyDNzErruL4DNrJHoL5jhdE6QVArUTR8" +certificate = "11HpWbvGUzBwSTTVZMX6Dc1bVAupxFfvzkFqWfcQzXwVWWeCFQ6rQTDtrNbv4ncSx11gBb1trRbuhuCuXNptqbQBHnyx4VJKULV9e4AWew" +# Optional: the certificate is checked against it at startup and before every handshake. authority_public_key = "9auqWEzQDVyd2oe1JVGFLMLHZtCo2FFqZwtKA5gd9xbuEu7PH72" -authority_secret_key = "mkDLTBBRxdBv998612qipDYoTK3YUrqLe8uWw7gu3iXbSrn2n" -cert_validity_sec = 3600 # How many shares we expect to receive in a minute (determines difficulty targets) shares_per_minute = 6.0 diff --git a/miner-apps/jd-client/config-examples/signet/jdc-config-local-infra-example.toml b/miner-apps/jd-client/config-examples/signet/jdc-config-local-infra-example.toml index 9bbd8d34a..e75823994 100644 --- a/miner-apps/jd-client/config-examples/signet/jdc-config-local-infra-example.toml +++ b/miner-apps/jd-client/config-examples/signet/jdc-config-local-infra-example.toml @@ -6,9 +6,24 @@ max_supported_version = 2 min_supported_version = 2 # Auth keys for open encrypted connection downstream +# A throwaway static key and the certificate the development authority +# 9auqWEzQDVyd2oe1JVGFLMLHZtCo2FFqZwtKA5gd9xbuEu7PH72 issued for it, valid until the year 2106. +# That authority's secret key is public, so anyone can mint certificates for it: these are for +# trying the examples and for tests, and prove nothing to anyone else. For a real deployment keep +# your authority secret key on another machine, issue a certificate there with +# `sv2-certificate issue-certificate` (see "Server keys" in the README), and give this server only +# its static key and that certificate, either inline as below or through a file read before every +# handshake, so replacing it (or the symlink it is) rotates the key without a restart: +# +# active_static_key = "/etc/sv2/active_static_key.toml" +# +# To use the file, leave static_private_key and certificate unset, both here and in the environment: +# when that pair is set, it is used and the file is ignored. The full precedence is under +# "Server keys" in the README. +static_private_key = "2Zdzjqd9c7EB4C9FBuqyDNzErruL4DNrJHoL5jhdE6QVArUTR8" +certificate = "11HpWbvGUzBwSTTVZMX6Dc1bVAupxFfvzkFqWfcQzXwVWWeCFQ6rQTDtrNbv4ncSx11gBb1trRbuhuCuXNptqbQBHnyx4VJKULV9e4AWew" +# Optional: the certificate is checked against it at startup and before every handshake. authority_public_key = "9auqWEzQDVyd2oe1JVGFLMLHZtCo2FFqZwtKA5gd9xbuEu7PH72" -authority_secret_key = "mkDLTBBRxdBv998612qipDYoTK3YUrqLe8uWw7gu3iXbSrn2n" -cert_validity_sec = 3600 # How many shares we expect to receive in a minute (determines difficulty targets) shares_per_minute = 6.0 diff --git a/miner-apps/jd-client/config-examples/testnet4/jdc-config-bitcoin-core-ipc-hosted-infra-example.toml b/miner-apps/jd-client/config-examples/testnet4/jdc-config-bitcoin-core-ipc-hosted-infra-example.toml index 09974976b..008c71753 100644 --- a/miner-apps/jd-client/config-examples/testnet4/jdc-config-bitcoin-core-ipc-hosted-infra-example.toml +++ b/miner-apps/jd-client/config-examples/testnet4/jdc-config-bitcoin-core-ipc-hosted-infra-example.toml @@ -6,9 +6,24 @@ max_supported_version = 2 min_supported_version = 2 # Auth keys for open encrypted connection downstream +# A throwaway static key and the certificate the development authority +# 9auqWEzQDVyd2oe1JVGFLMLHZtCo2FFqZwtKA5gd9xbuEu7PH72 issued for it, valid until the year 2106. +# That authority's secret key is public, so anyone can mint certificates for it: these are for +# trying the examples and for tests, and prove nothing to anyone else. For a real deployment keep +# your authority secret key on another machine, issue a certificate there with +# `sv2-certificate issue-certificate` (see "Server keys" in the README), and give this server only +# its static key and that certificate, either inline as below or through a file read before every +# handshake, so replacing it (or the symlink it is) rotates the key without a restart: +# +# active_static_key = "/etc/sv2/active_static_key.toml" +# +# To use the file, leave static_private_key and certificate unset, both here and in the environment: +# when that pair is set, it is used and the file is ignored. The full precedence is under +# "Server keys" in the README. +static_private_key = "2Zdzjqd9c7EB4C9FBuqyDNzErruL4DNrJHoL5jhdE6QVArUTR8" +certificate = "11HpWbvGUzBwSTTVZMX6Dc1bVAupxFfvzkFqWfcQzXwVWWeCFQ6rQTDtrNbv4ncSx11gBb1trRbuhuCuXNptqbQBHnyx4VJKULV9e4AWew" +# Optional: the certificate is checked against it at startup and before every handshake. authority_public_key = "9auqWEzQDVyd2oe1JVGFLMLHZtCo2FFqZwtKA5gd9xbuEu7PH72" -authority_secret_key = "mkDLTBBRxdBv998612qipDYoTK3YUrqLe8uWw7gu3iXbSrn2n" -cert_validity_sec = 3600 # How many shares we expect to receive in a minute (determines difficulty targets) shares_per_minute = 6.0 diff --git a/miner-apps/jd-client/config-examples/testnet4/jdc-config-bitcoin-core-ipc-local-infra-example.toml b/miner-apps/jd-client/config-examples/testnet4/jdc-config-bitcoin-core-ipc-local-infra-example.toml index 3e99fa8cd..b739293ca 100644 --- a/miner-apps/jd-client/config-examples/testnet4/jdc-config-bitcoin-core-ipc-local-infra-example.toml +++ b/miner-apps/jd-client/config-examples/testnet4/jdc-config-bitcoin-core-ipc-local-infra-example.toml @@ -6,9 +6,24 @@ max_supported_version = 2 min_supported_version = 2 # Auth keys for open encrypted connection downstream +# A throwaway static key and the certificate the development authority +# 9auqWEzQDVyd2oe1JVGFLMLHZtCo2FFqZwtKA5gd9xbuEu7PH72 issued for it, valid until the year 2106. +# That authority's secret key is public, so anyone can mint certificates for it: these are for +# trying the examples and for tests, and prove nothing to anyone else. For a real deployment keep +# your authority secret key on another machine, issue a certificate there with +# `sv2-certificate issue-certificate` (see "Server keys" in the README), and give this server only +# its static key and that certificate, either inline as below or through a file read before every +# handshake, so replacing it (or the symlink it is) rotates the key without a restart: +# +# active_static_key = "/etc/sv2/active_static_key.toml" +# +# To use the file, leave static_private_key and certificate unset, both here and in the environment: +# when that pair is set, it is used and the file is ignored. The full precedence is under +# "Server keys" in the README. +static_private_key = "2Zdzjqd9c7EB4C9FBuqyDNzErruL4DNrJHoL5jhdE6QVArUTR8" +certificate = "11HpWbvGUzBwSTTVZMX6Dc1bVAupxFfvzkFqWfcQzXwVWWeCFQ6rQTDtrNbv4ncSx11gBb1trRbuhuCuXNptqbQBHnyx4VJKULV9e4AWew" +# Optional: the certificate is checked against it at startup and before every handshake. authority_public_key = "9auqWEzQDVyd2oe1JVGFLMLHZtCo2FFqZwtKA5gd9xbuEu7PH72" -authority_secret_key = "mkDLTBBRxdBv998612qipDYoTK3YUrqLe8uWw7gu3iXbSrn2n" -cert_validity_sec = 3600 # How many shares we expect to receive in a minute (determines difficulty targets) shares_per_minute = 6.0 diff --git a/miner-apps/jd-client/config-examples/testnet4/jdc-config-hosted-infra-example.toml b/miner-apps/jd-client/config-examples/testnet4/jdc-config-hosted-infra-example.toml index 261f1e5a4..4af3006e6 100644 --- a/miner-apps/jd-client/config-examples/testnet4/jdc-config-hosted-infra-example.toml +++ b/miner-apps/jd-client/config-examples/testnet4/jdc-config-hosted-infra-example.toml @@ -6,9 +6,24 @@ max_supported_version = 2 min_supported_version = 2 # Auth keys for open encrypted connection downstream +# A throwaway static key and the certificate the development authority +# 9auqWEzQDVyd2oe1JVGFLMLHZtCo2FFqZwtKA5gd9xbuEu7PH72 issued for it, valid until the year 2106. +# That authority's secret key is public, so anyone can mint certificates for it: these are for +# trying the examples and for tests, and prove nothing to anyone else. For a real deployment keep +# your authority secret key on another machine, issue a certificate there with +# `sv2-certificate issue-certificate` (see "Server keys" in the README), and give this server only +# its static key and that certificate, either inline as below or through a file read before every +# handshake, so replacing it (or the symlink it is) rotates the key without a restart: +# +# active_static_key = "/etc/sv2/active_static_key.toml" +# +# To use the file, leave static_private_key and certificate unset, both here and in the environment: +# when that pair is set, it is used and the file is ignored. The full precedence is under +# "Server keys" in the README. +static_private_key = "2Zdzjqd9c7EB4C9FBuqyDNzErruL4DNrJHoL5jhdE6QVArUTR8" +certificate = "11HpWbvGUzBwSTTVZMX6Dc1bVAupxFfvzkFqWfcQzXwVWWeCFQ6rQTDtrNbv4ncSx11gBb1trRbuhuCuXNptqbQBHnyx4VJKULV9e4AWew" +# Optional: the certificate is checked against it at startup and before every handshake. authority_public_key = "9auqWEzQDVyd2oe1JVGFLMLHZtCo2FFqZwtKA5gd9xbuEu7PH72" -authority_secret_key = "mkDLTBBRxdBv998612qipDYoTK3YUrqLe8uWw7gu3iXbSrn2n" -cert_validity_sec = 3600 # How many shares we expect to receive in a minute (determines difficulty targets) shares_per_minute = 6.0 diff --git a/miner-apps/jd-client/config-examples/testnet4/jdc-config-local-infra-example.toml b/miner-apps/jd-client/config-examples/testnet4/jdc-config-local-infra-example.toml index 95c0acb7e..ae5b25e64 100644 --- a/miner-apps/jd-client/config-examples/testnet4/jdc-config-local-infra-example.toml +++ b/miner-apps/jd-client/config-examples/testnet4/jdc-config-local-infra-example.toml @@ -6,9 +6,24 @@ max_supported_version = 2 min_supported_version = 2 # Auth keys for open encrypted connection downstream +# A throwaway static key and the certificate the development authority +# 9auqWEzQDVyd2oe1JVGFLMLHZtCo2FFqZwtKA5gd9xbuEu7PH72 issued for it, valid until the year 2106. +# That authority's secret key is public, so anyone can mint certificates for it: these are for +# trying the examples and for tests, and prove nothing to anyone else. For a real deployment keep +# your authority secret key on another machine, issue a certificate there with +# `sv2-certificate issue-certificate` (see "Server keys" in the README), and give this server only +# its static key and that certificate, either inline as below or through a file read before every +# handshake, so replacing it (or the symlink it is) rotates the key without a restart: +# +# active_static_key = "/etc/sv2/active_static_key.toml" +# +# To use the file, leave static_private_key and certificate unset, both here and in the environment: +# when that pair is set, it is used and the file is ignored. The full precedence is under +# "Server keys" in the README. +static_private_key = "2Zdzjqd9c7EB4C9FBuqyDNzErruL4DNrJHoL5jhdE6QVArUTR8" +certificate = "11HpWbvGUzBwSTTVZMX6Dc1bVAupxFfvzkFqWfcQzXwVWWeCFQ6rQTDtrNbv4ncSx11gBb1trRbuhuCuXNptqbQBHnyx4VJKULV9e4AWew" +# Optional: the certificate is checked against it at startup and before every handshake. authority_public_key = "9auqWEzQDVyd2oe1JVGFLMLHZtCo2FFqZwtKA5gd9xbuEu7PH72" -authority_secret_key = "mkDLTBBRxdBv998612qipDYoTK3YUrqLe8uWw7gu3iXbSrn2n" -cert_validity_sec = 3600 # How many shares we expect to receive in a minute (determines difficulty targets) shares_per_minute = 6.0 diff --git a/pool-apps/pool/README.md b/pool-apps/pool/README.md index ecd990bd8..5b3e017c1 100644 --- a/pool-apps/pool/README.md +++ b/pool-apps/pool/README.md @@ -49,8 +49,7 @@ There are three example configuration files demonstrating different template pro The configuration file contains the following information: -1. The SRI Pool information which includes the SRI Pool authority public key - (`authority_public_key`), the SRI Pool authority secret key (`authority_secret_key`). +1. The keys the Pool presents to downstreams in the Noise handshake, see [Server keys](#server-keys). 2. The address which it will use to listen to new connection from downstream roles (`listen_address`) 3. The coinbase reward script specified as a descriptor (`coinbase_reward_script`) 4. A string that serves as signature on the coinbase tx (`pool_signature`). @@ -73,6 +72,57 @@ For connections with a Sv2 Template Provider, you may want to verify that your T Make sure the machine running the Pool application has its clock synced with an NTP server. Certificate validation is time-sensitive, and even a small drift of a few seconds can trigger an `InvalidCertificate` error. +### Server keys + +A downstream verifies the Pool by the authority public key it pins (`authority_pubkey` in its +upstream config). The Pool proves it holds that identity with a certificate over its static key, +issued where the authority secret key is kept: the Pool host never sees that key. It gets the +certificate in one of two ways: + +- `static_private_key` and `certificate` in its configuration, loaded once at startup. +- `active_static_key` pointing at a TOML file holding the same fields. The file is read before + every handshake, so replacing it (or the symlink it is) rotates the static key without a restart + and without disturbing open connections. + +An optional `authority_public_key` makes the Pool check the certificate against it at startup and +before every handshake, so a wrong file fails with a reason. For the file, an +`authority_public_key` inside the file is checked as well. + +Precedence. Each of these fields can come from the TOML file or from the environment +(`POOL__STATIC_PRIVATE_KEY`, `POOL__CERTIFICATE`, `POOL__ACTIVE_STATIC_KEY`, +`POOL__AUTHORITY_PUBLIC_KEY`), and the environment overrides the TOML field by field, as for +every other setting. On the merged result: + +1. `static_private_key` and `certificate` set: they are used, and `active_static_key` is ignored. +2. Otherwise `active_static_key` set: the file is used. +3. Neither: the Pool refuses to start. + +So an inline pair in the TOML still wins over `POOL__ACTIVE_STATIC_KEY` from the environment: +the environment overrides fields, not the choice between inline and file. To use the file, leave the +inline pair unset in both places. Half an inline pair, and `authority_secret_key` or +`cert_validity_sec` anywhere, are refused with a reason. + +The example configs ship a throwaway static key with a certificate from the development authority +`9auqWEzQDVyd2oe1JVGFLMLHZtCo2FFqZwtKA5gd9xbuEu7PH72`, whose secret key is public, so they start out of the +box and prove nothing to anyone else. Issue your own on the machine that holds your authority +secret key with the `sv2-certificate` binary from `stratum-apps`: + +```bash +# once: an authority keypair; publish the public key, keep the secret key off every server +cargo run -p stratum-apps --features cli --bin sv2-certificate -- keygen +# per rotation: a fresh static key and a certificate over it, as the file `active_static_key` +# points at and/or as `POOL__*` environment variables. The authority secret key is read from +# SV2_AUTHORITY_SECRET_KEY; typed at a silent prompt it stays out of the shell history and of +# `ps` output +read -rs SV2_AUTHORITY_SECRET_KEY && export SV2_AUTHORITY_SECRET_KEY +cargo run -p stratum-apps --features cli --bin sv2-certificate -- issue-certificate --valid-for 93600 \ + --toml key_2.toml --env key_2.env --env-prefix POOL +cargo run -p stratum-apps --features cli --bin sv2-certificate -- inspect-certificate +``` + +Make a certificate valid from before the moment it goes live and until after the next rotation, +so a late rotation never breaks handshakes. + ### Environment Variables Every configuration value can also be supplied through the environment. Variables are prefixed @@ -85,6 +135,10 @@ neither source, the pool exits with an error. ```bash POOL__LISTEN_ADDRESS=0.0.0.0:3333 +# Server keys (see above); `sv2-certificate issue-certificate --env --env-prefix POOL` writes these three: +POOL__STATIC_PRIVATE_KEY=... +POOL__CERTIFICATE=... +POOL__AUTHORITY_PUBLIC_KEY=... # Nested fields join each level with `__`: POOL__JDS__LISTEN_ADDRESS=0.0.0.0:3334 # Tagged enums (template_provider_type) take the variant as a path segment, diff --git a/pool-apps/pool/config-examples/mainnet/pool-config-bitcoin-core-ipc-example.toml b/pool-apps/pool/config-examples/mainnet/pool-config-bitcoin-core-ipc-example.toml index f014fe4aa..0001a076c 100644 --- a/pool-apps/pool/config-examples/mainnet/pool-config-bitcoin-core-ipc-example.toml +++ b/pool-apps/pool/config-examples/mainnet/pool-config-bitcoin-core-ipc-example.toml @@ -1,7 +1,22 @@ # SRI Pool config +# A throwaway static key and the certificate the development authority +# 9auqWEzQDVyd2oe1JVGFLMLHZtCo2FFqZwtKA5gd9xbuEu7PH72 issued for it, valid until the year 2106. +# That authority's secret key is public, so anyone can mint certificates for it: these are for +# trying the examples and for tests, and prove nothing to anyone else. For a real deployment keep +# your authority secret key on another machine, issue a certificate there with +# `sv2-certificate issue-certificate` (see "Server keys" in the README), and give this server only +# its static key and that certificate, either inline as below or through a file read before every +# handshake, so replacing it (or the symlink it is) rotates the key without a restart: +# +# active_static_key = "/etc/sv2/active_static_key.toml" +# +# To use the file, leave static_private_key and certificate unset, both here and in the environment: +# when that pair is set, it is used and the file is ignored. The full precedence is under +# "Server keys" in the README. +static_private_key = "2Zdzjqd9c7EB4C9FBuqyDNzErruL4DNrJHoL5jhdE6QVArUTR8" +certificate = "11HpWbvGUzBwSTTVZMX6Dc1bVAupxFfvzkFqWfcQzXwVWWeCFQ6rQTDtrNbv4ncSx11gBb1trRbuhuCuXNptqbQBHnyx4VJKULV9e4AWew" +# Optional: the certificate is checked against it at startup and before every handshake. authority_public_key = "9auqWEzQDVyd2oe1JVGFLMLHZtCo2FFqZwtKA5gd9xbuEu7PH72" -authority_secret_key = "mkDLTBBRxdBv998612qipDYoTK3YUrqLe8uWw7gu3iXbSrn2n" -cert_validity_sec = 3600 listen_address = "0.0.0.0:3333" # Coinbase outputs are specified as descriptors. A full list of descriptors is available at @@ -52,7 +67,7 @@ min_interval = 5 # Optional: Embedded Job Declaration Server (JDS) # When enabled, Pool runs a JDS subserver that listens for JDP connections from JDC. # Requires template_provider_type = BitcoinCoreIpc (JDS backend is selected by Pool startup). -# Shared fields (authority keys, cert_validity, coinbase_reward_script) are inherited +# Shared fields (server keys, coinbase_reward_script) are inherited # from the Pool config above. # [jds] # listen_address = "0.0.0.0:34254" diff --git a/pool-apps/pool/config-examples/mainnet/pool-config-hosted-sv2-tp-example.toml b/pool-apps/pool/config-examples/mainnet/pool-config-hosted-sv2-tp-example.toml index 62a02c759..c3fa302a7 100644 --- a/pool-apps/pool/config-examples/mainnet/pool-config-hosted-sv2-tp-example.toml +++ b/pool-apps/pool/config-examples/mainnet/pool-config-hosted-sv2-tp-example.toml @@ -1,7 +1,22 @@ # SRI Pool config +# A throwaway static key and the certificate the development authority +# 9auqWEzQDVyd2oe1JVGFLMLHZtCo2FFqZwtKA5gd9xbuEu7PH72 issued for it, valid until the year 2106. +# That authority's secret key is public, so anyone can mint certificates for it: these are for +# trying the examples and for tests, and prove nothing to anyone else. For a real deployment keep +# your authority secret key on another machine, issue a certificate there with +# `sv2-certificate issue-certificate` (see "Server keys" in the README), and give this server only +# its static key and that certificate, either inline as below or through a file read before every +# handshake, so replacing it (or the symlink it is) rotates the key without a restart: +# +# active_static_key = "/etc/sv2/active_static_key.toml" +# +# To use the file, leave static_private_key and certificate unset, both here and in the environment: +# when that pair is set, it is used and the file is ignored. The full precedence is under +# "Server keys" in the README. +static_private_key = "2Zdzjqd9c7EB4C9FBuqyDNzErruL4DNrJHoL5jhdE6QVArUTR8" +certificate = "11HpWbvGUzBwSTTVZMX6Dc1bVAupxFfvzkFqWfcQzXwVWWeCFQ6rQTDtrNbv4ncSx11gBb1trRbuhuCuXNptqbQBHnyx4VJKULV9e4AWew" +# Optional: the certificate is checked against it at startup and before every handshake. authority_public_key = "9auqWEzQDVyd2oe1JVGFLMLHZtCo2FFqZwtKA5gd9xbuEu7PH72" -authority_secret_key = "mkDLTBBRxdBv998612qipDYoTK3YUrqLe8uWw7gu3iXbSrn2n" -cert_validity_sec = 3600 listen_address = "0.0.0.0:3333" # Coinbase outputs are specified as descriptors. A full list of descriptors is available at diff --git a/pool-apps/pool/config-examples/mainnet/pool-config-local-sv2-tp-example.toml b/pool-apps/pool/config-examples/mainnet/pool-config-local-sv2-tp-example.toml index 6f4b6750a..c20cd3357 100644 --- a/pool-apps/pool/config-examples/mainnet/pool-config-local-sv2-tp-example.toml +++ b/pool-apps/pool/config-examples/mainnet/pool-config-local-sv2-tp-example.toml @@ -1,7 +1,22 @@ # SRI Pool config +# A throwaway static key and the certificate the development authority +# 9auqWEzQDVyd2oe1JVGFLMLHZtCo2FFqZwtKA5gd9xbuEu7PH72 issued for it, valid until the year 2106. +# That authority's secret key is public, so anyone can mint certificates for it: these are for +# trying the examples and for tests, and prove nothing to anyone else. For a real deployment keep +# your authority secret key on another machine, issue a certificate there with +# `sv2-certificate issue-certificate` (see "Server keys" in the README), and give this server only +# its static key and that certificate, either inline as below or through a file read before every +# handshake, so replacing it (or the symlink it is) rotates the key without a restart: +# +# active_static_key = "/etc/sv2/active_static_key.toml" +# +# To use the file, leave static_private_key and certificate unset, both here and in the environment: +# when that pair is set, it is used and the file is ignored. The full precedence is under +# "Server keys" in the README. +static_private_key = "2Zdzjqd9c7EB4C9FBuqyDNzErruL4DNrJHoL5jhdE6QVArUTR8" +certificate = "11HpWbvGUzBwSTTVZMX6Dc1bVAupxFfvzkFqWfcQzXwVWWeCFQ6rQTDtrNbv4ncSx11gBb1trRbuhuCuXNptqbQBHnyx4VJKULV9e4AWew" +# Optional: the certificate is checked against it at startup and before every handshake. authority_public_key = "9auqWEzQDVyd2oe1JVGFLMLHZtCo2FFqZwtKA5gd9xbuEu7PH72" -authority_secret_key = "mkDLTBBRxdBv998612qipDYoTK3YUrqLe8uWw7gu3iXbSrn2n" -cert_validity_sec = 3600 listen_address = "0.0.0.0:3333" # Coinbase outputs are specified as descriptors. A full list of descriptors is available at diff --git a/pool-apps/pool/config-examples/mainnet/pool-jds-config-bitcoin-core-ipc-example.toml b/pool-apps/pool/config-examples/mainnet/pool-jds-config-bitcoin-core-ipc-example.toml index bb45cb5d5..c84e50e93 100644 --- a/pool-apps/pool/config-examples/mainnet/pool-jds-config-bitcoin-core-ipc-example.toml +++ b/pool-apps/pool/config-examples/mainnet/pool-jds-config-bitcoin-core-ipc-example.toml @@ -1,7 +1,22 @@ # SRI Pool config (with embedded Job Declaration Server) +# A throwaway static key and the certificate the development authority +# 9auqWEzQDVyd2oe1JVGFLMLHZtCo2FFqZwtKA5gd9xbuEu7PH72 issued for it, valid until the year 2106. +# That authority's secret key is public, so anyone can mint certificates for it: these are for +# trying the examples and for tests, and prove nothing to anyone else. For a real deployment keep +# your authority secret key on another machine, issue a certificate there with +# `sv2-certificate issue-certificate` (see "Server keys" in the README), and give this server only +# its static key and that certificate, either inline as below or through a file read before every +# handshake, so replacing it (or the symlink it is) rotates the key without a restart: +# +# active_static_key = "/etc/sv2/active_static_key.toml" +# +# To use the file, leave static_private_key and certificate unset, both here and in the environment: +# when that pair is set, it is used and the file is ignored. The full precedence is under +# "Server keys" in the README. +static_private_key = "2Zdzjqd9c7EB4C9FBuqyDNzErruL4DNrJHoL5jhdE6QVArUTR8" +certificate = "11HpWbvGUzBwSTTVZMX6Dc1bVAupxFfvzkFqWfcQzXwVWWeCFQ6rQTDtrNbv4ncSx11gBb1trRbuhuCuXNptqbQBHnyx4VJKULV9e4AWew" +# Optional: the certificate is checked against it at startup and before every handshake. authority_public_key = "9auqWEzQDVyd2oe1JVGFLMLHZtCo2FFqZwtKA5gd9xbuEu7PH72" -authority_secret_key = "mkDLTBBRxdBv998612qipDYoTK3YUrqLe8uWw7gu3iXbSrn2n" -cert_validity_sec = 3600 listen_address = "0.0.0.0:3333" # Coinbase outputs are specified as descriptors. A full list of descriptors is available at @@ -66,7 +81,7 @@ min_interval = 5 # Embedded Job Declaration Server (JDS) # Pool runs a JDS subserver that listens for JDP connections from JDC. # Requires template_provider_type = BitcoinCoreIpc (JDS backend is selected by Pool startup). -# Shared fields (authority keys, cert_validity, coinbase_reward_script) are inherited +# Shared fields (server keys, coinbase_reward_script) are inherited # from the Pool config above. [jds] listen_address = "0.0.0.0:3334" diff --git a/pool-apps/pool/config-examples/signet/pool-config-bitcoin-core-ipc-example.toml b/pool-apps/pool/config-examples/signet/pool-config-bitcoin-core-ipc-example.toml index 9eb1f3f95..dc9b8a880 100644 --- a/pool-apps/pool/config-examples/signet/pool-config-bitcoin-core-ipc-example.toml +++ b/pool-apps/pool/config-examples/signet/pool-config-bitcoin-core-ipc-example.toml @@ -1,7 +1,22 @@ # SRI Pool config +# A throwaway static key and the certificate the development authority +# 9auqWEzQDVyd2oe1JVGFLMLHZtCo2FFqZwtKA5gd9xbuEu7PH72 issued for it, valid until the year 2106. +# That authority's secret key is public, so anyone can mint certificates for it: these are for +# trying the examples and for tests, and prove nothing to anyone else. For a real deployment keep +# your authority secret key on another machine, issue a certificate there with +# `sv2-certificate issue-certificate` (see "Server keys" in the README), and give this server only +# its static key and that certificate, either inline as below or through a file read before every +# handshake, so replacing it (or the symlink it is) rotates the key without a restart: +# +# active_static_key = "/etc/sv2/active_static_key.toml" +# +# To use the file, leave static_private_key and certificate unset, both here and in the environment: +# when that pair is set, it is used and the file is ignored. The full precedence is under +# "Server keys" in the README. +static_private_key = "2Zdzjqd9c7EB4C9FBuqyDNzErruL4DNrJHoL5jhdE6QVArUTR8" +certificate = "11HpWbvGUzBwSTTVZMX6Dc1bVAupxFfvzkFqWfcQzXwVWWeCFQ6rQTDtrNbv4ncSx11gBb1trRbuhuCuXNptqbQBHnyx4VJKULV9e4AWew" +# Optional: the certificate is checked against it at startup and before every handshake. authority_public_key = "9auqWEzQDVyd2oe1JVGFLMLHZtCo2FFqZwtKA5gd9xbuEu7PH72" -authority_secret_key = "mkDLTBBRxdBv998612qipDYoTK3YUrqLe8uWw7gu3iXbSrn2n" -cert_validity_sec = 3600 listen_address = "0.0.0.0:33333" # Coinbase outputs are specified as descriptors. A full list of descriptors is available at @@ -50,7 +65,7 @@ min_interval = 5 # Optional: Embedded Job Declaration Server (JDS) # When enabled, Pool runs a JDS subserver that listens for JDP connections from JDC. # Requires template_provider_type = BitcoinCoreIpc (JDS backend is selected by Pool startup). -# Shared fields (authority keys, cert_validity, coinbase_reward_script) are inherited +# Shared fields (server keys, coinbase_reward_script) are inherited # from the Pool config above. # [jds] # listen_address = "0.0.0.0:34254" diff --git a/pool-apps/pool/config-examples/signet/pool-config-local-sv2-tp-example.toml b/pool-apps/pool/config-examples/signet/pool-config-local-sv2-tp-example.toml index 82abb3661..14c6ff393 100644 --- a/pool-apps/pool/config-examples/signet/pool-config-local-sv2-tp-example.toml +++ b/pool-apps/pool/config-examples/signet/pool-config-local-sv2-tp-example.toml @@ -1,7 +1,22 @@ # SRI Pool config +# A throwaway static key and the certificate the development authority +# 9auqWEzQDVyd2oe1JVGFLMLHZtCo2FFqZwtKA5gd9xbuEu7PH72 issued for it, valid until the year 2106. +# That authority's secret key is public, so anyone can mint certificates for it: these are for +# trying the examples and for tests, and prove nothing to anyone else. For a real deployment keep +# your authority secret key on another machine, issue a certificate there with +# `sv2-certificate issue-certificate` (see "Server keys" in the README), and give this server only +# its static key and that certificate, either inline as below or through a file read before every +# handshake, so replacing it (or the symlink it is) rotates the key without a restart: +# +# active_static_key = "/etc/sv2/active_static_key.toml" +# +# To use the file, leave static_private_key and certificate unset, both here and in the environment: +# when that pair is set, it is used and the file is ignored. The full precedence is under +# "Server keys" in the README. +static_private_key = "2Zdzjqd9c7EB4C9FBuqyDNzErruL4DNrJHoL5jhdE6QVArUTR8" +certificate = "11HpWbvGUzBwSTTVZMX6Dc1bVAupxFfvzkFqWfcQzXwVWWeCFQ6rQTDtrNbv4ncSx11gBb1trRbuhuCuXNptqbQBHnyx4VJKULV9e4AWew" +# Optional: the certificate is checked against it at startup and before every handshake. authority_public_key = "9auqWEzQDVyd2oe1JVGFLMLHZtCo2FFqZwtKA5gd9xbuEu7PH72" -authority_secret_key = "mkDLTBBRxdBv998612qipDYoTK3YUrqLe8uWw7gu3iXbSrn2n" -cert_validity_sec = 3600 listen_address = "0.0.0.0:33333" # Coinbase outputs are specified as descriptors. A full list of descriptors is available at diff --git a/pool-apps/pool/config-examples/signet/pool-jds-config-bitcoin-core-ipc-example.toml b/pool-apps/pool/config-examples/signet/pool-jds-config-bitcoin-core-ipc-example.toml index f1658495d..6afaf2282 100644 --- a/pool-apps/pool/config-examples/signet/pool-jds-config-bitcoin-core-ipc-example.toml +++ b/pool-apps/pool/config-examples/signet/pool-jds-config-bitcoin-core-ipc-example.toml @@ -1,7 +1,22 @@ # SRI Pool config (with embedded Job Declaration Server) +# A throwaway static key and the certificate the development authority +# 9auqWEzQDVyd2oe1JVGFLMLHZtCo2FFqZwtKA5gd9xbuEu7PH72 issued for it, valid until the year 2106. +# That authority's secret key is public, so anyone can mint certificates for it: these are for +# trying the examples and for tests, and prove nothing to anyone else. For a real deployment keep +# your authority secret key on another machine, issue a certificate there with +# `sv2-certificate issue-certificate` (see "Server keys" in the README), and give this server only +# its static key and that certificate, either inline as below or through a file read before every +# handshake, so replacing it (or the symlink it is) rotates the key without a restart: +# +# active_static_key = "/etc/sv2/active_static_key.toml" +# +# To use the file, leave static_private_key and certificate unset, both here and in the environment: +# when that pair is set, it is used and the file is ignored. The full precedence is under +# "Server keys" in the README. +static_private_key = "2Zdzjqd9c7EB4C9FBuqyDNzErruL4DNrJHoL5jhdE6QVArUTR8" +certificate = "11HpWbvGUzBwSTTVZMX6Dc1bVAupxFfvzkFqWfcQzXwVWWeCFQ6rQTDtrNbv4ncSx11gBb1trRbuhuCuXNptqbQBHnyx4VJKULV9e4AWew" +# Optional: the certificate is checked against it at startup and before every handshake. authority_public_key = "9auqWEzQDVyd2oe1JVGFLMLHZtCo2FFqZwtKA5gd9xbuEu7PH72" -authority_secret_key = "mkDLTBBRxdBv998612qipDYoTK3YUrqLe8uWw7gu3iXbSrn2n" -cert_validity_sec = 3600 listen_address = "0.0.0.0:33333" # Coinbase outputs are specified as descriptors. A full list of descriptors is available at @@ -64,7 +79,7 @@ min_interval = 5 # Embedded Job Declaration Server (JDS) # Pool runs a JDS subserver that listens for JDP connections from JDC. # Requires template_provider_type = BitcoinCoreIpc (JDS backend is selected by Pool startup). -# Shared fields (authority keys, cert_validity, coinbase_reward_script) are inherited +# Shared fields (server keys, coinbase_reward_script) are inherited # from the Pool config above. [jds] listen_address = "0.0.0.0:33334" diff --git a/pool-apps/pool/config-examples/testnet4/pool-config-bitcoin-core-ipc-example.toml b/pool-apps/pool/config-examples/testnet4/pool-config-bitcoin-core-ipc-example.toml index 7606bb568..84ca55ad8 100644 --- a/pool-apps/pool/config-examples/testnet4/pool-config-bitcoin-core-ipc-example.toml +++ b/pool-apps/pool/config-examples/testnet4/pool-config-bitcoin-core-ipc-example.toml @@ -1,7 +1,22 @@ # SRI Pool config +# A throwaway static key and the certificate the development authority +# 9auqWEzQDVyd2oe1JVGFLMLHZtCo2FFqZwtKA5gd9xbuEu7PH72 issued for it, valid until the year 2106. +# That authority's secret key is public, so anyone can mint certificates for it: these are for +# trying the examples and for tests, and prove nothing to anyone else. For a real deployment keep +# your authority secret key on another machine, issue a certificate there with +# `sv2-certificate issue-certificate` (see "Server keys" in the README), and give this server only +# its static key and that certificate, either inline as below or through a file read before every +# handshake, so replacing it (or the symlink it is) rotates the key without a restart: +# +# active_static_key = "/etc/sv2/active_static_key.toml" +# +# To use the file, leave static_private_key and certificate unset, both here and in the environment: +# when that pair is set, it is used and the file is ignored. The full precedence is under +# "Server keys" in the README. +static_private_key = "2Zdzjqd9c7EB4C9FBuqyDNzErruL4DNrJHoL5jhdE6QVArUTR8" +certificate = "11HpWbvGUzBwSTTVZMX6Dc1bVAupxFfvzkFqWfcQzXwVWWeCFQ6rQTDtrNbv4ncSx11gBb1trRbuhuCuXNptqbQBHnyx4VJKULV9e4AWew" +# Optional: the certificate is checked against it at startup and before every handshake. authority_public_key = "9auqWEzQDVyd2oe1JVGFLMLHZtCo2FFqZwtKA5gd9xbuEu7PH72" -authority_secret_key = "mkDLTBBRxdBv998612qipDYoTK3YUrqLe8uWw7gu3iXbSrn2n" -cert_validity_sec = 3600 listen_address = "0.0.0.0:43333" # Coinbase outputs are specified as descriptors. A full list of descriptors is available at @@ -51,7 +66,7 @@ min_interval = 5 # Optional: Embedded Job Declaration Server (JDS) # When enabled, Pool runs a JDS subserver that listens for JDP connections from JDC. # Requires template_provider_type = BitcoinCoreIpc (JDS backend is selected by Pool startup). -# Shared fields (authority keys, cert_validity, coinbase_reward_script) are inherited +# Shared fields (server keys, coinbase_reward_script) are inherited # from the Pool config above. # [jds] # listen_address = "0.0.0.0:34254" diff --git a/pool-apps/pool/config-examples/testnet4/pool-config-hosted-sv2-tp-example.toml b/pool-apps/pool/config-examples/testnet4/pool-config-hosted-sv2-tp-example.toml index 778c35bb3..deac4d86b 100644 --- a/pool-apps/pool/config-examples/testnet4/pool-config-hosted-sv2-tp-example.toml +++ b/pool-apps/pool/config-examples/testnet4/pool-config-hosted-sv2-tp-example.toml @@ -1,7 +1,22 @@ # SRI Pool config +# A throwaway static key and the certificate the development authority +# 9auqWEzQDVyd2oe1JVGFLMLHZtCo2FFqZwtKA5gd9xbuEu7PH72 issued for it, valid until the year 2106. +# That authority's secret key is public, so anyone can mint certificates for it: these are for +# trying the examples and for tests, and prove nothing to anyone else. For a real deployment keep +# your authority secret key on another machine, issue a certificate there with +# `sv2-certificate issue-certificate` (see "Server keys" in the README), and give this server only +# its static key and that certificate, either inline as below or through a file read before every +# handshake, so replacing it (or the symlink it is) rotates the key without a restart: +# +# active_static_key = "/etc/sv2/active_static_key.toml" +# +# To use the file, leave static_private_key and certificate unset, both here and in the environment: +# when that pair is set, it is used and the file is ignored. The full precedence is under +# "Server keys" in the README. +static_private_key = "2Zdzjqd9c7EB4C9FBuqyDNzErruL4DNrJHoL5jhdE6QVArUTR8" +certificate = "11HpWbvGUzBwSTTVZMX6Dc1bVAupxFfvzkFqWfcQzXwVWWeCFQ6rQTDtrNbv4ncSx11gBb1trRbuhuCuXNptqbQBHnyx4VJKULV9e4AWew" +# Optional: the certificate is checked against it at startup and before every handshake. authority_public_key = "9auqWEzQDVyd2oe1JVGFLMLHZtCo2FFqZwtKA5gd9xbuEu7PH72" -authority_secret_key = "mkDLTBBRxdBv998612qipDYoTK3YUrqLe8uWw7gu3iXbSrn2n" -cert_validity_sec = 3600 listen_address = "0.0.0.0:43333" # Coinbase outputs are specified as descriptors. A full list of descriptors is available at diff --git a/pool-apps/pool/config-examples/testnet4/pool-config-local-sv2-tp-example.toml b/pool-apps/pool/config-examples/testnet4/pool-config-local-sv2-tp-example.toml index 4f781eb5d..8091f1f37 100644 --- a/pool-apps/pool/config-examples/testnet4/pool-config-local-sv2-tp-example.toml +++ b/pool-apps/pool/config-examples/testnet4/pool-config-local-sv2-tp-example.toml @@ -1,7 +1,22 @@ # SRI Pool config +# A throwaway static key and the certificate the development authority +# 9auqWEzQDVyd2oe1JVGFLMLHZtCo2FFqZwtKA5gd9xbuEu7PH72 issued for it, valid until the year 2106. +# That authority's secret key is public, so anyone can mint certificates for it: these are for +# trying the examples and for tests, and prove nothing to anyone else. For a real deployment keep +# your authority secret key on another machine, issue a certificate there with +# `sv2-certificate issue-certificate` (see "Server keys" in the README), and give this server only +# its static key and that certificate, either inline as below or through a file read before every +# handshake, so replacing it (or the symlink it is) rotates the key without a restart: +# +# active_static_key = "/etc/sv2/active_static_key.toml" +# +# To use the file, leave static_private_key and certificate unset, both here and in the environment: +# when that pair is set, it is used and the file is ignored. The full precedence is under +# "Server keys" in the README. +static_private_key = "2Zdzjqd9c7EB4C9FBuqyDNzErruL4DNrJHoL5jhdE6QVArUTR8" +certificate = "11HpWbvGUzBwSTTVZMX6Dc1bVAupxFfvzkFqWfcQzXwVWWeCFQ6rQTDtrNbv4ncSx11gBb1trRbuhuCuXNptqbQBHnyx4VJKULV9e4AWew" +# Optional: the certificate is checked against it at startup and before every handshake. authority_public_key = "9auqWEzQDVyd2oe1JVGFLMLHZtCo2FFqZwtKA5gd9xbuEu7PH72" -authority_secret_key = "mkDLTBBRxdBv998612qipDYoTK3YUrqLe8uWw7gu3iXbSrn2n" -cert_validity_sec = 3600 listen_address = "0.0.0.0:43333" # Coinbase outputs are specified as descriptors. A full list of descriptors is available at diff --git a/pool-apps/pool/config-examples/testnet4/pool-jds-config-bitcoin-core-ipc-example.toml b/pool-apps/pool/config-examples/testnet4/pool-jds-config-bitcoin-core-ipc-example.toml index e81efb91e..962097e6b 100644 --- a/pool-apps/pool/config-examples/testnet4/pool-jds-config-bitcoin-core-ipc-example.toml +++ b/pool-apps/pool/config-examples/testnet4/pool-jds-config-bitcoin-core-ipc-example.toml @@ -1,7 +1,22 @@ # SRI Pool config (with embedded Job Declaration Server) +# A throwaway static key and the certificate the development authority +# 9auqWEzQDVyd2oe1JVGFLMLHZtCo2FFqZwtKA5gd9xbuEu7PH72 issued for it, valid until the year 2106. +# That authority's secret key is public, so anyone can mint certificates for it: these are for +# trying the examples and for tests, and prove nothing to anyone else. For a real deployment keep +# your authority secret key on another machine, issue a certificate there with +# `sv2-certificate issue-certificate` (see "Server keys" in the README), and give this server only +# its static key and that certificate, either inline as below or through a file read before every +# handshake, so replacing it (or the symlink it is) rotates the key without a restart: +# +# active_static_key = "/etc/sv2/active_static_key.toml" +# +# To use the file, leave static_private_key and certificate unset, both here and in the environment: +# when that pair is set, it is used and the file is ignored. The full precedence is under +# "Server keys" in the README. +static_private_key = "2Zdzjqd9c7EB4C9FBuqyDNzErruL4DNrJHoL5jhdE6QVArUTR8" +certificate = "11HpWbvGUzBwSTTVZMX6Dc1bVAupxFfvzkFqWfcQzXwVWWeCFQ6rQTDtrNbv4ncSx11gBb1trRbuhuCuXNptqbQBHnyx4VJKULV9e4AWew" +# Optional: the certificate is checked against it at startup and before every handshake. authority_public_key = "9auqWEzQDVyd2oe1JVGFLMLHZtCo2FFqZwtKA5gd9xbuEu7PH72" -authority_secret_key = "mkDLTBBRxdBv998612qipDYoTK3YUrqLe8uWw7gu3iXbSrn2n" -cert_validity_sec = 3600 listen_address = "0.0.0.0:43333" # Coinbase outputs are specified as descriptors. A full list of descriptors is available at @@ -65,7 +80,7 @@ min_interval = 5 # Embedded Job Declaration Server (JDS) # Pool runs a JDS subserver that listens for JDP connections from JDC. # Requires template_provider_type = BitcoinCoreIpc (JDS backend is selected by Pool startup). -# Shared fields (authority keys, cert_validity, coinbase_reward_script) are inherited +# Shared fields (server keys, coinbase_reward_script) are inherited # from the Pool config above. [jds] listen_address = "0.0.0.0:43334" From 854aea2aac498f67489942f03af947768f01812f Mon Sep 17 00:00:00 2001 From: plebhash Date: Fri, 13 Nov 2026 16:01:48 -0300 Subject: [PATCH 8/9] feat!: pin an authority key on every Noise initiator `connect_with_noise` took the server's authority public key as an `Option`, and without one the Pool and JDC connected to a Sv2 Template Provider encrypted but unauthenticated. The Sv2 spec defines no such mode (04-Protocol-Security.md 4.5, 4.5.3, 4.7) and `noise_sv2` no longer offers it, so `Sv2Tp.public_key` is required: it is the key the TP prints at startup as "Template Provider authority key", as the Pool and JDC READMEs already say. The local-TP example configs carry the development authority key with a note that it will not match a real TP. The integration-test harness installs the test authority's secret key in sv2-tp's data directory before starting it (the `sv2_authority_key` file sv2-tp loads, in Bitcoin Core's `CKey` serialization), so sv2-tp presents a certificate from the same authority as every role under test and every client in the harness, the sniffer, the mock roles and the mining device included, pins that one key. The `mining_device` binary's `--pubkey-pool` flag is required for the same reason. BREAKING CHANGE: `connect_with_noise(stream, Secp256k1PublicKey)`; `TemplateProviderType::Sv2Tp { public_key }` is no longer optional, so Pool and JDC configs using a Sv2 Template Provider must set it. Covered by the bumps already in this series. --- integration-tests/README.md | 1 + integration-tests/bin/mining_device.rs | 4 +- integration-tests/lib/mining_device/mod.rs | 4 +- integration-tests/lib/mod.rs | 44 +++++++++---------- integration-tests/lib/template_provider.rs | 15 ++++++- integration-tests/lib/utils.rs | 8 +++- .../tests/monitoring_integration.rs | 2 - integration-tests/tests/pool_integration.rs | 2 +- integration-tests/tests/sv2_mining_device.rs | 2 +- miner-apps/jd-client/README.md | 4 +- .../jdc-config-local-infra-example.toml | 3 ++ .../jdc-config-solo-mining-example.toml | 3 ++ .../jdc-config-local-infra-example.toml | 3 ++ .../jdc-config-local-infra-example.toml | 3 ++ miner-apps/jd-client/src/args.rs | 8 ++++ .../template_message_handler.rs | 2 +- .../jd-client/src/lib/job_declarator/mod.rs | 2 +- .../src/lib/template_receiver/sv2_tp/mod.rs | 2 +- miner-apps/jd-client/src/lib/upstream/mod.rs | 2 +- .../translator/src/lib/sv2/upstream/mod.rs | 2 +- pool-apps/pool/README.md | 4 +- .../pool-config-local-sv2-tp-example.toml | 3 ++ .../pool-config-local-sv2-tp-example.toml | 3 ++ .../pool-config-local-sv2-tp-example.toml | 3 ++ pool-apps/pool/src/args.rs | 8 ++++ pool-apps/pool/src/lib/config.rs | 1 + .../src/lib/template_receiver/sv2_tp/mod.rs | 2 +- stratum-apps/src/network_helpers/mod.rs | 11 ++--- .../src/network_helpers/noise_connection.rs | 10 ++++- .../network_helpers/responder_credentials.rs | 2 +- stratum-apps/src/tp_type.rs | 3 +- 31 files changed, 113 insertions(+), 53 deletions(-) diff --git a/integration-tests/README.md b/integration-tests/README.md index 9b4e4f9a3..e1f1aa19a 100644 --- a/integration-tests/README.md +++ b/integration-tests/README.md @@ -51,6 +51,7 @@ To run it directly through Cargo: ```bash cargo run -p integration_tests_sv2 --release --bin mining_device -- \ --address-pool 127.0.0.1:3333 \ + --pubkey-pool 9auqWEzQDVyd2oe1JVGFLMLHZtCo2FFqZwtKA5gd9xbuEu7PH72 \ --id-device test ``` diff --git a/integration-tests/bin/mining_device.rs b/integration-tests/bin/mining_device.rs index a8226dd0b..c6c77886e 100644 --- a/integration-tests/bin/mining_device.rs +++ b/integration-tests/bin/mining_device.rs @@ -9,9 +9,9 @@ struct Args { #[arg( short, long, - help = "Pool pub key, when left empty the pool certificate is not checked" + help = "Pool authority public key the pool certificate must verify against" )] - pubkey_pool: Option, + pubkey_pool: Secp256k1PublicKey, #[arg( short, long, diff --git a/integration-tests/lib/mining_device/mod.rs b/integration-tests/lib/mining_device/mod.rs index 4c30e4e0a..6cd85e637 100644 --- a/integration-tests/lib/mining_device/mod.rs +++ b/integration-tests/lib/mining_device/mod.rs @@ -99,7 +99,7 @@ pub fn total_logical_cpus() -> u32 { pub async fn connect( address: String, - pub_key: Option, + pub_key: Secp256k1PublicKey, device_id: Option, user_id: Option, handicap: u32, @@ -134,7 +134,7 @@ pub async fn connect( }; info!("Pool tcp connection established at {}", address); let address = socket.peer_addr().unwrap(); - let initiator = Initiator::new(pub_key.map(|e| e.0)); + let initiator = Initiator::new(pub_key.0); let (receiver, sender) = Connection::connect(socket, initiator, CancellationToken::new()) .await .unwrap(); diff --git a/integration-tests/lib/mod.rs b/integration-tests/lib/mod.rs index 165ca0ed3..691ba78de 100644 --- a/integration-tests/lib/mod.rs +++ b/integration-tests/lib/mod.rs @@ -1,7 +1,4 @@ -use crate::{ - mining_device::Secp256k1PublicKey as MiningDeviceSecp256k1PublicKey, sniffer::*, - sv1_minerd::MinerdProcess, template_provider::*, -}; +use crate::{sniffer::*, sv1_minerd::MinerdProcess, template_provider::*}; use interceptor::InterceptAction; use jd_client_sv2::{JobDeclaratorClient, config::ConfigJDCMode}; use once_cell::sync::OnceCell; @@ -53,11 +50,12 @@ const JDC_COINBASE_REWARD_DESCRIPTOR: &str = "addr(tb1qpusf5256yxv50qt0pm0tue8k9 static LOGGER: OnceCell<()> = OnceCell::new(); -/// Helper to create Sv2Tp config for Pool/JDC with default public key. +/// Helper to create Sv2Tp config for Pool/JDC, pinning the test authority that +/// [`TemplateProvider::start`] installs on sv2-tp. pub fn sv2_tp_config(address: SocketAddr) -> TemplateProviderType { TemplateProviderType::Sv2Tp { address: address.to_string(), - public_key: None, + public_key: TEST_AUTHORITY_PUBLIC_KEY.parse().unwrap(), } } @@ -118,14 +116,21 @@ pub fn start_sniffer( (sniffer, listening_address) } +/// The development authority every server in the harness presents a certificate from: the roles +/// under test through [`test_responder_credentials`], sv2-tp through the key file +/// [`TemplateProvider::start`] installs. Every client pins this key. +pub const TEST_AUTHORITY_PUBLIC_KEY: &str = "9auqWEzQDVyd2oe1JVGFLMLHZtCo2FFqZwtKA5gd9xbuEu7PH72"; +/// Its secret key, which is public: it issues throwaway certificates only. +pub const TEST_AUTHORITY_SECRET_KEY: &str = "mkDLTBBRxdBv998612qipDYoTK3YUrqLe8uWw7gu3iXbSrn2n"; + /// What servers under test present in the Noise handshake: a throwaway static key and the /// certificate the shared test authority issued for it, valid until the year 2106. The clients -/// under test pin that authority's public key; no test holds its secret key. +/// under test pin that authority's public key. pub fn test_responder_credentials() -> ResponderCredentials { ResponderCredentials::PreIssued { static_private_key: "2Zdzjqd9c7EB4C9FBuqyDNzErruL4DNrJHoL5jhdE6QVArUTR8".parse().unwrap(), certificate: "11HpWbvGUzBwSTTVZMX6Dc1bVAupxFfvzkFqWfcQzXwVWWeCFQ6rQTDtrNbv4ncSx11gBb1trRbuhuCuXNptqbQBHnyx4VJKULV9e4AWew".parse().unwrap(), - authority_public_key: Some("9auqWEzQDVyd2oe1JVGFLMLHZtCo2FFqZwtKA5gd9xbuEu7PH72".parse().unwrap()), + authority_public_key: Some(TEST_AUTHORITY_PUBLIC_KEY.parse().unwrap()), } } @@ -252,10 +257,8 @@ pub fn start_jdc_with_user_identities( let jdc_address = get_available_address(); let coinbase_reward_script = CoinbaseRewardScript::from_descriptor(JDC_COINBASE_REWARD_DESCRIPTOR).unwrap(); - let authority_pubkey = Secp256k1PublicKey::try_from( - "9auqWEzQDVyd2oe1JVGFLMLHZtCo2FFqZwtKA5gd9xbuEu7PH72".to_string(), - ) - .unwrap(); + let authority_pubkey = + Secp256k1PublicKey::try_from(TEST_AUTHORITY_PUBLIC_KEY.to_string()).unwrap(); let upstreams = pool .iter() .map(|(pool_addr, jds_addr, per_upstream_id)| { @@ -387,10 +390,9 @@ pub async fn start_sv2_translator_with_user_identities( enable_monitoring: bool, ) -> (TranslatorSv2, SocketAddr, Option) { let job_keepalive_interval_secs = job_keepalive_interval_secs.unwrap_or(60); - let upstream_authority_pubkey = Secp256k1PublicKey::try_from( - "9auqWEzQDVyd2oe1JVGFLMLHZtCo2FFqZwtKA5gd9xbuEu7PH72".to_string(), - ) - .expect("failed to parse test authority pubkey"); + let upstream_authority_pubkey = + Secp256k1PublicKey::try_from(TEST_AUTHORITY_PUBLIC_KEY.to_string()) + .expect("failed to parse test authority pubkey"); let upstreams = upstreams .iter() @@ -465,10 +467,9 @@ pub async fn start_sv2_translator_with_user_identity( .map(|upstream| { let upstream_address = upstream.ip().to_string(); let upstream_port = upstream.port(); - let upstream_authority_pubkey = Secp256k1PublicKey::try_from( - "9auqWEzQDVyd2oe1JVGFLMLHZtCo2FFqZwtKA5gd9xbuEu7PH72".to_string(), - ) - .expect("failed"); + let upstream_authority_pubkey = + Secp256k1PublicKey::try_from(TEST_AUTHORITY_PUBLIC_KEY.to_string()) + .expect("failed"); translator_sv2::config::Upstream::new( upstream_address, @@ -540,7 +541,6 @@ pub async fn start_minerd( pub fn start_mining_device_sv2( upstream: SocketAddr, - pub_key: Option, device_id: Option, user_id: Option, handicap: u32, @@ -553,7 +553,7 @@ pub fn start_mining_device_sv2( tokio::spawn(async move { crate::mining_device::connect( upstream.to_string(), - pub_key, + TEST_AUTHORITY_PUBLIC_KEY.parse().unwrap(), device_id, user_id, handicap, diff --git a/integration-tests/lib/template_provider.rs b/integration-tests/lib/template_provider.rs index 4636ca2b4..0df374236 100644 --- a/integration-tests/lib/template_provider.rs +++ b/integration-tests/lib/template_provider.rs @@ -564,7 +564,7 @@ impl BitcoinCore { } } - fn network_dir(&self) -> PathBuf { + pub(crate) fn network_dir(&self) -> PathBuf { let network_dir = if self.is_signet { "signet" } else { "regtest" }; self.data_dir.join(network_dir) } @@ -724,6 +724,19 @@ impl TemplateProvider { "-regtest" }; + // sv2-tp signs its certificate with the authority key it finds in its data directory, + // so install the test authority there before it starts; every client in the harness pins + // that authority (see `crate::TEST_AUTHORITY_PUBLIC_KEY`). The file is Bitcoin Core's + // `CKey` serialization: one "compressed" flag byte, then the 32 key bytes. + let net_dir = bitcoin_core.network_dir(); + create_dir_all(&net_dir).expect("Failed to create the sv2-tp network data directory"); + let authority: stratum_apps::key_utils::Secp256k1SecretKey = + crate::TEST_AUTHORITY_SECRET_KEY.parse().expect("valid key"); + let mut key_file = vec![1u8]; + key_file.extend_from_slice(&authority.0.secret_bytes()); + std::fs::write(net_dir.join("sv2_authority_key"), key_file) + .expect("Failed to install the sv2-tp authority key"); + let sv2_tp_process = Command::new(&sv2_tp_bin) .arg(network) .arg(format!("-datadir={}", datadir.display())) diff --git a/integration-tests/lib/utils.rs b/integration-tests/lib/utils.rs index c00b23f38..6f14d94da 100644 --- a/integration-tests/lib/utils.rs +++ b/integration-tests/lib/utils.rs @@ -263,7 +263,13 @@ pub async fn create_downstream( pub async fn create_upstream( stream: tokio::net::TcpStream, ) -> Option<(Receiver, Sender)> { - let initiator = Initiator::without_pk().expect("This fn call can not fail"); + // Every server the harness connects to presents a certificate from the test authority. + let initiator = Initiator::new( + crate::TEST_AUTHORITY_PUBLIC_KEY + .parse::() + .expect("valid key") + .0, + ); Connection::connect::(stream, initiator, CancellationToken::new()) .await .ok() diff --git a/integration-tests/tests/monitoring_integration.rs b/integration-tests/tests/monitoring_integration.rs index dba883a38..d62b30625 100644 --- a/integration-tests/tests/monitoring_integration.rs +++ b/integration-tests/tests/monitoring_integration.rs @@ -45,7 +45,6 @@ async fn pool_monitoring_with_sv2_mining_device() { start_mining_device_sv2( sniffer_addr, None, - None, Some("test-miner".to_string()), 1, None, @@ -393,7 +392,6 @@ async fn pool_api_endpoints_with_miner() { start_mining_device_sv2( sniffer_addr, None, - None, Some("test-miner".to_string()), 1, None, diff --git a/integration-tests/tests/pool_integration.rs b/integration-tests/tests/pool_integration.rs index 0991a7934..a37108704 100644 --- a/integration-tests/tests/pool_integration.rs +++ b/integration-tests/tests/pool_integration.rs @@ -199,7 +199,7 @@ async fn pool_standard_channel_receives_share() { let (_tp, tp_addr) = start_template_provider(None, DifficultyLevel::Low); let (pool, pool_addr, _) = start_pool(sv2_tp_config(tp_addr), vec![], vec![], false).await; let (sniffer, sniffer_addr) = start_sniffer("A", pool_addr, false, vec![], None); - start_mining_device_sv2(sniffer_addr, None, None, None, 1, None, true); + start_mining_device_sv2(sniffer_addr, None, None, 1, None, true); sniffer .wait_for_message_type(MessageDirection::ToUpstream, MESSAGE_TYPE_SETUP_CONNECTION) .await; diff --git a/integration-tests/tests/sv2_mining_device.rs b/integration-tests/tests/sv2_mining_device.rs index ebbd05399..a4b60321e 100644 --- a/integration-tests/tests/sv2_mining_device.rs +++ b/integration-tests/tests/sv2_mining_device.rs @@ -7,7 +7,7 @@ async fn sv2_mining_device_and_pool_success() { let (_tp, tp_addr) = start_template_provider(None, DifficultyLevel::Low); let (pool, pool_addr, _) = start_pool(sv2_tp_config(tp_addr), vec![], vec![], false).await; let (sniffer, sniffer_addr) = start_sniffer("A", pool_addr, false, vec![], None); - start_mining_device_sv2(sniffer_addr, None, None, None, 1, None, true); + start_mining_device_sv2(sniffer_addr, None, None, 1, None, true); sniffer .wait_for_message_type(MessageDirection::ToUpstream, MESSAGE_TYPE_SETUP_CONNECTION) .await; diff --git a/miner-apps/jd-client/README.md b/miner-apps/jd-client/README.md index 45e5ed24f..7395c6266 100644 --- a/miner-apps/jd-client/README.md +++ b/miner-apps/jd-client/README.md @@ -75,7 +75,7 @@ The configuration file contains the following information: 4. The `template_provider_type` section, which determines how the pool obtains block templates. There are two options: - `[template_provider_type.Sv2Tp]` - Connects to an SV2 Template Provider, with the following parameters: - `address` - The Template Provider's network address - - `public_key` - (Optional) The TP's authority public key for connection verification + - `public_key` - The TP's authority public key, which its certificate must verify against - `[template_provider_type.BitcoinCoreIpc]` - Connects directly to Bitcoin Core via IPC, with the following parameters: - `version` - Required Bitcoin Core IPC schema major version (`30` or `31`, any other value fails startup) - `network` - Bitcoin network (mainnet, testnet4, signet, regtest) for determining socket path @@ -83,7 +83,7 @@ The configuration file contains the following information: - `fee_threshold` - Minimum fee threshold to trigger new templates - `min_interval` - Minimum interval between template updates in seconds -For connections with a Sv2 Template Provider, you may want to verify that your TP connection is authentic. You can get the `public_key` from the logs of your TP, for example: +`public_key` is the authority key your TP prints at startup, for example: ``` # 2024-02-13T14:59:24Z Template Provider authority key: EguTM8URcZDQVeEBsM4B5vg9weqEUnufA8pm85fG4bZd diff --git a/miner-apps/jd-client/config-examples/mainnet/jdc-config-local-infra-example.toml b/miner-apps/jd-client/config-examples/mainnet/jdc-config-local-infra-example.toml index b284e8b4f..2712572f8 100644 --- a/miner-apps/jd-client/config-examples/mainnet/jdc-config-local-infra-example.toml +++ b/miner-apps/jd-client/config-examples/mainnet/jdc-config-local-infra-example.toml @@ -107,3 +107,6 @@ user_identity = "your_backup_username_here" [template_provider_type.Sv2Tp] # address accepts "ip:port" or "hostname:port" (e.g. "tp.example.com:8442") address = "127.0.0.1:8442" +# The authority public key your TP prints at startup ("Template Provider authority key: ..."); +# the value below is the development authority used by the examples and will not match your TP. +public_key = "9auqWEzQDVyd2oe1JVGFLMLHZtCo2FFqZwtKA5gd9xbuEu7PH72" diff --git a/miner-apps/jd-client/config-examples/mainnet/jdc-config-solo-mining-example.toml b/miner-apps/jd-client/config-examples/mainnet/jdc-config-solo-mining-example.toml index 316ebe880..3d73b0565 100644 --- a/miner-apps/jd-client/config-examples/mainnet/jdc-config-solo-mining-example.toml +++ b/miner-apps/jd-client/config-examples/mainnet/jdc-config-solo-mining-example.toml @@ -66,3 +66,6 @@ cidrs = ["192.168.1.0/24"] # Local Sv2 Template Provider config [template_provider_type.Sv2Tp] address = "127.0.0.1:8442" +# The authority public key your TP prints at startup ("Template Provider authority key: ..."); +# the value below is the development authority used by the examples and will not match your TP. +public_key = "9auqWEzQDVyd2oe1JVGFLMLHZtCo2FFqZwtKA5gd9xbuEu7PH72" diff --git a/miner-apps/jd-client/config-examples/signet/jdc-config-local-infra-example.toml b/miner-apps/jd-client/config-examples/signet/jdc-config-local-infra-example.toml index e75823994..1d97a0e31 100644 --- a/miner-apps/jd-client/config-examples/signet/jdc-config-local-infra-example.toml +++ b/miner-apps/jd-client/config-examples/signet/jdc-config-local-infra-example.toml @@ -106,3 +106,6 @@ user_identity = "your_backup_username_here" [template_provider_type.Sv2Tp] # address accepts "ip:port" or "hostname:port" (e.g. "tp.example.com:8442") address = "127.0.0.1:38442" +# The authority public key your TP prints at startup ("Template Provider authority key: ..."); +# the value below is the development authority used by the examples and will not match your TP. +public_key = "9auqWEzQDVyd2oe1JVGFLMLHZtCo2FFqZwtKA5gd9xbuEu7PH72" diff --git a/miner-apps/jd-client/config-examples/testnet4/jdc-config-local-infra-example.toml b/miner-apps/jd-client/config-examples/testnet4/jdc-config-local-infra-example.toml index ae5b25e64..20547388f 100644 --- a/miner-apps/jd-client/config-examples/testnet4/jdc-config-local-infra-example.toml +++ b/miner-apps/jd-client/config-examples/testnet4/jdc-config-local-infra-example.toml @@ -107,3 +107,6 @@ user_identity = "your_backup_username_here" [template_provider_type.Sv2Tp] # address accepts "ip:port" or "hostname:port" (e.g. "tp.example.com:8442") address = "127.0.0.1:48442" +# The authority public key your TP prints at startup ("Template Provider authority key: ..."); +# the value below is the development authority used by the examples and will not match your TP. +public_key = "9auqWEzQDVyd2oe1JVGFLMLHZtCo2FFqZwtKA5gd9xbuEu7PH72" diff --git a/miner-apps/jd-client/src/args.rs b/miner-apps/jd-client/src/args.rs index 2ac38db35..56ee42121 100644 --- a/miner-apps/jd-client/src/args.rs +++ b/miner-apps/jd-client/src/args.rs @@ -91,6 +91,10 @@ mod tests { "JDC__TEMPLATE_PROVIDER_TYPE__SV2TP__ADDRESS", "127.0.0.1:8442", ), + ( + "JDC__TEMPLATE_PROVIDER_TYPE__SV2TP__PUBLIC_KEY", + "9auqWEzQDVyd2oe1JVGFLMLHZtCo2FFqZwtKA5gd9xbuEu7PH72", + ), ( "JDC__UPSTREAM_01__AUTHORITY_PUBKEY", "9auqWEzQDVyd2oe1JVGFLMLHZtCo2FFqZwtKA5gd9xbuEu7PH72", @@ -160,6 +164,10 @@ mod tests { "JDC_PREISSUED__TEMPLATE_PROVIDER_TYPE__SV2TP__ADDRESS", "127.0.0.1:8442", ), + ( + "JDC_PREISSUED__TEMPLATE_PROVIDER_TYPE__SV2TP__PUBLIC_KEY", + "9auqWEzQDVyd2oe1JVGFLMLHZtCo2FFqZwtKA5gd9xbuEu7PH72", + ), ( "JDC_PREISSUED__UPSTREAM_01__AUTHORITY_PUBKEY", "9auqWEzQDVyd2oe1JVGFLMLHZtCo2FFqZwtKA5gd9xbuEu7PH72", diff --git a/miner-apps/jd-client/src/lib/channel_manager/template_message_handler.rs b/miner-apps/jd-client/src/lib/channel_manager/template_message_handler.rs index 98348a9ad..75aab814b 100644 --- a/miner-apps/jd-client/src/lib/channel_manager/template_message_handler.rs +++ b/miner-apps/jd-client/src/lib/channel_manager/template_message_handler.rs @@ -777,7 +777,7 @@ mod tests { }, TemplateProviderType::Sv2Tp { address: "127.0.0.1:0".to_string(), - public_key: None, + public_key: "9auqWEzQDVyd2oe1JVGFLMLHZtCo2FFqZwtKA5gd9xbuEu7PH72".parse().unwrap(), }, vec![], "test-jdc".to_string(), diff --git a/miner-apps/jd-client/src/lib/job_declarator/mod.rs b/miner-apps/jd-client/src/lib/job_declarator/mod.rs index bbcd17764..fb618c03a 100644 --- a/miner-apps/jd-client/src/lib/job_declarator/mod.rs +++ b/miner-apps/jd-client/src/lib/job_declarator/mod.rs @@ -165,7 +165,7 @@ impl JobDeclarator { info!("Shutdown received during handshake, dropping connection"); return Err(JDCError::shutdown(JDCErrorKind::CouldNotInitiateSystem)); } - result = connect_with_noise(stream, Some(upstream_entry.authority_pubkey)) => { + result = connect_with_noise(stream, upstream_entry.authority_pubkey) => { result.map_err(JDCError::fallback)?.into_split() } }; diff --git a/miner-apps/jd-client/src/lib/template_receiver/sv2_tp/mod.rs b/miner-apps/jd-client/src/lib/template_receiver/sv2_tp/mod.rs index e2f15e098..8d1a2b106 100644 --- a/miner-apps/jd-client/src/lib/template_receiver/sv2_tp/mod.rs +++ b/miner-apps/jd-client/src/lib/template_receiver/sv2_tp/mod.rs @@ -136,7 +136,7 @@ impl Sv2Tp { /// Retries up to 3 times before returning [`JDCError::Shutdown`]. pub async fn new( tp_address: String, - public_key: Option, + public_key: Secp256k1PublicKey, channel_manager_receiver: Receiver, channel_manager_sender: Sender, cancellation_token: CancellationToken, diff --git a/miner-apps/jd-client/src/lib/upstream/mod.rs b/miner-apps/jd-client/src/lib/upstream/mod.rs index 556cc07bf..b38284657 100644 --- a/miner-apps/jd-client/src/lib/upstream/mod.rs +++ b/miner-apps/jd-client/src/lib/upstream/mod.rs @@ -180,7 +180,7 @@ impl Upstream { info!("Shutdown received during handshake, dropping connection"); Err(JDCError::shutdown(JDCErrorKind::CouldNotInitiateSystem)) } - result = connect_with_noise(stream, Some(upstream_entry.authority_pubkey)) => { + result = connect_with_noise(stream, upstream_entry.authority_pubkey) => { match result { Ok(noise_stream) => Ok(noise_stream.into_split()), Err(e) => Err(JDCError::fallback(e)) diff --git a/miner-apps/translator/src/lib/sv2/upstream/mod.rs b/miner-apps/translator/src/lib/sv2/upstream/mod.rs index f424ca4c0..595b8b514 100644 --- a/miner-apps/translator/src/lib/sv2/upstream/mod.rs +++ b/miner-apps/translator/src/lib/sv2/upstream/mod.rs @@ -315,7 +315,7 @@ impl Upstream { info!("Shutdown received during handshake, dropping connection"); Err(TproxyError::shutdown(TproxyErrorKind::CouldNotInitiateSystem)) } - result = connect_with_noise(socket, Some(upstream.authority_pubkey)) => { + result = connect_with_noise(socket, upstream.authority_pubkey) => { match result { Ok(stream) => { let (reader, writer) = stream.into_split(); diff --git a/pool-apps/pool/README.md b/pool-apps/pool/README.md index 5b3e017c1..23821b418 100644 --- a/pool-apps/pool/README.md +++ b/pool-apps/pool/README.md @@ -56,7 +56,7 @@ The configuration file contains the following information: 5. The `template_provider_type` section, which determines how the pool obtains block templates. There are two options: - `[template_provider_type.Sv2Tp]` - Connects to an SV2 Template Provider, with the following parameters: - `address` - The Template Provider's network address - - `public_key` - (Optional) The TP's authority public key for connection verification + - `public_key` - The TP's authority public key, which its certificate must verify against - `[template_provider_type.BitcoinCoreIpc]` - Connects directly to Bitcoin Core via IPC, with the following parameters: - `version` - Required Bitcoin Core IPC schema major version (`30` or `31`, any other value fails startup) - `network` - Bitcoin network (mainnet, testnet4, signet, regtest) for determining socket path @@ -64,7 +64,7 @@ The configuration file contains the following information: - `fee_threshold` - Minimum fee threshold to trigger new templates - `min_interval` - Minimum interval between template updates in seconds -For connections with a Sv2 Template Provider, you may want to verify that your TP connection is authentic. You can get the `public_key` from the logs of your TP, for example: +`public_key` is the authority key your TP prints at startup, for example: ``` # 2024-02-13T14:59:24Z Template Provider authority key: EguTM8URcZDQVeEBsM4B5vg9weqEUnufA8pm85fG4bZd diff --git a/pool-apps/pool/config-examples/mainnet/pool-config-local-sv2-tp-example.toml b/pool-apps/pool/config-examples/mainnet/pool-config-local-sv2-tp-example.toml index c20cd3357..27e19a05e 100644 --- a/pool-apps/pool/config-examples/mainnet/pool-config-local-sv2-tp-example.toml +++ b/pool-apps/pool/config-examples/mainnet/pool-config-local-sv2-tp-example.toml @@ -56,3 +56,6 @@ monitoring_cache_refresh_secs = 15 [template_provider_type.Sv2Tp] # address accepts "ip:port" or "hostname:port" (e.g. "tp.example.com:8442") address = "127.0.0.1:8442" +# The authority public key your TP prints at startup ("Template Provider authority key: ..."); +# the value below is the development authority used by the examples and will not match your TP. +public_key = "9auqWEzQDVyd2oe1JVGFLMLHZtCo2FFqZwtKA5gd9xbuEu7PH72" diff --git a/pool-apps/pool/config-examples/signet/pool-config-local-sv2-tp-example.toml b/pool-apps/pool/config-examples/signet/pool-config-local-sv2-tp-example.toml index 14c6ff393..f96788331 100644 --- a/pool-apps/pool/config-examples/signet/pool-config-local-sv2-tp-example.toml +++ b/pool-apps/pool/config-examples/signet/pool-config-local-sv2-tp-example.toml @@ -54,6 +54,9 @@ monitoring_cache_refresh_secs = 15 [template_provider_type.Sv2Tp] # address accepts "ip:port" or "hostname:port" (e.g. "tp.example.com:8442") address = "127.0.0.1:38442" +# The authority public key your TP prints at startup ("Template Provider authority key: ..."); +# the value below is the development authority used by the examples and will not match your TP. +public_key = "9auqWEzQDVyd2oe1JVGFLMLHZtCo2FFqZwtKA5gd9xbuEu7PH72" # Note: Embedded JDS ([jds] section) is NOT available with Sv2Tp template provider. # JDS requires template_provider_type = BitcoinCoreIpc for direct IPC access to Bitcoin Core. diff --git a/pool-apps/pool/config-examples/testnet4/pool-config-local-sv2-tp-example.toml b/pool-apps/pool/config-examples/testnet4/pool-config-local-sv2-tp-example.toml index 8091f1f37..3268b4cd9 100644 --- a/pool-apps/pool/config-examples/testnet4/pool-config-local-sv2-tp-example.toml +++ b/pool-apps/pool/config-examples/testnet4/pool-config-local-sv2-tp-example.toml @@ -55,3 +55,6 @@ monitoring_cache_refresh_secs = 15 [template_provider_type.Sv2Tp] # address accepts "ip:port" or "hostname:port" (e.g. "tp.example.com:8442") address = "127.0.0.1:48442" +# The authority public key your TP prints at startup ("Template Provider authority key: ..."); +# the value below is the development authority used by the examples and will not match your TP. +public_key = "9auqWEzQDVyd2oe1JVGFLMLHZtCo2FFqZwtKA5gd9xbuEu7PH72" diff --git a/pool-apps/pool/src/args.rs b/pool-apps/pool/src/args.rs index 11765ed9d..cc1e08f85 100644 --- a/pool-apps/pool/src/args.rs +++ b/pool-apps/pool/src/args.rs @@ -93,6 +93,10 @@ mod tests { "POOL__TEMPLATE_PROVIDER_TYPE__SV2TP__ADDRESS", "127.0.0.1:8442", ), + ( + "POOL__TEMPLATE_PROVIDER_TYPE__SV2TP__PUBLIC_KEY", + "9auqWEzQDVyd2oe1JVGFLMLHZtCo2FFqZwtKA5gd9xbuEu7PH72", + ), ]; for (key, value) in vars { unsafe { std::env::set_var(key, value) }; @@ -144,6 +148,10 @@ mod tests { "POOL_PREISSUED__TEMPLATE_PROVIDER_TYPE__SV2TP__ADDRESS", "127.0.0.1:8442", ), + ( + "POOL_PREISSUED__TEMPLATE_PROVIDER_TYPE__SV2TP__PUBLIC_KEY", + "9auqWEzQDVyd2oe1JVGFLMLHZtCo2FFqZwtKA5gd9xbuEu7PH72", + ), ]; let inline = [ ( diff --git a/pool-apps/pool/src/lib/config.rs b/pool-apps/pool/src/lib/config.rs index 00cfe6b05..a0b036590 100644 --- a/pool-apps/pool/src/lib/config.rs +++ b/pool-apps/pool/src/lib/config.rs @@ -259,6 +259,7 @@ share_batch_size = 10 [template_provider_type.Sv2Tp] address = "127.0.0.1:8442" +public_key = "9auqWEzQDVyd2oe1JVGFLMLHZtCo2FFqZwtKA5gd9xbuEu7PH72" "# ), ) diff --git a/pool-apps/pool/src/lib/template_receiver/sv2_tp/mod.rs b/pool-apps/pool/src/lib/template_receiver/sv2_tp/mod.rs index bd4923fd7..c5dd627ed 100644 --- a/pool-apps/pool/src/lib/template_receiver/sv2_tp/mod.rs +++ b/pool-apps/pool/src/lib/template_receiver/sv2_tp/mod.rs @@ -91,7 +91,7 @@ impl Sv2Tp { /// Retries up to 3 times before returning [`PoolError::shutdown`]. pub async fn new( tp_address: String, - public_key: Option, + public_key: Secp256k1PublicKey, channel_manager_receiver: Receiver, channel_manager_sender: Sender, cancellation_token: CancellationToken, diff --git a/stratum-apps/src/network_helpers/mod.rs b/stratum-apps/src/network_helpers/mod.rs index 46906da90..2890aa739 100644 --- a/stratum-apps/src/network_helpers/mod.rs +++ b/stratum-apps/src/network_helpers/mod.rs @@ -118,16 +118,13 @@ pub const TCP_CONNECT_TIMEOUT: Duration = Duration::from_secs(5); /// The handshake timeout is opinionated and fixed at `NOISE_HANDSHAKE_TIMEOUT`. If you need a /// custom timeout, use [`noise_stream::NoiseTcpStream::new`] directly. /// -/// Pass `Some(key)` to verify the server's authority public key, or `None` to skip -/// verification (encrypted but unauthenticated — use only on trusted networks). +/// The server's certificate must verify against `authority_pub_key`, or the handshake fails. pub async fn connect_with_noise( stream: TcpStream, - authority_pub_key: Option, + authority_pub_key: Secp256k1PublicKey, ) -> Result { - let initiator = match authority_pub_key { - Some(key) => Initiator::from_raw_k(key.into_bytes()).map_err(|_| Error::InvalidKey)?, - None => Initiator::without_pk().map_err(|_| Error::InvalidKey)?, - }; + let initiator = + Initiator::from_raw_k(authority_pub_key.into_bytes()).map_err(|_| Error::InvalidKey)?; let stream = noise_stream::NoiseTcpStream::connect(stream, initiator, NOISE_HANDSHAKE_TIMEOUT).await?; Ok(stream) diff --git a/stratum-apps/src/network_helpers/noise_connection.rs b/stratum-apps/src/network_helpers/noise_connection.rs index f311f4e2a..8ab7653cd 100644 --- a/stratum-apps/src/network_helpers/noise_connection.rs +++ b/stratum-apps/src/network_helpers/noise_connection.rs @@ -174,7 +174,8 @@ mod tests { use tokio::net::TcpListener; // A throwaway static key and a certificate over it from the development authority, valid - // until the year 2106. The initiator below pins nothing, so any valid certificate does. + // until the year 2106. The initiator below pins that authority. + const AUTHORITY_PUBLIC: &str = "9auqWEzQDVyd2oe1JVGFLMLHZtCo2FFqZwtKA5gd9xbuEu7PH72"; const STATIC_KEY: &str = "2Zdzjqd9c7EB4C9FBuqyDNzErruL4DNrJHoL5jhdE6QVArUTR8"; const CERTIFICATE: &str = "11HpWbvGUzBwSTTVZMX6Dc1bVAupxFfvzkFqWfcQzXwVWWeCFQ6rQTDtrNbv4ncSx11gBb1trRbuhuCuXNptqbQBHnyx4VJKULV9e4AWew"; @@ -203,7 +204,12 @@ mod tests { }); let stream = TcpStream::connect(addr).await.unwrap(); - let initiator = Initiator::without_pk().unwrap(); + let initiator = Initiator::new( + AUTHORITY_PUBLIC + .parse::() + .unwrap() + .0, + ); let cancellation_token = CancellationToken::new(); let (receiver, sender) = Connection::connect::>( stream, diff --git a/stratum-apps/src/network_helpers/responder_credentials.rs b/stratum-apps/src/network_helpers/responder_credentials.rs index caf098b1f..820460403 100644 --- a/stratum-apps/src/network_helpers/responder_credentials.rs +++ b/stratum-apps/src/network_helpers/responder_credentials.rs @@ -350,7 +350,7 @@ mod tests { // Connects once, pinning the test authority, and reports whether the handshake succeeded. async fn connect_once(addr: std::net::SocketAddr) -> bool { let stream = TcpStream::connect(addr).await.unwrap(); - connect_with_noise(stream, Some(AUTHORITY_PUBLIC.parse().unwrap())) + connect_with_noise(stream, AUTHORITY_PUBLIC.parse().unwrap()) .await .is_ok() } diff --git a/stratum-apps/src/tp_type.rs b/stratum-apps/src/tp_type.rs index 65caa1dfa..1f8bcd057 100644 --- a/stratum-apps/src/tp_type.rs +++ b/stratum-apps/src/tp_type.rs @@ -81,7 +81,8 @@ pub fn resolve_ipc_socket_path( pub enum TemplateProviderType { Sv2Tp { address: String, - public_key: Option, + /// The TP's authority public key, which its certificate must verify against. + public_key: Secp256k1PublicKey, }, #[cfg(feature = "bitcoin-core-sv2")] BitcoinCoreIpc { From 165488f419b9322a09910cd3bc5ea55e3679bdad Mon Sep 17 00:00:00 2001 From: plebhash Date: Mon, 9 Nov 2026 19:15:16 -0300 Subject: [PATCH 9/9] TEMP: point stratum-core to companion PR branch 2026-11-09-noise-preissued-cert Temporary commit so CI builds against https://github.com/stratum-mining/stratum/pull/2497. Drop it and update stratum-core to stratum main once that PR is merged. --- Cargo.lock | 40 ++++++++++++++++++++-------------------- Cargo.toml | 5 +++++ 2 files changed, 25 insertions(+), 20 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 2a62b91f2..59c3323f2 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1023,7 +1023,7 @@ checksum = "32637268377fc7b10a8c6d51de3e7fba1ce5dd371a96e342b34e6078db558e7f" [[package]] name = "binary_sv2" version = "8.0.0" -source = "git+https://github.com/stratum-mining/stratum?branch=main#2220f62dbdc833a64c53f05bd0fbed3ae611f4d6" +source = "git+https://github.com/plebhash/stratum?branch=2026-11-09-noise-preissued-cert#1581d171f8a2486fd4ba5692cb7006793219e8db" dependencies = [ "buffer_sv2", "derive_codec_sv2", @@ -1220,7 +1220,7 @@ dependencies = [ [[package]] name = "buffer_sv2" version = "4.0.0" -source = "git+https://github.com/stratum-mining/stratum?branch=main#2220f62dbdc833a64c53f05bd0fbed3ae611f4d6" +source = "git+https://github.com/plebhash/stratum?branch=2026-11-09-noise-preissued-cert#1581d171f8a2486fd4ba5692cb7006793219e8db" [[package]] name = "bumpalo" @@ -1354,7 +1354,7 @@ dependencies = [ [[package]] name = "channels_sv2" version = "9.0.0" -source = "git+https://github.com/stratum-mining/stratum?branch=main#2220f62dbdc833a64c53f05bd0fbed3ae611f4d6" +source = "git+https://github.com/plebhash/stratum?branch=2026-11-09-noise-preissued-cert#1581d171f8a2486fd4ba5692cb7006793219e8db" dependencies = [ "binary_sv2", "bitcoin", @@ -1472,8 +1472,8 @@ dependencies = [ [[package]] name = "codec_sv2" -version = "8.1.0" -source = "git+https://github.com/stratum-mining/stratum?branch=main#2220f62dbdc833a64c53f05bd0fbed3ae611f4d6" +version = "9.0.0" +source = "git+https://github.com/plebhash/stratum?branch=2026-11-09-noise-preissued-cert#1581d171f8a2486fd4ba5692cb7006793219e8db" dependencies = [ "binary_sv2", "buffer_sv2", @@ -1510,7 +1510,7 @@ dependencies = [ [[package]] name = "common_messages_sv2" version = "10.0.0" -source = "git+https://github.com/stratum-mining/stratum?branch=main#2220f62dbdc833a64c53f05bd0fbed3ae611f4d6" +source = "git+https://github.com/plebhash/stratum?branch=2026-11-09-noise-preissued-cert#1581d171f8a2486fd4ba5692cb7006793219e8db" dependencies = [ "binary_sv2", ] @@ -1800,7 +1800,7 @@ dependencies = [ [[package]] name = "derive_codec_sv2" version = "2.0.0" -source = "git+https://github.com/stratum-mining/stratum?branch=main#2220f62dbdc833a64c53f05bd0fbed3ae611f4d6" +source = "git+https://github.com/plebhash/stratum?branch=2026-11-09-noise-preissued-cert#1581d171f8a2486fd4ba5692cb7006793219e8db" [[package]] name = "digest" @@ -2006,7 +2006,7 @@ dependencies = [ [[package]] name = "extensions_sv2" version = "0.4.0" -source = "git+https://github.com/stratum-mining/stratum?branch=main#2220f62dbdc833a64c53f05bd0fbed3ae611f4d6" +source = "git+https://github.com/plebhash/stratum?branch=2026-11-09-noise-preissued-cert#1581d171f8a2486fd4ba5692cb7006793219e8db" dependencies = [ "binary_sv2", ] @@ -2089,7 +2089,7 @@ dependencies = [ [[package]] name = "framing_sv2" version = "9.0.0" -source = "git+https://github.com/stratum-mining/stratum?branch=main#2220f62dbdc833a64c53f05bd0fbed3ae611f4d6" +source = "git+https://github.com/plebhash/stratum?branch=2026-11-09-noise-preissued-cert#1581d171f8a2486fd4ba5692cb7006793219e8db" dependencies = [ "binary_sv2", "buffer_sv2", @@ -2301,7 +2301,7 @@ dependencies = [ [[package]] name = "handlers_sv2" version = "0.7.0" -source = "git+https://github.com/stratum-mining/stratum?branch=main#2220f62dbdc833a64c53f05bd0fbed3ae611f4d6" +source = "git+https://github.com/plebhash/stratum?branch=2026-11-09-noise-preissued-cert#1581d171f8a2486fd4ba5692cb7006793219e8db" dependencies = [ "binary_sv2", "common_messages_sv2", @@ -2904,7 +2904,7 @@ dependencies = [ [[package]] name = "job_declaration_sv2" version = "11.0.0" -source = "git+https://github.com/stratum-mining/stratum?branch=main#2220f62dbdc833a64c53f05bd0fbed3ae611f4d6" +source = "git+https://github.com/plebhash/stratum?branch=2026-11-09-noise-preissued-cert#1581d171f8a2486fd4ba5692cb7006793219e8db" dependencies = [ "binary_sv2", ] @@ -3155,7 +3155,7 @@ checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a" [[package]] name = "mining_sv2" version = "13.0.0" -source = "git+https://github.com/stratum-mining/stratum?branch=main#2220f62dbdc833a64c53f05bd0fbed3ae611f4d6" +source = "git+https://github.com/plebhash/stratum?branch=2026-11-09-noise-preissued-cert#1581d171f8a2486fd4ba5692cb7006793219e8db" dependencies = [ "binary_sv2", ] @@ -3219,8 +3219,8 @@ dependencies = [ [[package]] name = "noise_sv2" -version = "2.1.0" -source = "git+https://github.com/stratum-mining/stratum?branch=main#2220f62dbdc833a64c53f05bd0fbed3ae611f4d6" +version = "3.0.0" +source = "git+https://github.com/plebhash/stratum?branch=2026-11-09-noise-preissued-cert#1581d171f8a2486fd4ba5692cb7006793219e8db" dependencies = [ "chacha20poly1305", "rand 0.8.6", @@ -3382,7 +3382,7 @@ dependencies = [ [[package]] name = "parsers_sv2" version = "0.7.0" -source = "git+https://github.com/stratum-mining/stratum?branch=main#2220f62dbdc833a64c53f05bd0fbed3ae611f4d6" +source = "git+https://github.com/plebhash/stratum?branch=2026-11-09-noise-preissued-cert#1581d171f8a2486fd4ba5692cb7006793219e8db" dependencies = [ "binary_sv2", "common_messages_sv2", @@ -4511,8 +4511,8 @@ dependencies = [ [[package]] name = "stratum-core" -version = "0.7.0" -source = "git+https://github.com/stratum-mining/stratum?branch=main#2220f62dbdc833a64c53f05bd0fbed3ae611f4d6" +version = "0.8.0" +source = "git+https://github.com/plebhash/stratum?branch=2026-11-09-noise-preissued-cert#1581d171f8a2486fd4ba5692cb7006793219e8db" dependencies = [ "binary_sv2", "bitcoin", @@ -4535,7 +4535,7 @@ dependencies = [ [[package]] name = "stratum_translation" version = "0.6.0" -source = "git+https://github.com/stratum-mining/stratum?branch=main#2220f62dbdc833a64c53f05bd0fbed3ae611f4d6" +source = "git+https://github.com/plebhash/stratum?branch=2026-11-09-noise-preissued-cert#1581d171f8a2486fd4ba5692cb7006793219e8db" dependencies = [ "binary_sv2", "bitcoin", @@ -4582,7 +4582,7 @@ checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" [[package]] name = "sv1_api" version = "7.0.0" -source = "git+https://github.com/stratum-mining/stratum?branch=main#2220f62dbdc833a64c53f05bd0fbed3ae611f4d6" +source = "git+https://github.com/plebhash/stratum?branch=2026-11-09-noise-preissued-cert#1581d171f8a2486fd4ba5692cb7006793219e8db" dependencies = [ "binary_sv2", "bitcoin", @@ -4661,7 +4661,7 @@ dependencies = [ [[package]] name = "template_distribution_sv2" version = "8.0.0" -source = "git+https://github.com/stratum-mining/stratum?branch=main#2220f62dbdc833a64c53f05bd0fbed3ae611f4d6" +source = "git+https://github.com/plebhash/stratum?branch=2026-11-09-noise-preissued-cert#1581d171f8a2486fd4ba5692cb7006793219e8db" dependencies = [ "binary_sv2", ] diff --git a/Cargo.toml b/Cargo.toml index 180dcaea3..98d2b14ae 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -22,3 +22,8 @@ default-members = [ "miner-apps/jd-client", "miner-apps/translator", ] + +# Override dependencies with local paths +# Temporary: builds against the companion stratum PR's branch until it lands upstream. +[patch."https://github.com/stratum-mining/stratum"] +stratum-core = { git = "https://github.com/plebhash/stratum", branch = "2026-11-09-noise-preissued-cert" }