diff --git a/Cargo.lock b/Cargo.lock index 58a34da8dd..5e9c64cb60 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -250,7 +250,7 @@ dependencies = [ [[package]] name = "channels_sv2" -version = "9.0.0" +version = "10.0.0" dependencies = [ "binary_sv2", "bitcoin", @@ -1162,7 +1162,7 @@ checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" [[package]] name = "stratum-core" -version = "0.7.0" +version = "0.8.0" dependencies = [ "binary_sv2", "bitcoin", @@ -1184,7 +1184,7 @@ dependencies = [ [[package]] name = "stratum_translation" -version = "0.6.0" +version = "0.7.0" dependencies = [ "binary_sv2", "bitcoin", diff --git a/stratum-core/Cargo.toml b/stratum-core/Cargo.toml index a04da46d3b..657dbb8854 100644 --- a/stratum-core/Cargo.toml +++ b/stratum-core/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "stratum-core" -version = "0.7.0" +version = "0.8.0" authors = ["The Stratum V2 Developers"] edition = "2021" readme = "README.md" @@ -20,13 +20,13 @@ framing_sv2 = { path = "../sv2/framing-sv2", version = "^9.0.0" } noise_sv2 = { path = "../sv2/noise-sv2", version = "^2.1.0" } parsers_sv2 = { path = "../sv2/parsers-sv2", version = "^0.7.0" } handlers_sv2 = { path = "../sv2/handlers-sv2", version = "^0.7.0" } -channels_sv2 = { path = "../sv2/channels-sv2", version = "^9.0.0" } +channels_sv2 = { path = "../sv2/channels-sv2", version = "^10.0.0" } common_messages_sv2 = { path = "../sv2/subprotocols/common-messages", version = "^10.0.0" } mining_sv2 = { path = "../sv2/subprotocols/mining", version = "^13.0.0" } template_distribution_sv2 = { path = "../sv2/subprotocols/template-distribution", version = "^8.0.0" } job_declaration_sv2 = { path = "../sv2/subprotocols/job-declaration", version = "^11.0.0" } sv1_api = { path = "../sv1", version = "^7.0.0", optional = true } -stratum_translation = { path = "stratum-translation", version = "^0.6.0", optional = true } +stratum_translation = { path = "stratum-translation", version = "^0.7.0", optional = true } bitcoin = { workspace = true } [features] diff --git a/stratum-core/stratum-translation/Cargo.toml b/stratum-core/stratum-translation/Cargo.toml index eb3f1644b4..c5e635f9d7 100644 --- a/stratum-core/stratum-translation/Cargo.toml +++ b/stratum-core/stratum-translation/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "stratum_translation" -version = "0.6.0" +version = "0.7.0" edition = "2021" license = "MIT OR Apache-2.0" description = "Stratum V1 ↔ Stratum V2 translation utilities for reuse across proxies, apps, and firmware" @@ -12,7 +12,7 @@ path = "src/lib.rs" [dependencies] binary_sv2 = { path = "../../sv2/binary-sv2", version = "^8.0.0" } mining_sv2 = { path = "../../sv2/subprotocols/mining", version = "^13.0.0" } -channels_sv2 = { path = "../../sv2/channels-sv2", version = "^9.0.0" } +channels_sv2 = { path = "../../sv2/channels-sv2", version = "^10.0.0" } v1 = { path = "../../sv1", package = "sv1_api", version = "^7.0.0" } tracing = { workspace = true } bitcoin = { workspace = true } diff --git a/sv2/channels-sv2/Cargo.toml b/sv2/channels-sv2/Cargo.toml index 6aa2b4e73f..9719d5298f 100644 --- a/sv2/channels-sv2/Cargo.toml +++ b/sv2/channels-sv2/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "channels_sv2" -version = "9.0.0" +version = "10.0.0" authors = ["The Stratum V2 Developers"] edition = "2021" readme = "README.md" diff --git a/sv2/channels-sv2/src/client/error.rs b/sv2/channels-sv2/src/client/error.rs index 84d617c018..e84bfb3dc9 100644 --- a/sv2/channels-sv2/src/client/error.rs +++ b/sv2/channels-sv2/src/client/error.rs @@ -34,6 +34,9 @@ pub enum ExtendedChannelError { /// An immediately-active job carried an `ntime_start` below the `ntime_start` of the chain tip /// it is mined against; the job is discarded and the channel left unchanged. JobNtimeStartBelowChainTip, + /// The assembled coinbase `scriptSig` would exceed the size mandated by Bitcoin consensus + /// rules (see [`MAX_SCRIPT_SIG_SIZE`](crate::MAX_SCRIPT_SIG_SIZE)). + ScriptSigSizeTooLarge, } /// Errors that can occur within a **standard channel** context. diff --git a/sv2/channels-sv2/src/client/extended.rs b/sv2/channels-sv2/src/client/extended.rs index 367ca742f3..5ecd19f797 100644 --- a/sv2/channels-sv2/src/client/extended.rs +++ b/sv2/channels-sv2/src/client/extended.rs @@ -15,7 +15,7 @@ use crate::{ extranonce_manager::{prefix::RetiredExtranoncePrefixes, ExtranoncePrefix}, merkle_root::merkle_root_from_path, target::{bytes_to_hex, u256_to_block_hash}, - MAX_EXTRANONCE_LEN, MAX_FUTURE_BLOCK_TIME, VERSION_ROLLING_MASK, + MAX_EXTRANONCE_LEN, MAX_FUTURE_BLOCK_TIME, MAX_SCRIPT_SIG_SIZE, VERSION_ROLLING_MASK, }; use alloc::{collections::VecDeque, format, string::String, vec, vec::Vec}; use binary_sv2::Sv2OptionOwned; @@ -533,6 +533,10 @@ impl ExtendedChannel { /// The previous active job (if any) moves to the past jobs list. At most [`MAX_PAST_JOBS`] /// past jobs are kept: retiring one beyond that limit evicts the oldest. /// + /// Returns [`ExtendedChannelError::ScriptSigSizeTooLarge`] if the job's `coinbase_prefix` and + /// the full extranonce do not fit within [`MAX_SCRIPT_SIG_SIZE`], leaving the channel + /// unchanged. + /// /// To be used by a Sv2 Job Declarator Client pub fn on_set_custom_mining_job_success( &mut self, @@ -560,6 +564,17 @@ impl ExtendedChannel { return Err(ExtendedChannelError::ChainTipMismatch); } + // the caller passes the SetCustomMiningJob it sent, which is not necessarily one built by + // JobFactory::new_custom_job, so the scriptSig budget is checked here too. an oversized + // prefix would otherwise yield a consensus-invalid coinbase, and past 252 bytes it would + // also break the one-byte CompactSize assumption the prefix/suffix split below relies + // on, silently mis-slicing the coinbase. + let full_extranonce_size = self.get_full_extranonce_size(); + if set_custom_mining_job.coinbase_prefix.len() + full_extranonce_size > MAX_SCRIPT_SIG_SIZE + { + return Err(ExtendedChannelError::ScriptSigSizeTooLarge); + } + let deserialized_outputs = Vec::::consensus_decode( &mut set_custom_mining_job .coinbase_tx_outputs @@ -570,7 +585,6 @@ impl ExtendedChannel { let mut script_sig = vec![]; script_sig.extend_from_slice(set_custom_mining_job.coinbase_prefix.as_bytes()); - let full_extranonce_size = self.get_full_extranonce_size(); let full_extranonce = vec![0; full_extranonce_size]; script_sig.extend_from_slice(&full_extranonce); @@ -590,6 +604,9 @@ impl ExtendedChannel { let serialized_coinbase = serialize(&coinbase); + // the coinbase scriptSig is limited to 100 bytes by Bitcoin consensus rules, which is + // always below the 253 byte threshold where CompactSize switches from a 1-byte to a + // 3-byte encoding, so the script length prefix is unconditionally 1 byte let prefix_index = 4 // tx version + marker_flag_len(&coinbase.input[0].witness) // segwit marker and flag, if any + 1 // number of inputs @@ -1050,6 +1067,7 @@ mod tests { extranonce_manager::{ ExtranonceAllocator, ExtranonceAllocatorError, ExtranoncePrefix, MAX_EXTRANONCE_LEN, }, + MAX_SCRIPT_SIG_SIZE, }; use binary_sv2::Sv2OptionOwned as Sv2Option; use bitcoin::{ @@ -1064,6 +1082,91 @@ mod tests { }; use std::convert::TryInto; + #[test] + fn test_custom_job_success_rejects_oversized_script_sig() { + // the scriptSig is the custom job's coinbase_prefix followed by the full extranonce, and + // must fit within MAX_SCRIPT_SIG_SIZE. past 252 bytes its length prefix would also take + // three bytes, so the prefix/suffix split would land two bytes early. + let full_extranonce_size = 32; + let mut channel = ExtendedChannel::new( + 1, + "user_identity".to_string(), + ExtranoncePrefix::from_wire(vec![1; 24]).unwrap(), + Target::from_le_bytes([0xff; 32]), + 1.0, + true, + (full_extranonce_size - 24) as u16, + None, + ) + .unwrap(); + assert_eq!(channel.get_full_extranonce_size(), full_extranonce_size); + channel + .on_chain_tip_update(ChainTip::new([0u8; 32].into(), 503543726, 1746839905)) + .unwrap(); + + let mut script_bytes = vec![0]; // SegWit version 0 + script_bytes.push(20); // Push 20 bytes (length of pubkey hash) + script_bytes.extend_from_slice(&[ + 235, 225, 183, 220, 194, 147, 204, 170, 14, 231, 67, 168, 111, 137, 223, 130, 88, 194, + 8, 252, + ]); + let coinbase_outputs = vec![TxOut { + value: Amount::from_sat(5_000_000_000), + script_pubkey: ScriptBuf::from(script_bytes), + }]; + + let mut on_custom_job = |coinbase_prefix_len: usize, job_id: u32| { + let set_custom_mining_job = SetCustomMiningJob { + channel_id: 1, + request_id: job_id, + token: vec![0].try_into().unwrap(), + version: 536870912, + prev_hash: [0u8; 32].into(), + ntime_start: 1746839905, + nbits: 503543726, + coinbase_tx_version: 2, + coinbase_prefix: vec![0xab; coinbase_prefix_len].try_into().unwrap(), + coinbase_tx_input_n_sequence: 4294967295, + coinbase_tx_outputs: serialize(&coinbase_outputs).try_into().unwrap(), + coinbase_tx_locktime: 0, + merkle_path: vec![].try_into().unwrap(), + }; + let set_custom_mining_job_success = SetCustomMiningJobSuccess { + channel_id: 1, + request_id: job_id, + job_id, + }; + channel + .on_set_custom_mining_job_success( + set_custom_mining_job, + set_custom_mining_job_success, + ) + .map(|_| channel.get_active_job().unwrap().job_message.job_id) + }; + + // a prefix that fills the budget exactly is accepted + assert_eq!( + on_custom_job(MAX_SCRIPT_SIG_SIZE - full_extranonce_size, 1).unwrap(), + 1 + ); + + // one byte over is a consensus-invalid coinbase + assert!(matches!( + on_custom_job(MAX_SCRIPT_SIG_SIZE - full_extranonce_size + 1, 2), + Err(ExtendedChannelError::ScriptSigSizeTooLarge) + )); + + // 252 + 32 = 284 bytes would also need a three-byte length prefix + assert!(matches!( + on_custom_job(252, 3), + Err(ExtendedChannelError::ScriptSigSizeTooLarge) + )); + + // the rejected jobs left the channel unchanged + assert_eq!(channel.get_active_job().unwrap().job_message.job_id, 1); + assert_eq!(channel.get_past_jobs_count(), 0); + } + #[test] fn upstream_prefix_update_only_affects_subsequent_jobs() { // upstream(1) + local_prefix(1) + local_index(1) + rollable(2) = 5 diff --git a/sv2/channels-sv2/src/lib.rs b/sv2/channels-sv2/src/lib.rs index d8290f2117..e8c4b90165 100644 --- a/sv2/channels-sv2/src/lib.rs +++ b/sv2/channels-sv2/src/lib.rs @@ -42,6 +42,14 @@ pub const VERSION_ROLLING_MASK: u32 = 0x1fffffe0; /// share rolled from the wire value, which is why a prebuilt job carries its own `ntime_start`. pub const MAX_FUTURE_BLOCK_TIME: u32 = 2 * 60 * 60; +/// Maximum size, in bytes, of a coinbase transaction `scriptSig`, as mandated by Bitcoin +/// consensus rules. +/// +/// It also keeps the `scriptSig` length prefix at one byte: CompactSize only switches from a +/// 1-byte to a 3-byte encoding at 253, so the coinbase prefix/suffix split indexes can count the +/// length prefix as a single byte. +pub const MAX_SCRIPT_SIG_SIZE: usize = 100; + /// Worst-case chain-tip lifetime, in minutes, assumed when bounding the accepted-share dedup /// cache (`seen_shares`). /// diff --git a/sv2/channels-sv2/src/server/extended.rs b/sv2/channels-sv2/src/server/extended.rs index 61d88b64b3..89ef5eb402 100644 --- a/sv2/channels-sv2/src/server/extended.rs +++ b/sv2/channels-sv2/src/server/extended.rs @@ -1259,13 +1259,13 @@ mod tests { jobs::{ error::JobFactoryError, extended::ExtendedJob, - factory::{MAX_COINBASE_PREFIX_SIZE, MAX_SCRIPT_SIG_SIZE}, + factory::MAX_COINBASE_PREFIX_SIZE, job_store::{MAX_FUTURE_JOBS, MAX_PAST_JOBS}, JobOrigin, PrebuiltJob, }, share_accounting::{ShareValidationError, ShareValidationResult}, }, - MAX_EXTRANONCE_LEN, + MAX_EXTRANONCE_LEN, MAX_SCRIPT_SIG_SIZE, }; use binary_sv2::{Sv2OptionOwned as Sv2Option, U256Owned as U256}; use bitcoin::{ diff --git a/sv2/channels-sv2/src/server/group.rs b/sv2/channels-sv2/src/server/group.rs index 82fd1b46c8..14d9710a6b 100644 --- a/sv2/channels-sv2/src/server/group.rs +++ b/sv2/channels-sv2/src/server/group.rs @@ -476,12 +476,11 @@ mod tests { error::GroupChannelError, group::GroupChannel, jobs::{ - error::JobFactoryError, - factory::{MAX_COINBASE_PREFIX_SIZE, MAX_SCRIPT_SIG_SIZE}, - job_store::MAX_FUTURE_JOBS, - JobOrigin, PrebuiltJob, + error::JobFactoryError, factory::MAX_COINBASE_PREFIX_SIZE, + job_store::MAX_FUTURE_JOBS, JobOrigin, PrebuiltJob, }, }, + MAX_SCRIPT_SIG_SIZE, }; use binary_sv2::Sv2OptionOwned as Sv2Option; use bitcoin::{transaction::TxOut, Amount, ScriptBuf}; diff --git a/sv2/channels-sv2/src/server/jobs/factory.rs b/sv2/channels-sv2/src/server/jobs/factory.rs index 9e09b36e91..c6a075576c 100644 --- a/sv2/channels-sv2/src/server/jobs/factory.rs +++ b/sv2/channels-sv2/src/server/jobs/factory.rs @@ -30,6 +30,7 @@ use crate::{ merkle_root::merkle_root_from_path, outputs::deserialize_template_outputs, server::jobs::{error::*, extended::ExtendedJob, standard::StandardJob, PrebuiltJob}, + MAX_SCRIPT_SIG_SIZE, }; use binary_sv2::{B0255Owned, Sv2OptionOwned}; use bitcoin::{ @@ -42,10 +43,6 @@ use mining_sv2::{NewExtendedMiningJobOwned, NewMiningJobOwned, SetCustomMiningJo use std::convert::TryInto; use template_distribution_sv2::NewTemplateOwned; -/// Maximum size, in bytes, of a coinbase transaction `scriptSig`, as mandated by Bitcoin -/// consensus rules. -pub const MAX_SCRIPT_SIG_SIZE: usize = 100; - /// Maximum number of bytes that [`NewTemplateOwned::coinbase_prefix`] is allowed to contribute to /// the coinbase `scriptSig`, as mandated by the Sv2 Template Distribution Protocol spec. /// diff --git a/sv2/channels-sv2/src/server/standard.rs b/sv2/channels-sv2/src/server/standard.rs index eadc95a8d0..58dff02ac8 100644 --- a/sv2/channels-sv2/src/server/standard.rs +++ b/sv2/channels-sv2/src/server/standard.rs @@ -1090,14 +1090,14 @@ mod tests { group::GroupChannel, jobs::{ error::JobFactoryError, - factory::{MAX_COINBASE_PREFIX_SIZE, MAX_SCRIPT_SIG_SIZE}, + factory::MAX_COINBASE_PREFIX_SIZE, job_store::{MAX_FUTURE_JOBS, MAX_PAST_JOBS}, JobOrigin, PrebuiltJob, }, share_accounting::{ShareValidationError, ShareValidationResult}, standard::StandardChannel, }, - MAX_EXTRANONCE_LEN, + MAX_EXTRANONCE_LEN, MAX_SCRIPT_SIG_SIZE, }; use binary_sv2::Sv2OptionOwned as Sv2Option; use bitcoin::{