diff --git a/Cargo.lock b/Cargo.lock index ad00fc915..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", @@ -4482,6 +4482,8 @@ dependencies = [ "axum", "bitcoin_core_sv2", "bs58", + "chrono", + "clap", "config", "dashmap", "dirs", @@ -4499,6 +4501,7 @@ dependencies = [ "stratum-core", "tokio", "tokio-util", + "toml 0.8.23", "tower", "tracing", "tracing-subscriber", @@ -4508,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", @@ -4532,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", @@ -4579,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", @@ -4658,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" } 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/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 4beb04cfa..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; @@ -11,9 +8,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; @@ -54,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(), } } @@ -119,6 +116,24 @@ 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. +pub fn test_responder_credentials() -> ResponderCredentials { + ResponderCredentials::PreIssued { + static_private_key: "2Zdzjqd9c7EB4C9FBuqyDNzErruL4DNrJHoL5jhdE6QVArUTR8".parse().unwrap(), + certificate: "11HpWbvGUzBwSTTVZMX6Dc1bVAupxFfvzkFqWfcQzXwVWWeCFQ6rQTDtrNbv4ncSx11gBb1trRbuhuCuXNptqbQBHnyx4VJKULV9e4AWew".parse().unwrap(), + authority_public_key: Some(TEST_AUTHORITY_PUBLIC_KEY.parse().unwrap()), + } +} + pub async fn start_pool( template_provider_config: TemplateProviderType, supported_extensions: Vec, @@ -127,25 +142,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 +157,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,22 +253,12 @@ 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( - "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)| { @@ -281,7 +272,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 +284,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 +311,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 +326,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 +337,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, @@ -411,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() @@ -489,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, @@ -564,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, @@ -577,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 f215db542..6f14d94da 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 @@ -271,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 93016cc19..7395c6266 100644 --- a/miner-apps/jd-client/README.md +++ b/miner-apps/jd-client/README.md @@ -71,11 +71,11 @@ 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 - - `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 @@ -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..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 @@ -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 @@ -92,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 1a75a1385..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 @@ -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 @@ -51,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-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..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 @@ -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 @@ -91,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-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..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 @@ -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 @@ -92,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 980c7cce1..56ee42121 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)", @@ -88,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", @@ -126,4 +133,73 @@ 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__TEMPLATE_PROVIDER_TYPE__SV2TP__PUBLIC_KEY", + "9auqWEzQDVyd2oe1JVGFLMLHZtCo2FFqZwtKA5gd9xbuEu7PH72", + ), + ( + "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..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 @@ -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,20 +770,14 @@ 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, + public_key: "9auqWEzQDVyd2oe1JVGFLMLHZtCo2FFqZwtKA5gd9xbuEu7PH72".parse().unwrap(), }, vec![], "test-jdc".to_string(), 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/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/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/README.md b/pool-apps/pool/README.md index ecd990bd8..23821b418 100644 --- a/pool-apps/pool/README.md +++ b/pool-apps/pool/README.md @@ -49,15 +49,14 @@ 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`). 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 @@ -65,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 @@ -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..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 @@ -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 @@ -41,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/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..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 @@ -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 @@ -39,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/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..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 @@ -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 @@ -40,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/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" diff --git a/pool-apps/pool/src/args.rs b/pool-apps/pool/src/args.rs index 281bd09e8..cc1e08f85 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)", @@ -90,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) }; @@ -120,4 +127,75 @@ 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", + ), + ( + "POOL_PREISSUED__TEMPLATE_PROVIDER_TYPE__SV2TP__PUBLIC_KEY", + "9auqWEzQDVyd2oe1JVGFLMLHZtCo2FFqZwtKA5gd9xbuEu7PH72", + ), + ]; + 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..a0b036590 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 @@ -289,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/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/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/Cargo.toml b/stratum-apps/Cargo.toml index f3368e547..64e63682f 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 } @@ -56,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"] @@ -67,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 @@ -92,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"); + } +} 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/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/keys.rs b/stratum-apps/src/key_utils/keys.rs new file mode 100644 index 000000000..347820012 --- /dev/null +++ b/stratum-apps/src/key_utils/keys.rs @@ -0,0 +1,161 @@ +//! 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. + +use crate::key_utils::Error; +use bs58::decode; +use core::{convert::TryFrom, fmt::Display, str::FromStr}; +use secp256k1::{SecretKey, XOnlyPublicKey}; +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Copy, Clone, Serialize, Deserialize)] +#[serde(into = "String", try_from = "String")] +pub struct Secp256k1SecretKey(pub SecretKey); + +impl TryFrom for Secp256k1SecretKey { + type Error = Error; + + fn try_from(value: String) -> Result { + value.parse() + } +} + +impl FromStr for Secp256k1SecretKey { + type Err = Error; + + fn from_str(value: &str) -> Result { + let decoded = decode(value).with_check(None).into_vec()?; + let secret = SecretKey::from_slice(&decoded)?; + Ok(Secp256k1SecretKey(secret)) + } +} + +impl From for String { + fn from(secret: Secp256k1SecretKey) -> Self { + secret.to_string() + } +} + +impl Display for Secp256k1SecretKey { + fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { + let bytes = self.0.secret_bytes(); + f.write_str(&bs58::encode(bytes).with_check().into_string()) + } +} + +#[derive(Debug, Copy, Clone, Serialize, Deserialize)] +#[serde(into = "String", try_from = "String")] +pub struct Secp256k1PublicKey(pub XOnlyPublicKey); + +impl TryFrom for Secp256k1PublicKey { + type Error = Error; + + fn try_from(value: String) -> Result { + value.parse() + } +} + +impl FromStr for Secp256k1PublicKey { + type Err = Error; + + fn from_str(value: &str) -> Result { + let decoded = decode(value).with_check(None).into_vec()?; + if decoded.len() < 34 { + return Err(Error::KeyLength); + } + let key_version = + u16::from_le_bytes(decoded[..2].try_into().expect("Invalid array length")); + if key_version != 1 { + return Err(Error::KeyVersion(key_version)); + } + let public = XOnlyPublicKey::from_slice(&decoded[2..]).map_err(Error::Secp256k1)?; + Ok(Secp256k1PublicKey(public)) + } +} + +impl From for String { + fn from(public: Secp256k1PublicKey) -> Self { + public.to_string() + } +} + +impl Display for Secp256k1PublicKey { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + let mut output = [0_u8; 34]; + output[0] = 1; + let bytes = self.0.serialize(); + output[2..].copy_from_slice(&bytes); + f.write_str(&bs58::encode(&output).with_check().into_string()) + } +} + +impl Secp256k1PublicKey { + pub fn into_bytes(self) -> [u8; 32] { + self.0.serialize() + } +} +impl Secp256k1SecretKey { + pub fn into_bytes(self) -> [u8; 32] { + self.0.secret_bytes() + } +} + +impl From for Secp256k1PublicKey { + fn from(value: Secp256k1SecretKey) -> Self { + let context = secp256k1::Secp256k1::new(); + let (x_coordinate, _) = value.0.public_key(&context).x_only_public_key(); + Self(x_coordinate) + } +} + +#[cfg(test)] +mod test { + use super::*; + + #[test] + fn key_conversions() { + let secret_key = "zmBEmPhqo3A92FkiLVvyCz6htc3e53ph3ZbD4ASqGaLjwnFLi"; + let public_key = "9bDuixKmZqAJnrmP746n8zU1wyAQRrus7th9dxnkPg6RzQvCnan"; + let bad_public_key1 = "9bDuixKmZqAJnrmP746n8zU1wyAQRrus7th9dxnkPg6RzQvCnam"; // invalid checksum (swapped char) + let bad_public_key2 = "2myPhc5vkPzuC5FXNK5tee79WmP7uoLh55SxezoF8iqwF3E3rnPY"; // invalid version (version 12) + let bad_public_key3 = "2wmHTKZkLg2QzXyEXGMBXzKP7JXDUt8yy9SA5hoQwERc92qR6c"; // invalid length (1 B missing) + + let error = bad_public_key1 + .parse::() + .expect_err("Bad bud public key failed to raise error"); + assert!( + matches!(error, Error::Bs58Decode(_)), + "expected failed checksum error, got {}", + error + ); + let error = bad_public_key2 + .parse::() + .expect_err("Bad bud public key failed to raise error"); + assert!( + matches!(error, Error::KeyVersion(_)), + "expected invalid key version error, got {}", + error + ); + let error = bad_public_key3 + .parse::() + .expect_err("Bad bud public key failed to raise error"); + assert!( + matches!(error, Error::KeyLength), + "expected invalid key length error, got {}", + error + ); + + let parsed_key = secret_key + .parse::() + .expect("Invalid test key"); + + let calculated_public_key = Secp256k1PublicKey::from(parsed_key); + assert_eq!(calculated_public_key.to_string(), public_key); + + let parsed_public_key = public_key + .parse::() + .expect("Invalid test pubkey"); + assert_eq!(calculated_public_key.0, parsed_public_key.0); + } +} diff --git a/stratum-apps/src/key_utils/mod.rs b/stratum-apps/src/key_utils/mod.rs index 1e6cabb83..5fb13c039 100644 --- a/stratum-apps/src/key_utils/mod.rs +++ b/stratum-apps/src/key_utils/mod.rs @@ -1,265 +1,20 @@ -#![cfg_attr(not(feature = "std"), no_std)] - -extern crate alloc; - -use alloc::{ - string::{String, ToString}, - vec::Vec, -}; -use bs58::{decode, decode::Error as Bs58DecodeError}; -use core::{convert::TryFrom, fmt::Display, str::FromStr}; -use secp256k1::{ - Keypair, Message as SecpMessage, Secp256k1, SecretKey, SignOnly, VerifyOnly, XOnlyPublicKey, - schnorr::Signature, -}; -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); - -impl TryFrom for Secp256k1SecretKey { - type Error = Error; - - fn try_from(value: String) -> Result { - value.parse() - } -} - -impl FromStr for Secp256k1SecretKey { - type Err = Error; - - fn from_str(value: &str) -> Result { - let decoded = decode(value).with_check(None).into_vec()?; - let secret = SecretKey::from_slice(&decoded)?; - Ok(Secp256k1SecretKey(secret)) - } -} - -impl From for String { - fn from(secret: Secp256k1SecretKey) -> Self { - secret.to_string() - } -} - -impl Display for Secp256k1SecretKey { - fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { - let bytes = self.0.secret_bytes(); - f.write_str(&bs58::encode(bytes).with_check().into_string()) - } -} - -#[derive(Debug, Copy, Clone, Serialize, Deserialize)] -#[serde(into = "String", try_from = "String")] -pub struct Secp256k1PublicKey(pub XOnlyPublicKey); - -impl TryFrom for Secp256k1PublicKey { - type Error = Error; - - fn try_from(value: String) -> Result { - value.parse() - } -} - -impl FromStr for Secp256k1PublicKey { - type Err = Error; - - fn from_str(value: &str) -> Result { - let decoded = decode(value).with_check(None).into_vec()?; - if decoded.len() < 34 { - return Err(Error::KeyLength); - } - let key_version = - u16::from_le_bytes(decoded[..2].try_into().expect("Invalid array length")); - if key_version != 1 { - return Err(Error::KeyVersion(key_version)); - } - let public = XOnlyPublicKey::from_slice(&decoded[2..]).map_err(Error::Secp256k1)?; - Ok(Secp256k1PublicKey(public)) - } -} - -impl From for String { - fn from(public: Secp256k1PublicKey) -> Self { - public.to_string() - } -} - -impl Display for Secp256k1PublicKey { - fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { - let mut output = [0_u8; 34]; - output[0] = 1; - let bytes = self.0.serialize(); - output[2..].copy_from_slice(&bytes); - f.write_str(&bs58::encode(&output).with_check().into_string()) - } -} - -impl Secp256k1PublicKey { - pub fn into_bytes(self) -> [u8; 32] { - self.0.serialize() - } -} -impl Secp256k1SecretKey { - pub fn into_bytes(self) -> [u8; 32] { - self.0.secret_bytes() - } -} - -impl From for Secp256k1PublicKey { - fn from(value: Secp256k1SecretKey) -> Self { - let context = secp256k1::Secp256k1::new(); - let (x_coordinate, _) = value.0.public_key(&context).x_only_public_key(); - Self(x_coordinate) - } -} - -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::*; - - #[test] - fn key_conversions() { - let secret_key = "zmBEmPhqo3A92FkiLVvyCz6htc3e53ph3ZbD4ASqGaLjwnFLi"; - let public_key = "9bDuixKmZqAJnrmP746n8zU1wyAQRrus7th9dxnkPg6RzQvCnan"; - let bad_public_key1 = "9bDuixKmZqAJnrmP746n8zU1wyAQRrus7th9dxnkPg6RzQvCnam"; // invalid checksum (swapped char) - let bad_public_key2 = "2myPhc5vkPzuC5FXNK5tee79WmP7uoLh55SxezoF8iqwF3E3rnPY"; // invalid version (version 12) - let bad_public_key3 = "2wmHTKZkLg2QzXyEXGMBXzKP7JXDUt8yy9SA5hoQwERc92qR6c"; // invalid length (1 B missing) - - let error = bad_public_key1 - .parse::() - .expect_err("Bad bud public key failed to raise error"); - assert!( - matches!(error, Error::Bs58Decode(_)), - "expected failed checksum error, got {}", - error - ); - let error = bad_public_key2 - .parse::() - .expect_err("Bad bud public key failed to raise error"); - assert!( - matches!(error, Error::KeyVersion(_)), - "expected invalid key version error, got {}", - error - ); - let error = bad_public_key3 - .parse::() - .expect_err("Bad bud public key failed to raise error"); - assert!( - matches!(error, Error::KeyLength), - "expected invalid key length error, got {}", - error - ); - - let parsed_key = secret_key - .parse::() - .expect("Invalid test key"); - - let calculated_public_key = Secp256k1PublicKey::from(parsed_key); - assert_eq!(calculated_public_key.to_string(), public_key); - - let parsed_public_key = public_key - .parse::() - .expect("Invalid test pubkey"); - assert_eq!(calculated_public_key.0, parsed_public_key.0); - } -} +//! 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::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; 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() + } +} diff --git a/stratum-apps/src/network_helpers/mod.rs b/stratum-apps/src/network_helpers/mod.rs index 3b47f6460..2890aa739 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,24 +14,20 @@ 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}; -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)] @@ -49,6 +46,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 +72,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}"), } } @@ -114,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) @@ -134,20 +135,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) diff --git a/stratum-apps/src/network_helpers/noise_connection.rs b/stratum-apps/src/network_helpers/noise_connection.rs index df54f5ae9..8ab7653cd 100644 --- a/stratum-apps/src/network_helpers/noise_connection.rs +++ b/stratum-apps/src/network_helpers/noise_connection.rs @@ -167,18 +167,17 @@ 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 that authority. + const AUTHORITY_PUBLIC: &str = "9auqWEzQDVyd2oe1JVGFLMLHZtCo2FFqZwtKA5gd9xbuEu7PH72"; + const STATIC_KEY: &str = "2Zdzjqd9c7EB4C9FBuqyDNzErruL4DNrJHoL5jhdE6QVArUTR8"; + const CERTIFICATE: &str = "11HpWbvGUzBwSTTVZMX6Dc1bVAupxFfvzkFqWfcQzXwVWWeCFQ6rQTDtrNbv4ncSx11gBb1trRbuhuCuXNptqbQBHnyx4VJKULV9e4AWew"; #[tokio::test] async fn cancellation_shuts_down_connection() { @@ -187,11 +186,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, @@ -202,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 new file mode 100644 index 000000000..820460403 --- /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, 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(); + } +} 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 {