use super::*;
fn authorize_raw(endpoint: &str, username: &str) -> Option<stratum::Message> {
let mut stream = TcpStream::connect(endpoint).unwrap();
let mut reader = BufReader::new(stream.try_clone().unwrap());
writeln!(
stream,
"{}",
serde_json::json!({
"id": 1,
"method": "mining.subscribe",
"params": [USER_AGENT],
})
)
.unwrap();
let mut line = String::new();
reader.read_line(&mut line).unwrap();
let response: stratum::Message = serde_json::from_str(&line).unwrap();
assert!(matches!(response, stratum::Message::Response { .. }));
writeln!(
stream,
"{}",
serde_json::json!({
"id": 2,
"method": "mining.authorize",
"params": [username, "x"],
})
)
.unwrap();
line.clear();
(reader.read_line(&mut line).unwrap() > 0).then(|| serde_json::from_str(&line).unwrap())
}
#[test]
#[timeout(90000)]
fn mine_to_pool() {
let bitcoind = bitcoind();
let pool = TestPool::spawn_with_args(&bitcoind, "--start-diff 0.00001");
let stratum_endpoint = pool.stratum_endpoint();
let miner = CommandBuilder::new(format!(
"miner --mode share-found --username {} {stratum_endpoint} --cpu-cores 1",
signet_username()
))
.spawn();
let stdout = miner.wait_with_output().unwrap();
let output =
serde_json::from_str::<Vec<Share>>(&String::from_utf8_lossy(&stdout.stdout)).unwrap();
assert_eq!(output.len(), 1);
}
#[tokio::test]
#[timeout(120000)]
async fn stratum_state_machine() {
let bitcoind = bitcoind();
let pool = TestPool::spawn_with_args(
&bitcoind,
"--start-diff 0.00001 --disable-bouncer --update-interval 120",
);
{
let client = pool.stratum_client().await;
client.connect().await.unwrap();
assert!(
client
.configure(vec!["unknown-extension".into()], None)
.await
.unwrap_err()
.to_string()
.contains("Unsupported extension")
);
assert_stratum_error(client.authorize().await, StratumError::MethodNotAllowed);
assert_stratum_error(
client
.submit(
JobId::new(0),
Extranonce::random(8),
Ntime::from(0),
Nonce::from(0),
None,
)
.await,
StratumError::Unauthorized,
);
}
{
let client = pool.stratum_client().await;
client.connect().await.unwrap();
client
.configure(
vec!["version-rolling".into()],
Some(Version::from_str("1fffe000").unwrap()),
)
.await
.unwrap();
client
.configure(
vec!["version-rolling".into()],
Some(Version::from_str("1fffe000").unwrap()),
)
.await
.unwrap();
assert_stratum_error(client.authorize().await, StratumError::MethodNotAllowed);
assert_stratum_error(
client
.submit(
JobId::new(0),
Extranonce::random(8),
Ntime::from(0),
Nonce::from(0),
None,
)
.await,
StratumError::Unauthorized,
);
}
{
let client = pool.stratum_client().await;
client.connect().await.unwrap();
let (subscribe, _, _) = client.subscribe().await.unwrap();
assert_eq!(subscribe.subscriptions.len(), 2);
let (configure, _, _) = client
.configure(
vec!["version-rolling".into()],
Some(Version::from_str("1fffe000").unwrap()),
)
.await
.unwrap();
assert!(configure.version_rolling);
assert_stratum_error(client.subscribe().await, StratumError::MethodNotAllowed);
assert_stratum_error(
client
.submit(
JobId::new(0),
Extranonce::random(8),
Ntime::from(0),
Nonce::from(0),
None,
)
.await,
StratumError::Unauthorized,
);
}
{
let client = pool.stratum_client().await;
let mut events = client.connect().await.unwrap();
let (subscribe_result, _, _) = client.subscribe().await.unwrap();
let enonce1 = subscribe_result.enonce1.clone();
let enonce2_size = subscribe_result.enonce2_size;
client.authorize().await.unwrap();
let (notify, difficulty) = wait_for_notify(&mut events).await;
assert_eq!(difficulty, Difficulty::from(0.00001));
assert_eq!(notify.job_id, JobId::from(0));
assert!(notify.clean_jobs);
assert_stratum_error(
client
.configure(
vec!["version-rolling".into()],
Some(Version::from_str("1fffe000").unwrap()),
)
.await,
StratumError::MethodNotAllowed,
);
let enonce2_for_state_check = Extranonce::random(enonce2_size);
let (ntime_check, nonce_check) =
solve_share(¬ify, &enonce1, &enonce2_for_state_check, difficulty);
client
.submit(
notify.job_id,
enonce2_for_state_check,
ntime_check,
nonce_check,
None,
)
.await
.unwrap();
assert_stratum_error(client.authorize().await, StratumError::MethodNotAllowed);
let enonce2 = Extranonce::random(enonce2_size);
let (ntime, nonce) = solve_share(¬ify, &enonce1, &enonce2, difficulty);
client
.submit(notify.job_id, enonce2, ntime, nonce, None)
.await
.unwrap();
}
{
let client = pool.stratum_client().await;
let mut events = client.connect().await.unwrap();
client
.configure(
vec!["version-rolling".into()],
Some(Version::from_str("1fffe000").unwrap()),
)
.await
.unwrap();
let (subscribe_result, _, _) = client.subscribe().await.unwrap();
let enonce1 = subscribe_result.enonce1.clone();
let enonce2_size = subscribe_result.enonce2_size;
client.authorize().await.unwrap();
let (notify, difficulty) = wait_for_notify(&mut events).await;
let enonce2 = Extranonce::random(enonce2_size);
let (ntime, nonce) = solve_share(¬ify, &enonce1, &enonce2, difficulty);
client
.submit(notify.job_id, enonce2, ntime, nonce, None)
.await
.unwrap();
assert_stratum_error(client.subscribe().await, StratumError::MethodNotAllowed);
}
let original_enonce1 = {
let client = pool.stratum_client().await;
let mut events = client.connect().await.unwrap();
let (subscribe_result, _, _) = client.subscribe().await.unwrap();
let enonce1 = subscribe_result.enonce1.clone();
client.authorize().await.unwrap();
let (notify, difficulty) = wait_for_notify(&mut events).await;
let enonce2 = Extranonce::random(subscribe_result.enonce2_size);
let (ntime, nonce) = solve_share(¬ify, &enonce1, &enonce2, difficulty);
client
.submit(notify.job_id, enonce2, ntime, nonce, None)
.await
.unwrap();
client.disconnect().await;
enonce1
};
tokio::time::sleep(Duration::from_millis(100)).await;
{
let client = pool.stratum_client().await;
let mut events = client.connect().await.unwrap();
let (subscribe_result, _, _) = client
.subscribe_with_enonce1(Some(original_enonce1.clone()))
.await
.unwrap();
assert_eq!(
subscribe_result.enonce1, original_enonce1,
"Session resumption should return the same enonce1"
);
client.authorize().await.unwrap();
let (notify, difficulty) = wait_for_notify(&mut events).await;
let enonce2 = Extranonce::random(subscribe_result.enonce2_size);
let (ntime, nonce) = solve_share(¬ify, &original_enonce1, &enonce2, difficulty);
client
.submit(notify.job_id, enonce2, ntime, nonce, None)
.await
.unwrap();
}
{
let client = pool.stratum_client().await;
client.connect().await.unwrap();
let fake_enonce1: Extranonce = "deadbeef".parse().unwrap();
let (subscribe_result, _, _) = client
.subscribe_with_enonce1(Some(fake_enonce1.clone()))
.await
.unwrap();
assert_ne!(
subscribe_result.enonce1, fake_enonce1,
"Unknown enonce1 should result in new enonce1 being issued"
);
client.authorize().await.unwrap();
}
{
let client_address_wrong_network = pool
.stratum_client_for_username("bc1qw508d6qejxtdg4y5r3zarvary0c5xw7kv8f3t4.worker")
.await;
client_address_wrong_network.connect().await.unwrap();
client_address_wrong_network.subscribe().await.unwrap();
assert!(authorize_raw(&pool.stratum_endpoint(), "notabitcoinaddress").is_none());
assert!(
client_address_wrong_network
.authorize()
.await
.unwrap_err()
.to_string()
.contains(
"bc1qw508d6qejxtdg4y5r3zarvary0c5xw7kv8f3t4 is not valid for signet network"
)
);
}
}
#[tokio::test]
#[timeout(180000)]
#[ignore]
#[serial(heavy)]
async fn clean_jobs_true_on_init_and_new_block() {
let bitcoind = bitcoind();
let pool = TestPool::spawn_with_args(&bitcoind, "--start-diff 0.0001");
let client = pool.stratum_client().await;
let mut events = client.connect().await.unwrap();
client.subscribe().await.unwrap();
client.authorize().await.unwrap();
let (notify, _) = wait_for_notify(&mut events).await;
assert!(notify.clean_jobs);
pool.mine_block().await;
let notify = wait_for_new_block(&mut events, notify.job_id).await;
assert!(notify.clean_jobs);
}
#[test]
#[timeout(90000)]
fn configure_template_update_interval() {
let bitcoind = bitcoind();
let pool = TestPool::spawn_with_args(&bitcoind, "--update-interval 1 --start-diff 0.00001");
let stratum_endpoint = pool.stratum_endpoint();
let output = CommandBuilder::new(format!(
"template {stratum_endpoint} --username {} --raw",
signet_username()
))
.spawn()
.wait_with_output()
.unwrap();
let t1 =
serde_json::from_str::<stratum::Notify>(&String::from_utf8_lossy(&output.stdout)).unwrap();
std::thread::sleep(Duration::from_secs(1));
let output = CommandBuilder::new(format!(
"template {stratum_endpoint} --username {} --raw",
signet_username()
))
.spawn()
.wait_with_output()
.unwrap();
let t2 =
serde_json::from_str::<stratum::Notify>(&String::from_utf8_lossy(&output.stdout)).unwrap();
assert!(t1.ntime < t2.ntime);
}
#[tokio::test]
#[timeout(180000)]
#[ignore]
#[serial(heavy)]
async fn concurrently_listening_workers_receive_new_templates_on_new_block() {
use std::sync::Barrier;
use std::time::Duration;
let bitcoind = bitcoind();
let pool = TestPool::spawn_with_args(&bitcoind, "--start-diff 0.0001");
let endpoint = pool.stratum_endpoint();
let user = signet_username();
let gate = Arc::new(Barrier::new(3));
let (out_1, mut in_1) = mpsc::channel(2);
let (out_2, mut in_2) = mpsc::channel(2);
for out in [out_1, out_2] {
let gate = gate.clone();
let endpoint = endpoint.clone();
let user = user.clone();
tokio::task::spawn_blocking(move || {
let mut template_watcher = CommandBuilder::new(format!(
"template {endpoint} --username {user} --watch --raw"
))
.spawn();
let mut reader = BufReader::new(template_watcher.stdout.take().unwrap());
let initial_template = next_json::<stratum::Notify>(&mut reader);
gate.wait();
let new_template = next_json::<stratum::Notify>(&mut reader);
out.blocking_send((initial_template, new_template)).ok();
template_watcher.kill().unwrap();
template_watcher.wait().unwrap();
});
}
gate.wait();
pool.mine_block().await;
let (initial_template_worker_a, new_template_worker_a) =
tokio::time::timeout(Duration::from_secs(10), in_1.recv())
.await
.unwrap()
.unwrap();
let (initial_template_worker_b, new_template_worker_b) =
tokio::time::timeout(Duration::from_secs(10), in_2.recv())
.await
.unwrap()
.unwrap();
assert_eq!(
initial_template_worker_a.prevhash,
initial_template_worker_b.prevhash
);
assert_ne!(
initial_template_worker_a.prevhash,
new_template_worker_a.prevhash
);
assert_ne!(
initial_template_worker_b.prevhash,
new_template_worker_b.prevhash,
);
assert_eq!(
new_template_worker_a.prevhash,
new_template_worker_b.prevhash
);
assert!(new_template_worker_a.ntime >= initial_template_worker_a.ntime);
assert!(new_template_worker_b.ntime >= initial_template_worker_b.ntime);
}
#[tokio::test]
#[timeout(120000)]
async fn vardiff_adjusts_difficulty() {
let bitcoind = bitcoind();
let pool = TestPool::spawn_with_args(
&bitcoind,
"--start-diff 0.00001 --vardiff-period 1 --vardiff-window 5 --disable-bouncer",
);
let client = pool.stratum_client().await;
let mut events = client.connect().await.unwrap();
let (subscribe, _, _) = client.subscribe().await.unwrap();
let enonce1 = subscribe.enonce1;
client.authorize().await.unwrap();
let (mut notify, initial_difficulty) = wait_for_notify(&mut events).await;
let old_job_id = notify.job_id;
let user_address = signet_username()
.address()
.clone()
.assume_checked()
.to_string();
let new_difficulty = mine_until_difficulty_increases(
&client,
&mut events,
&mut notify,
&enonce1,
subscribe.enonce2_size,
initial_difficulty,
)
.await;
assert!(new_difficulty > initial_difficulty);
bitcoind
.submit_premined_block()
.await
.expect("submit_premined_block failed");
timeout(Duration::from_secs(10), async {
loop {
match events.recv().await.unwrap() {
stratum::client::Event::Notify(n) if n.job_id != notify.job_id => break,
_ => {}
}
}
})
.await
.expect("Timeout waiting for new block notification");
let baseline = pool.get_user(&user_address).await.unwrap();
assert_stratum_error(
client
.submit(
old_job_id,
Extranonce::random(subscribe.enonce2_size),
Ntime::from(0),
Nonce::from(0),
None,
)
.await,
StratumError::Stale,
);
let after_stale = pool.get_user(&user_address).await.unwrap();
let stale_delta = (after_stale.stats.rejected_work - baseline.stats.rejected_work).as_f64();
assert_eq!(stale_delta, initial_difficulty.as_f64());
assert_stratum_error(
client
.submit_with_username(
"tb1qft5p2uhsdcdc3l2ua4ap5qqfg4pjaqlp250x7us7a8qqhrxrxfsqaqh7jw.different_worker"
.parse()
.unwrap(),
old_job_id,
Extranonce::random(subscribe.enonce2_size),
Ntime::from(0),
Nonce::from(0),
None,
)
.await,
StratumError::WorkerMismatch,
);
let after_mismatch = pool.get_user(&user_address).await.unwrap();
let mismatch_delta =
(after_mismatch.stats.rejected_work - after_stale.stats.rejected_work).as_f64();
assert_eq!(mismatch_delta, initial_difficulty.as_f64());
}
#[tokio::test]
#[timeout(120000)]
async fn new_job_shares_rejected_at_old_diff() {
let bitcoind = bitcoind();
let pool = TestPool::spawn_with_args(
&bitcoind,
"--start-diff 0.00001 --vardiff-period 1 --vardiff-window 5 --update-interval 1 --disable-bouncer",
);
let client = pool.stratum_client().await;
let mut events = client.connect().await.unwrap();
let (subscribe, _, _) = client.subscribe().await.unwrap();
let enonce1 = subscribe.enonce1;
client.authorize().await.unwrap();
let (mut notify, initial_difficulty) = wait_for_notify(&mut events).await;
mine_until_difficulty_increases(
&client,
&mut events,
&mut notify,
&enonce1,
subscribe.enonce2_size,
initial_difficulty,
)
.await;
let new_notify = timeout(Duration::from_secs(10), async {
loop {
match events.recv().await {
Ok(stratum::client::Event::Notify(n)) if n.job_id != notify.job_id => return n,
Ok(_) => continue,
Err(e) => panic!("Event channel closed: {:?}", e),
}
}
})
.await
.expect("Timeout waiting for new job after difficulty change");
let mut got_above_target = false;
for _ in 0..20 {
match submit_share(
&client,
&new_notify,
&enonce1,
subscribe.enonce2_size,
initial_difficulty,
)
.await
{
Err(ClientError::Stratum { response })
if response.error_code == StratumError::AboveTarget as i32 =>
{
got_above_target = true;
break;
}
Err(ClientError::Stratum { response })
if response.error_code == StratumError::Duplicate as i32 =>
{
continue;
}
Ok(_) => continue,
Err(e) => panic!("Unexpected error: {:?}", e),
}
}
assert!(got_above_target);
}
#[tokio::test]
#[timeout(90000)]
async fn share_validation() {
let bitcoind = bitcoind();
let pool = TestPool::spawn_with_args(
&bitcoind,
"--start-diff 0.000001 --disable-bouncer --update-interval 5",
);
let status = pool.get_status().await.unwrap();
assert_eq!(status.downstream.user_count, 0);
assert_eq!(status.downstream.worker_count, 0);
assert_eq!(status.downstream.session_count, 0);
assert_eq!(status.block_count, 0);
assert_eq!(status.downstream.stats.accepted_shares, 0);
assert_eq!(status.downstream.stats.rejected_shares, 0);
assert!(status.downstream.stats.best_share.is_none());
assert!(status.downstream.stats.last_share.is_none());
let system_status = pool.get_system_status().await.unwrap();
assert!(system_status.cpu_usage_percent >= 0.0 && system_status.cpu_usage_percent <= 100.0);
assert!(
system_status.memory_usage_percent >= 0.0 && system_status.memory_usage_percent <= 100.0
);
assert!(system_status.disk_usage_percent >= 0.0 && system_status.disk_usage_percent <= 100.0);
assert!(system_status.uptime > 0);
let bitcoin_status = pool.get_bitcoin_status().await.unwrap();
assert!(bitcoin_status.network_difficulty.as_f64() > 0.0);
let client = pool.stratum_client().await;
let mut events = client.connect().await.unwrap();
let (subscribe, _, _) = client.subscribe().await.unwrap();
let enonce1 = subscribe.enonce1;
let enonce2_size = subscribe.enonce2_size;
client.authorize().await.unwrap();
let (notify, difficulty) = wait_for_notify(&mut events).await;
let username = signet_username();
let user_address = username.address().clone().assume_checked().to_string();
let enonce2 = Extranonce::random(enonce2_size);
let (ntime, nonce) = solve_share(¬ify, &enonce1, &enonce2, difficulty);
client
.submit(notify.job_id, enonce2.clone(), ntime, nonce, None)
.await
.unwrap();
let status = pool.get_status().await.unwrap();
assert_eq!(status.downstream.user_count, 1);
assert_eq!(status.downstream.worker_count, 1);
assert_eq!(status.downstream.session_count, 1);
assert_eq!(status.downstream.stats.accepted_shares, 1);
assert_eq!(status.downstream.stats.rejected_shares, 0);
assert!(status.downstream.stats.best_share.is_some());
assert!(status.downstream.stats.last_share.is_some());
let user = pool.get_user(&user_address).await.unwrap();
assert_eq!(
user.address.clone().assume_checked().to_string(),
user_address
);
assert_eq!(user.stats.accepted_shares, 1);
assert_eq!(user.stats.rejected_shares, 0);
assert!(user.stats.best_share.is_some());
assert!(user.stats.last_share.is_some());
assert_eq!(user.workers.len(), 1);
assert_eq!(user.workers[0].stats.accepted_shares, 1);
assert_eq!(user.workers[0].stats.rejected_shares, 0);
assert!(user.workers[0].stats.best_share.is_some());
assert!(user.workers[0].stats.last_share.is_some());
assert_stratum_error(
client
.submit(notify.job_id, enonce2, ntime, nonce, None)
.await,
StratumError::Duplicate,
);
let status = pool.get_status().await.unwrap();
assert_eq!(status.downstream.stats.accepted_shares, 1);
assert_eq!(status.downstream.stats.rejected_shares, 1);
let user = pool.get_user(&user_address).await.unwrap();
assert_eq!(user.stats.accepted_shares, 1);
assert_eq!(user.stats.rejected_shares, 1);
assert_eq!(user.workers[0].stats.accepted_shares, 1);
assert_eq!(user.workers[0].stats.rejected_shares, 1);
assert_stratum_error(
client
.submit(
notify.job_id,
Extranonce::random(enonce2_size - 1),
ntime,
nonce,
None,
)
.await,
StratumError::InvalidNonce2Length,
);
let status = pool.get_status().await.unwrap();
assert_eq!(status.downstream.stats.accepted_shares, 1);
assert_eq!(status.downstream.stats.rejected_shares, 2);
assert_stratum_error(
client
.submit(
notify.job_id,
Extranonce::random(enonce2_size + 1),
ntime,
nonce,
None,
)
.await,
StratumError::InvalidNonce2Length,
);
let status = pool.get_status().await.unwrap();
assert_eq!(status.downstream.stats.accepted_shares, 1);
assert_eq!(status.downstream.stats.rejected_shares, 3);
assert_stratum_error(
client
.submit(
JobId::from(0xdeadbeef),
Extranonce::random(enonce2_size),
ntime,
nonce,
None,
)
.await,
StratumError::Stale,
);
let status = pool.get_status().await.unwrap();
assert_eq!(status.downstream.stats.accepted_shares, 1);
assert_eq!(status.downstream.stats.rejected_shares, 4);
assert_stratum_error(
client
.submit(
notify.job_id,
Extranonce::random(enonce2_size),
notify.ntime,
Nonce::from(0),
None,
)
.await,
StratumError::AboveTarget,
);
let status = pool.get_status().await.unwrap();
assert_eq!(status.downstream.stats.accepted_shares, 1);
assert_eq!(status.downstream.stats.rejected_shares, 5);
assert_stratum_error(
client
.submit_with_username(
"tb1qft5p2uhsdcdc3l2ua4ap5qqfg4pjaqlp250x7us7a8qqhrxrxfsqaqh7jw.different_worker"
.parse()
.unwrap(),
notify.job_id,
Extranonce::random(enonce2_size),
notify.ntime,
Nonce::from(0),
None,
)
.await,
StratumError::WorkerMismatch,
);
let status = pool.get_status().await.unwrap();
assert_eq!(status.downstream.stats.accepted_shares, 1);
assert_eq!(status.downstream.stats.rejected_shares, 6);
let user = pool.get_user(&user_address).await.unwrap();
assert_eq!(user.stats.accepted_shares, 1);
assert_eq!(user.stats.rejected_shares, 6);
let job_ntime: u32 = notify.ntime.into();
assert_stratum_error(
client
.submit(
notify.job_id,
Extranonce::random(enonce2_size),
Ntime::from(job_ntime - 1),
Nonce::from(0),
None,
)
.await,
StratumError::NtimeOutOfRange,
);
let status = pool.get_status().await.unwrap();
assert_eq!(status.downstream.stats.accepted_shares, 1);
assert_eq!(status.downstream.stats.rejected_shares, 7);
assert_stratum_error(
client
.submit(
notify.job_id,
Extranonce::random(enonce2_size),
Ntime::from(job_ntime + 7001),
Nonce::from(0),
None,
)
.await,
StratumError::NtimeOutOfRange,
);
let status = pool.get_status().await.unwrap();
assert_eq!(status.downstream.stats.accepted_shares, 1);
assert_eq!(status.downstream.stats.rejected_shares, 8);
let user = pool.get_user(&user_address).await.unwrap();
assert_eq!(user.stats.accepted_shares, 1);
assert_eq!(user.stats.rejected_shares, 8);
let enonce2_vr = Extranonce::random(enonce2_size);
let (ntime_vr, nonce_vr) = solve_share(¬ify, &enonce1, &enonce2_vr, difficulty);
assert_stratum_error(
client
.submit(
notify.job_id,
enonce2_vr,
ntime_vr,
nonce_vr,
Some(Version::from_str("00100000").unwrap()),
)
.await,
StratumError::InvalidVersionMask,
);
let status = pool.get_status().await.unwrap();
assert_eq!(status.downstream.stats.accepted_shares, 1);
assert_eq!(status.downstream.stats.rejected_shares, 9);
let old_job_id = notify.job_id;
let fresh_enonce2 = Extranonce::random(enonce2_size);
let (old_ntime, old_nonce) = solve_share(¬ify, &enonce1, &fresh_enonce2, difficulty);
bitcoind
.submit_premined_block()
.await
.expect("submit_premined_block failed");
timeout(Duration::from_secs(10), async {
loop {
match events.recv().await.unwrap() {
stratum::client::Event::Notify(n) if n.job_id != old_job_id => break,
_ => {}
}
}
})
.await
.expect("Timeout waiting for new block notification");
let baseline = pool.get_status().await.unwrap();
let user_baseline = pool.get_user(&user_address).await.unwrap();
assert_stratum_error(
client
.submit(old_job_id, fresh_enonce2, old_ntime, old_nonce, None)
.await,
StratumError::Stale,
);
let status = pool.get_status().await.unwrap();
assert_eq!(
status.downstream.stats.rejected_shares,
baseline.downstream.stats.rejected_shares + 1
);
let user = pool.get_user(&user_address).await.unwrap();
assert_eq!(
user.stats.rejected_shares,
user_baseline.stats.rejected_shares + 1
);
assert_eq!(
user.workers[0].stats.rejected_shares,
user_baseline.workers[0].stats.rejected_shares + 1
);
{
let client = pool.stratum_client().await;
let mut events = client.connect().await.unwrap();
let (configure_response, _, _) = client
.configure(
vec!["version-rolling".into()],
Some(Version::from_str("1fffe000").unwrap()),
)
.await
.unwrap();
assert!(configure_response.version_rolling);
assert_eq!(
configure_response.version_rolling_mask,
Some(Version::from_str("1fffe000").unwrap())
);
let (subscribe, _, _) = client.subscribe().await.unwrap();
let enonce1 = subscribe.enonce1;
let enonce2_size = subscribe.enonce2_size;
client.authorize().await.unwrap();
let (notify, difficulty) = wait_for_notify(&mut events).await;
let version_mask = Version::from_str("1fffe000").unwrap();
let version_bits_valid = Version::from_str("00100000").unwrap();
let enonce2_valid = Extranonce::random(enonce2_size);
let (ntime_valid, nonce_valid) = solve_share_with_version_bits(
¬ify,
&enonce1,
&enonce2_valid,
difficulty,
Some(version_bits_valid),
Some(version_mask),
);
client
.submit(
notify.job_id,
enonce2_valid,
ntime_valid,
nonce_valid,
Some(version_bits_valid),
)
.await
.unwrap();
let enonce2_zero = Extranonce::random(enonce2_size);
let (ntime_zero, nonce_zero) = solve_share(¬ify, &enonce1, &enonce2_zero, difficulty);
client
.submit(
notify.job_id,
enonce2_zero,
ntime_zero,
nonce_zero,
Some(Version::from(0)),
)
.await
.unwrap();
assert_stratum_error(
client
.submit(
notify.job_id,
Extranonce::random(enonce2_size),
notify.ntime,
Nonce::from(0),
Some(Version::from_str("e0000000").unwrap()),
)
.await,
StratumError::InvalidVersionMask,
);
}
}
#[tokio::test]
#[timeout(90000)]
async fn bouncer() {
let bitcoind = bitcoind();
let pool = TestPool::spawn_with_args(&bitcoind, "--start-diff 0.00001 --update-interval 120");
let auth_timeout_test = async {
let client = pool.stratum_client().await;
let _events = client.connect().await.unwrap();
client.subscribe().await.unwrap();
tokio::time::sleep(Duration::from_secs(4)).await;
let result = client.authorize().await;
assert!(
result.is_err(),
"auth_timeout: Expected connection to be dropped after AUTH_TIMEOUT"
);
};
let idle_timeout_test = async {
let client = pool.stratum_client().await;
let mut events = client.connect().await.unwrap();
let (subscribe, _, _) = client.subscribe().await.unwrap();
let enonce1 = subscribe.enonce1;
let enonce2_size = subscribe.enonce2_size;
client.authorize().await.unwrap();
let (notify, difficulty) = wait_for_notify(&mut events).await;
let enonce2 = Extranonce::random(enonce2_size);
let (ntime, nonce) = solve_share(¬ify, &enonce1, &enonce2, difficulty);
client
.submit(notify.job_id, enonce2, ntime, nonce, None)
.await
.unwrap();
tokio::time::sleep(Duration::from_secs(8)).await;
let result = client
.submit(
notify.job_id,
Extranonce::random(enonce2_size),
ntime,
nonce,
None,
)
.await;
assert!(
result.is_err(),
"idle_timeout: Expected connection to be dropped after IDLE_TIMEOUT"
);
};
let reject_escalation_test = async {
let client = pool.stratum_client().await;
let mut events = client.connect().await.unwrap();
let (subscribe, _, _) = client.subscribe().await.unwrap();
let enonce2_size = subscribe.enonce2_size;
client.authorize().await.unwrap();
let (initial_notify, _) = wait_for_notify(&mut events).await;
let initial_job_id = initial_notify.job_id;
let start = std::time::Instant::now();
let mut fresh_job_received = false;
let mut last_job_id = initial_job_id;
loop {
let elapsed = start.elapsed();
let result = client
.submit(
initial_notify.job_id,
Extranonce::random(enonce2_size),
initial_notify.ntime,
Nonce::from(0),
None,
)
.await;
match &result {
Err(ClientError::Io { .. })
| Err(ClientError::NotConnected)
| Err(ClientError::ChannelRecv { .. }) => break,
_ => {}
}
while let Some(Ok(event)) = events.try_recv() {
if let stratum::client::Event::Notify(notify) = event
&& notify.job_id != last_job_id
{
last_job_id = notify.job_id;
fresh_job_received = true;
}
}
if elapsed > Duration::from_secs(10) {
panic!(
"reject_escalation: Connection still alive after 10s - expected drop at DROP_THRESHOLD (3s)"
);
}
}
assert!(
fresh_job_received,
"reject_escalation: Expected fresh job notification at WARN_THRESHOLD"
);
};
let auth_failure_test = async {
let client = pool
.stratum_client_for_username("bc1qw508d6qejxtdg4y5r3zarvary0c5xw7kv8f3t4.worker")
.await;
client.connect().await.unwrap();
client.subscribe().await.unwrap();
let start = std::time::Instant::now();
let mut dropped = false;
while start.elapsed() < Duration::from_secs(10) {
match client.authorize().await {
Ok(_) => panic!("auth_failure: Expected unauthorized response"),
Err(ClientError::NotConnected) | Err(ClientError::Io { .. }) => {
dropped = true;
break;
}
Err(err) => {
assert!(
matches!(
err,
ClientError::Stratum { ref response }
if response.error_code == StratumError::Unauthorized as i32
),
"auth_failure: Expected Unauthorized, got {err:?}"
);
tokio::time::sleep(Duration::from_millis(100)).await;
}
}
}
assert!(
dropped,
"auth_failure: Expected connection to be dropped after auth failures and bouncer escalation"
);
};
let authorize_before_subscribe_test = async {
let client = pool.stratum_client().await;
client.connect().await.unwrap();
let start = std::time::Instant::now();
let mut dropped = false;
while start.elapsed() < Duration::from_secs(10) {
match client.authorize().await {
Ok(_) => panic!("auth_before_subscribe: Expected MethodNotAllowed response"),
Err(ClientError::NotConnected) | Err(ClientError::Io { .. }) => {
dropped = true;
break;
}
Err(err) => {
assert!(
matches!(
err,
ClientError::Stratum { ref response }
if response.error_code == StratumError::MethodNotAllowed as i32
),
"auth_before_subscribe: Expected MethodNotAllowed, got {err:?}"
);
tokio::time::sleep(Duration::from_millis(100)).await;
}
}
}
assert!(
dropped,
"auth_before_subscribe: Expected connection to be dropped after repeated authorize-before-subscribe attempts"
);
};
let submit_before_authorize_test = async {
let client = pool.stratum_client().await;
client.connect().await.unwrap();
client.subscribe().await.unwrap();
let start = std::time::Instant::now();
let mut dropped = false;
while start.elapsed() < Duration::from_secs(10) {
match client
.submit(
JobId::new(0),
Extranonce::random(8),
Ntime::from(0),
Nonce::from(0),
None,
)
.await
{
Ok(_) => panic!("submit_before_authorize: Expected unauthorized response"),
Err(ClientError::NotConnected) | Err(ClientError::Io { .. }) => {
dropped = true;
break;
}
Err(err) => {
assert!(
matches!(
err,
ClientError::Stratum { ref response }
if response.error_code == StratumError::Unauthorized as i32
),
"submit_before_authorize: Expected Unauthorized, got {err:?}"
);
tokio::time::sleep(Duration::from_millis(100)).await;
}
}
}
assert!(
dropped,
"submit_before_authorize: Expected connection to be dropped after repeated submit-before-authorize attempts"
);
};
let duplicate_subscribe_test = async {
let client = pool.stratum_client().await;
client.connect().await.unwrap();
client.subscribe().await.unwrap();
let start = std::time::Instant::now();
let mut dropped = false;
while start.elapsed() < Duration::from_secs(10) {
match client.subscribe().await {
Ok(_) => panic!("duplicate_subscribe: Expected MethodNotAllowed response"),
Err(ClientError::NotConnected) | Err(ClientError::Io { .. }) => {
dropped = true;
break;
}
Err(err) => {
assert!(
matches!(
err,
ClientError::Stratum { ref response }
if response.error_code == StratumError::MethodNotAllowed as i32
),
"duplicate_subscribe: Expected MethodNotAllowed, got {err:?}"
);
tokio::time::sleep(Duration::from_millis(100)).await;
}
}
}
assert!(
dropped,
"duplicate_subscribe: Expected connection to be dropped after repeated subscribe attempts"
);
};
let duplicate_authorize_test = async {
let client = pool.stratum_client().await;
client.connect().await.unwrap();
client.subscribe().await.unwrap();
client.authorize().await.unwrap();
let start = std::time::Instant::now();
let mut dropped = false;
while start.elapsed() < Duration::from_secs(10) {
match client.authorize().await {
Ok(_) => panic!("duplicate_authorize: Expected MethodNotAllowed response"),
Err(ClientError::NotConnected)
| Err(ClientError::Io { .. })
| Err(ClientError::Timeout { .. }) => {
dropped = true;
break;
}
Err(err) => {
assert!(
matches!(
err,
ClientError::Stratum { ref response }
if response.error_code == StratumError::MethodNotAllowed as i32
),
"duplicate_authorize: Expected MethodNotAllowed, got {err:?}"
);
tokio::time::sleep(Duration::from_millis(100)).await;
}
}
}
assert!(
dropped,
"duplicate_authorize: Expected connection to be dropped after repeated authorize attempts"
);
};
tokio::join!(
auth_timeout_test,
idle_timeout_test,
reject_escalation_test,
auth_failure_test,
authorize_before_subscribe_test,
submit_before_authorize_test,
duplicate_subscribe_test,
duplicate_authorize_test
);
}
#[tokio::test]
#[timeout(90000)]
async fn high_diff_port() {
let bitcoind = bitcoind();
let high_diff_port = allocate_port();
let pool = TestPool::spawn_with_args(
&bitcoind,
format!(
"--start-diff 0.00001 --disable-bouncer --update-interval 120 --high-diff-port {high_diff_port}",
),
);
let normal_client = pool.stratum_client().await;
let mut normal_events = normal_client.connect().await.unwrap();
normal_client.subscribe().await.unwrap();
normal_client.authorize().await.unwrap();
let (_, normal_diff) = wait_for_notify(&mut normal_events).await;
assert_eq!(normal_diff, Difficulty::from(0.00001));
let high_diff_client = stratum::client::Client::new(
format!("127.0.0.1:{high_diff_port}"),
signet_username(),
None,
USER_AGENT.to_string(),
Duration::from_secs(5),
);
let mut high_diff_events = high_diff_client.connect().await.unwrap();
high_diff_client.subscribe().await.unwrap();
high_diff_client.authorize().await.unwrap();
let (_, high_diff) = wait_for_notify(&mut high_diff_events).await;
assert_eq!(high_diff, Difficulty::from(1_000_000));
}
#[tokio::test]
#[timeout(90000)]
async fn idle_drop_retires_session() {
let bitcoind = bitcoind();
let pool = TestPool::spawn_with_args(&bitcoind, "--start-diff 0.00001 --update-interval 120");
let client = pool.stratum_client().await;
let mut events = client.connect().await.unwrap();
let (subscribe, _, _) = client.subscribe().await.unwrap();
let enonce1 = subscribe.enonce1;
let enonce2_size = subscribe.enonce2_size;
client.authorize().await.unwrap();
let (notify, difficulty) = wait_for_notify(&mut events).await;
let enonce2 = Extranonce::random(enonce2_size);
let (ntime, nonce) = solve_share(¬ify, &enonce1, &enonce2, difficulty);
client
.submit(notify.job_id, enonce2, ntime, nonce, None)
.await
.unwrap();
let status = pool.get_status().await.unwrap();
assert_eq!(status.downstream.session_count, 1);
tokio::time::sleep(Duration::from_secs(8)).await;
let status = pool.get_status().await.unwrap();
assert_eq!(status.downstream.session_count, 0);
}