sv1_api 3.0.0

API for bridging SV1 miners to SV2 pools
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
#![allow(clippy::result_unit_err)]
//! Stratum V1 application protocol:
//!
//! json-rpc has two types of messages: **request** and **response**.
//! A request message can be either a **notification** or a **standard message**.
//! Standard messages expect a response, notifications do not. A typical example of a notification
//! is the broadcasting of a new block.
//!
//! Every RPC request contains three parts:
//! * message ID: integer or string
//! * remote method: unicode string
//! * parameters: list of parameters
//!
//! ## Standard requests
//! Message ID must be an unique identifier of request during current transport session. It may be
//! integer or some unique string, like UUID. ID must be unique only from one side (it means, both
//! server and clients can initiate request with id “1”). Client or server can choose string/UUID
//! identifier for example in the case when standard “atomic” counter isn’t available.
//!
//! ## Notifications
//! Notifications are like Request, but it does not expect any response and message ID is always
//! null:
//! * message ID: null
//! * remote method: unicode string
//! * parameters: list of parameters
//!
//! ## Responses
//! Every response contains the following parts
//! * message ID: same ID as in request, for pairing request-response together
//! * result: any json-encoded result object (number, string, list, array, …)
//! * error: null or list (error code, error message)
//!
//! References:
//! [https://docs.google.com/document/d/17zHy1SUlhgtCMbypO8cHgpWH73V5iUQKk_0rWvMqSNs/edit?hl=en_US#]
//! [https://braiins.com/stratum-v1/docs]
//! [https://en.bitcoin.it/wiki/Stratum_mining_protocol]
//! [https://en.bitcoin.it/wiki/BIP_0310]
//! [https://docs.google.com/spreadsheets/d/1z8a3S9gFkS8NGhBCxOMUDqs7h9SQltz8-VX3KPHk7Jw/edit#gid=0]

pub mod error;
pub mod json_rpc;
pub mod methods;
pub mod utils;

use bitcoin_hashes::hex::FromHex;
use std::convert::{TryFrom, TryInto};
use tracing::debug;

// use error::Result;
use error::Error;
pub use json_rpc::Message;
pub use methods::{client_to_server, server_to_client, Method, MethodError, ParsingMethodError};
use utils::{Extranonce, HexU32Be};

/// json_rpc Response are not handled because stratum v1 does not have any request from a server to
/// a client
/// TODO: Should update to accommodate miner requesting a difficulty change
///
/// A stratum v1 server represent a single connection with a client
pub trait IsServer<'a> {
    /// handle the received message and return a response if the message is a request or
    /// notification.
    fn handle_message(
        &mut self,
        client_id: Option<usize>,
        msg: json_rpc::Message,
    ) -> Result<Option<json_rpc::Response>, Error<'a>>
    where
        Self: std::marker::Sized,
    {
        match msg {
            Message::StandardRequest(_) => {
                // handle valid standard request
                self.handle_request(client_id, msg)
            }
            Message::Notification(_) => {
                // handle valid server notification
                self.handle_request(client_id, msg)
            }
            _ => {
                // Server shouldn't receive json_rpc responses
                Err(Error::InvalidJsonRpcMessageKind)
            }
        }
    }

    /// Call the right handler according with the called method
    fn handle_request(
        &mut self,
        client_id: Option<usize>,
        msg: json_rpc::Message,
    ) -> Result<Option<json_rpc::Response>, Error<'a>>
    where
        Self: std::marker::Sized,
    {
        let request = msg.try_into()?;

        match request {
            // TODO: Handle suggested difficulty
            methods::Client2Server::SuggestDifficulty() => Ok(None),
            methods::Client2Server::Authorize(authorize) => {
                let authorized = self.handle_authorize(client_id, &authorize);
                if authorized {
                    self.authorize(client_id, &authorize.name);
                }
                Ok(Some(authorize.respond(authorized)))
            }
            methods::Client2Server::Configure(configure) => {
                debug!("{:?}", configure);
                self.set_version_rolling_mask(client_id, configure.version_rolling_mask());
                self.set_version_rolling_min_bit(
                    client_id,
                    configure.version_rolling_min_bit_count(),
                );
                let (version_rolling, min_diff) = self.handle_configure(client_id, &configure);
                Ok(Some(configure.respond(version_rolling, min_diff)))
            }
            methods::Client2Server::ExtranonceSubscribe(_) => {
                self.handle_extranonce_subscribe();
                Ok(None)
            }
            methods::Client2Server::Submit(submit) => {
                let has_valid_version_bits = match &submit.version_bits {
                    Some(a) => {
                        if let Some(version_rolling_mask) = self.version_rolling_mask(client_id) {
                            version_rolling_mask.check_mask(a)
                        } else {
                            false
                        }
                    }
                    None => self.version_rolling_mask(client_id).is_none(),
                };

                let is_valid_submission = self.is_authorized(client_id, &submit.user_name)
                    && self.extranonce2_size(client_id) == submit.extra_nonce2.len()
                    && has_valid_version_bits;

                if is_valid_submission {
                    let accepted = self.handle_submit(client_id, &submit);
                    Ok(Some(submit.respond(accepted)))
                } else {
                    Err(Error::InvalidSubmission)
                }
            }
            methods::Client2Server::Subscribe(subscribe) => {
                let subscriptions = self.handle_subscribe(client_id, &subscribe);
                let extra_n1 = self.set_extranonce1(client_id, None);
                let extra_n2_size = self.set_extranonce2_size(client_id, None);
                Ok(Some(subscribe.respond(
                    subscriptions,
                    extra_n1,
                    extra_n2_size,
                )))
            }
        }
    }

    /// This message (JSON RPC Request) SHOULD be the first message sent by the miner after the
    /// connection with the server is established.
    fn handle_configure(
        &mut self,
        client_id: Option<usize>,
        request: &client_to_server::Configure,
    ) -> (Option<server_to_client::VersionRollingParams>, Option<bool>);

    /// On the beginning of the session, client subscribes current connection for receiving mining
    /// jobs.
    ///
    /// The client can specify [mining.notify][a] job_id the client wishes to resume working with
    ///
    /// The result contains three items:
    /// * Subscriptions details: 2-tuple with name of subscribed notification and subscription ID.
    ///   Teoretically it may be used for unsubscribing, but obviously miners won't use it.
    /// * Extranonce1 - Hex-encoded, per-connection unique string which will be used for coinbase
    ///   serialization later. Keep it safe!
    /// * Extranonce2_size - Represents expected length of extranonce2 which will be generated by
    ///   the miner.
    ///
    /// Almost instantly after the subscription server start to send [jobs][a]
    ///
    /// This function return the first item of the result (2 tuple with name of subscibed ...)
    ///
    /// [a]: crate::methods::server_to_client::Notify
    fn handle_subscribe(
        &self,
        client_id: Option<usize>,
        request: &client_to_server::Subscribe,
    ) -> Vec<(String, String)>;

    /// You can authorize as many workers as you wish and at any
    /// time during the session. In this way, you can handle big basement of independent mining rigs
    /// just by one Stratum connection.
    ///
    /// https://bitcoin.stackexchange.com/questions/29416/how-do-pool-servers-handle-multiple-workers-sharing-one-connection-with-stratum
    fn handle_authorize(
        &self,
        client_id: Option<usize>,
        request: &client_to_server::Authorize,
    ) -> bool;

    /// When miner find the job which meets requested difficulty, it can submit share to the server.
    /// Only [Submit](client_to_server::Submit) requests for authorized user names can be submitted.
    fn handle_submit(
        &self,
        client_id: Option<usize>,
        request: &client_to_server::Submit<'a>,
    ) -> bool;

    /// Indicates to the server that the client supports the mining.set_extranonce method.
    fn handle_extranonce_subscribe(&self);

    fn is_authorized(&self, client_id: Option<usize>, name: &str) -> bool;

    fn authorize(&mut self, client_id: Option<usize>, name: &str);

    /// Set extranonce1 to extranonce1 if provided. If not create a new one and set it.
    fn set_extranonce1(
        &mut self,
        client_id: Option<usize>,
        extranonce1: Option<Extranonce<'a>>,
    ) -> Extranonce<'a>;

    fn extranonce1(&self, client_id: Option<usize>) -> Extranonce<'a>;

    /// Set extranonce2_size to extranonce2_size if provided. If not create a new one and set it.
    fn set_extranonce2_size(
        &mut self,
        client_id: Option<usize>,
        extra_nonce2_size: Option<usize>,
    ) -> usize;

    fn extranonce2_size(&self, client_id: Option<usize>) -> usize;

    fn version_rolling_mask(&self, client_id: Option<usize>) -> Option<HexU32Be>;

    fn set_version_rolling_mask(&mut self, client_id: Option<usize>, mask: Option<HexU32Be>);

    fn set_version_rolling_min_bit(&mut self, client_id: Option<usize>, mask: Option<HexU32Be>);

    fn update_extranonce(
        &mut self,
        client_id: Option<usize>,
        extra_nonce1: Extranonce<'a>,
        extra_nonce2_size: usize,
    ) -> Result<json_rpc::Message, Error<'a>> {
        self.set_extranonce1(client_id, Some(extra_nonce1.clone()));
        self.set_extranonce2_size(client_id, Some(extra_nonce2_size));

        Ok(server_to_client::SetExtranonce {
            extra_nonce1,
            extra_nonce2_size,
        }
        .into())
    }
    // {"params":["00003000"], "id":null, "method": "mining.set_version_mask"}
    // fn update_version_rolling_mask

    fn notify(&mut self, client_id: Option<usize>) -> Result<json_rpc::Message, Error<'_>>;

    fn handle_set_difficulty(
        &mut self,
        _client_id: Option<usize>,
        value: f64,
    ) -> Result<json_rpc::Message, Error<'_>> {
        let set_difficulty = server_to_client::SetDifficulty { value };
        Ok(set_difficulty.into())
    }
}

pub trait IsClient<'a> {
    /// Deserialize a [raw json_rpc message][a] into a [stratum v1 message][b] and handle the
    /// result.
    ///
    /// [a]: crate::...
    /// [b]:
    fn handle_message(
        &mut self,
        server_id: Option<usize>,
        msg: json_rpc::Message,
    ) -> Result<Option<json_rpc::Message>, Error<'a>>
    where
        Self: std::marker::Sized,
    {
        let method: Result<Method<'a>, MethodError<'a>> = msg.try_into();

        match method {
            Ok(m) => match m {
                Method::Server2ClientResponse(response) => {
                    let response = self.update_response(server_id, response)?;
                    self.handle_response(server_id, response)
                }
                Method::Server2Client(request) => self.handle_request(server_id, request),
                Method::Client2Server(_) => Err(Error::InvalidReceiver(m.into())),
                Method::ErrorMessage(msg) => self.handle_error_message(server_id, msg),
            },
            Err(e) => Err(e.into()),
        }
    }

    fn update_response(
        &mut self,
        server_id: Option<usize>,
        response: methods::Server2ClientResponse<'a>,
    ) -> Result<methods::Server2ClientResponse<'a>, Error<'a>> {
        match &response {
            methods::Server2ClientResponse::GeneralResponse(general) => {
                let is_authorize = self.id_is_authorize(server_id, &general.id);
                let is_submit = self.id_is_submit(server_id, &general.id);
                match (is_authorize, is_submit) {
                    (Some(prev_name), false) => {
                        let authorize = general.clone().into_authorize(prev_name);
                        Ok(methods::Server2ClientResponse::Authorize(authorize))
                    }
                    (None, false) => Ok(methods::Server2ClientResponse::Submit(
                        general.clone().into_submit(),
                    )),
                    _ => Err(Error::UnknownID(general.id)),
                }
            }
            _ => Ok(response),
        }
    }

    /// Call the right handler according with the called method
    fn handle_request(
        &mut self,
        server_id: Option<usize>,
        request: methods::Server2Client<'a>,
    ) -> Result<Option<json_rpc::Message>, Error<'a>>
    where
        Self: std::marker::Sized,
    {
        match request {
            methods::Server2Client::Notify(notify) => {
                self.handle_notify(server_id, notify)?;
                Ok(None)
            }
            methods::Server2Client::SetDifficulty(mut set_diff) => {
                self.handle_set_difficulty(server_id, &mut set_diff)?;
                Ok(None)
            }
            methods::Server2Client::SetExtranonce(mut set_extra_nonce) => {
                self.handle_set_extranonce(server_id, &mut set_extra_nonce)?;
                Ok(None)
            }
            methods::Server2Client::SetVersionMask(mut set_version_mask) => {
                self.handle_set_version_mask(server_id, &mut set_version_mask)?;
                Ok(None)
            }
        }
    }

    fn handle_response(
        &mut self,
        server_id: Option<usize>,
        response: methods::Server2ClientResponse<'a>,
    ) -> Result<Option<json_rpc::Message>, Error<'a>>
    where
        Self: std::marker::Sized,
    {
        match response {
            methods::Server2ClientResponse::Configure(mut configure) => {
                self.handle_configure(server_id, &mut configure)?;
                self.set_version_rolling_mask(server_id, configure.version_rolling_mask());
                self.set_version_rolling_min_bit(server_id, configure.version_rolling_min_bit());
                self.set_status(server_id, ClientStatus::Configured);

                //in sv1 the mining.configure message should be the first message to come in before
                // the subscribe - the subscribe response is where the server hands out the
                // extranonce so it doesnt really matter what the server sets the
                // extranonce to in the mining.configure handler
                debug!("NOTICE: Subscribe extranonce is hardcoded by server");
                let subscribe = self
                    .subscribe(
                        server_id,
                        configure.id,
                        Some(Extranonce::try_from(
                            Vec::<u8>::from_hex("08000002").map_err(Error::HexError)?,
                        )?),
                    )
                    .ok();
                Ok(subscribe)
            }
            methods::Server2ClientResponse::Subscribe(subscribe) => {
                self.handle_subscribe(server_id, &subscribe)?;
                self.set_extranonce1(server_id, subscribe.extra_nonce1);
                self.set_extranonce2_size(server_id, subscribe.extra_nonce2_size);
                self.set_status(server_id, ClientStatus::Subscribed);
                Ok(None)
            }
            methods::Server2ClientResponse::Authorize(authorize) => {
                if authorize.is_ok() {
                    self.authorize_user_name(server_id, authorize.user_name());
                };
                Ok(None)
            }
            methods::Server2ClientResponse::Submit(_) => Ok(None),
            // impossible state
            methods::Server2ClientResponse::GeneralResponse(_) => panic!(),
            methods::Server2ClientResponse::SetDifficulty(_) => Ok(None),
        }
    }

    fn handle_error_message(
        &mut self,
        server_id: Option<usize>,
        message: Message,
    ) -> Result<Option<json_rpc::Message>, Error<'a>>;

    /// Check if the client sent an Authorize request with the given id, if so it return the
    /// authorized name
    fn id_is_authorize(&mut self, server_id: Option<usize>, id: &u64) -> Option<String>;

    /// Check if the client sent a Submit request with the given id
    fn id_is_submit(&mut self, server_id: Option<usize>, id: &u64) -> bool;

    fn handle_notify(
        &mut self,
        server_id: Option<usize>,
        notify: server_to_client::Notify<'a>,
    ) -> Result<(), Error<'a>>;

    fn handle_configure(
        &mut self,
        server_id: Option<usize>,
        conf: &mut server_to_client::Configure,
    ) -> Result<(), Error<'a>>;

    fn handle_set_difficulty(
        &mut self,
        server_id: Option<usize>,
        m: &mut server_to_client::SetDifficulty,
    ) -> Result<(), Error<'a>>;

    fn handle_set_extranonce(
        &mut self,
        server_id: Option<usize>,
        m: &mut server_to_client::SetExtranonce,
    ) -> Result<(), Error<'a>>;

    fn handle_set_version_mask(
        &mut self,
        server_id: Option<usize>,
        m: &mut server_to_client::SetVersionMask,
    ) -> Result<(), Error<'a>>;

    fn handle_subscribe(
        &mut self,
        server_id: Option<usize>,
        subscribe: &server_to_client::Subscribe<'a>,
    ) -> Result<(), Error<'a>>;

    fn set_extranonce1(&mut self, server_id: Option<usize>, extranonce1: Extranonce<'a>);

    fn extranonce1(&self, server_id: Option<usize>) -> Extranonce<'a>;

    fn set_extranonce2_size(&mut self, server_id: Option<usize>, extra_nonce2_size: usize);

    fn extranonce2_size(&self, server_id: Option<usize>) -> usize;

    fn version_rolling_mask(&self, server_id: Option<usize>) -> Option<HexU32Be>;

    fn set_version_rolling_mask(&mut self, server_id: Option<usize>, mask: Option<HexU32Be>);

    fn set_version_rolling_min_bit(&mut self, server_id: Option<usize>, min: Option<HexU32Be>);

    fn version_rolling_min_bit(&mut self, server_id: Option<usize>) -> Option<HexU32Be>;

    fn set_status(&mut self, server_id: Option<usize>, status: ClientStatus);

    fn signature(&self, server_id: Option<usize>) -> String;

    fn status(&self, server_id: Option<usize>) -> ClientStatus;

    fn last_notify(&self, server_id: Option<usize>) -> Option<server_to_client::Notify<'_>>;

    /// Check if the given user_name has been authorized by the server
    #[allow(clippy::ptr_arg)]
    fn is_authorized(&self, server_id: Option<usize>, name: &String) -> bool;

    /// Register the given user_name has authorized by the server
    fn authorize_user_name(&mut self, server_id: Option<usize>, name: String);

    fn configure(&mut self, server_id: Option<usize>, id: u64) -> json_rpc::Message {
        if self.version_rolling_min_bit(server_id).is_none()
            && self.version_rolling_mask(server_id).is_none()
        {
            client_to_server::Configure::void(id).into()
        } else {
            client_to_server::Configure::new(
                id,
                self.version_rolling_mask(server_id),
                self.version_rolling_min_bit(server_id),
            )
            .into()
        }
    }

    fn subscribe(
        &mut self,
        server_id: Option<usize>,
        id: u64,
        extranonce1: Option<Extranonce<'a>>,
    ) -> Result<json_rpc::Message, Error<'a>> {
        match self.status(server_id) {
            ClientStatus::Init => Err(Error::IncorrectClientStatus("mining.subscribe".to_string())),
            _ => Ok(client_to_server::Subscribe {
                id,
                agent_signature: self.signature(server_id),
                extranonce1,
            }
            .try_into()?),
        }
    }

    fn authorize(
        &mut self,
        server_id: Option<usize>,
        id: u64,
        name: String,
        password: String,
    ) -> Result<json_rpc::Message, Error<'_>> {
        match self.status(server_id) {
            ClientStatus::Init => Err(Error::IncorrectClientStatus("mining.authorize".to_string())),
            _ => Ok(client_to_server::Authorize { id, name, password }.into()),
        }
    }

    #[allow(clippy::too_many_arguments)]
    fn submit(
        &mut self,
        server_id: Option<usize>,
        id: u64,
        user_name: String,
        extra_nonce2: Extranonce<'a>,
        time: i64,
        nonce: i64,
        version_bits: Option<HexU32Be>,
    ) -> Result<json_rpc::Message, Error<'a>> {
        match self.status(server_id) {
            ClientStatus::Init => Err(Error::IncorrectClientStatus("mining.submit".to_string())),
            _ => {
                if let Some(notify) = self.last_notify(server_id) {
                    if !self.is_authorized(server_id, &user_name) {
                        return Err(Error::UnauthorizedClient(user_name));
                    }
                    Ok(client_to_server::Submit {
                        job_id: notify.job_id,
                        user_name,
                        extra_nonce2,
                        time: HexU32Be(time as u32),
                        nonce: HexU32Be(nonce as u32),
                        version_bits,
                        id,
                    }
                    .into())
                } else {
                    Err(Error::IncorrectClientStatus(
                        "No Notify instance found".to_string(),
                    ))
                }
            }
        }
    }
}

#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum ClientStatus {
    Init,
    Configured,
    Subscribed,
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::collections::HashSet;

    // A minimal implementation of IsServer trait for testing
    struct TestServer<'a> {
        authorized_users: HashSet<String>,
        extranonce1: Extranonce<'a>,
        extranonce2_size: usize,
        version_rolling_mask: Option<HexU32Be>,
        version_rolling_min_bit: Option<HexU32Be>,
    }

    impl<'a> TestServer<'a> {
        fn new(extranonce1: Extranonce<'a>, extranonce2_size: usize) -> Self {
            Self {
                authorized_users: HashSet::new(),
                extranonce1,
                extranonce2_size,
                version_rolling_mask: None,
                version_rolling_min_bit: None,
            }
        }
    }

    impl<'a> IsServer<'a> for TestServer<'a> {
        fn handle_configure(
            &mut self,
            _client_id: Option<usize>,
            _request: &client_to_server::Configure,
        ) -> (Option<server_to_client::VersionRollingParams>, Option<bool>) {
            (None, None)
        }

        fn handle_subscribe(
            &self,
            _client_id: Option<usize>,
            _request: &client_to_server::Subscribe,
        ) -> Vec<(String, String)> {
            vec![("mining.notify".to_string(), "1".to_string())]
        }

        fn handle_authorize(
            &self,
            _client_id: Option<usize>,
            _request: &client_to_server::Authorize,
        ) -> bool {
            true
        }

        fn notify(&mut self, _client_id: Option<usize>) -> Result<json_rpc::Message, Error<'_>> {
            Ok(json_rpc::Message::StandardRequest(
                json_rpc::StandardRequest {
                    id: 1,
                    method: "mining.notify".to_string(),
                    params: serde_json::json!([]),
                },
            ))
        }

        fn handle_submit(
            &self,
            _client_id: Option<usize>,
            _request: &client_to_server::Submit<'a>,
        ) -> bool {
            true
        }

        fn handle_extranonce_subscribe(&self) {}

        fn is_authorized(&self, _client_id: Option<usize>, name: &str) -> bool {
            self.authorized_users.contains(name)
        }

        fn authorize(&mut self, _client_id: Option<usize>, name: &str) {
            self.authorized_users.insert(name.to_string());
        }

        fn set_extranonce1(
            &mut self,
            _client_id: Option<usize>,
            extranonce1: Option<Extranonce<'a>>,
        ) -> Extranonce<'a> {
            if let Some(extranonce1) = extranonce1 {
                self.extranonce1 = extranonce1;
            }
            self.extranonce1.clone()
        }

        fn extranonce1(&self, _client_id: Option<usize>) -> Extranonce<'a> {
            self.extranonce1.clone()
        }

        fn set_extranonce2_size(
            &mut self,
            _client_id: Option<usize>,
            extra_nonce2_size: Option<usize>,
        ) -> usize {
            if let Some(extra_nonce2_size) = extra_nonce2_size {
                self.extranonce2_size = extra_nonce2_size;
            }
            self.extranonce2_size
        }

        fn extranonce2_size(&self, _client_id: Option<usize>) -> usize {
            self.extranonce2_size
        }

        fn version_rolling_mask(&self, _client_id: Option<usize>) -> Option<HexU32Be> {
            None
        }

        fn set_version_rolling_mask(&mut self, _client_id: Option<usize>, mask: Option<HexU32Be>) {
            self.version_rolling_mask = mask;
        }

        fn set_version_rolling_min_bit(
            &mut self,
            _client_id: Option<usize>,
            mask: Option<HexU32Be>,
        ) {
            self.version_rolling_min_bit = mask;
        }
    }

    #[test]
    fn test_server_handle_invalid_message() {
        let extranonce1 = Extranonce::try_from(Vec::<u8>::from_hex("08000002").unwrap()).unwrap();
        let mut server = TestServer::new(extranonce1, 4);

        // Create an invalid message (response)
        let request_message = json_rpc::Message::StandardRequest(json_rpc::StandardRequest {
            id: 42,
            method: "mining.subscribe_bad".to_string(),
            params: serde_json::json!([]),
        });

        let result = server.handle_message(None, request_message);

        assert!(result.is_err());
        match result.unwrap_err() {
            Error::Method(inner) => match *inner {
                MethodError::MethodNotFound(_) => {}
                other => panic!("Expected MethodNotFound error, got {:?}", other),
            },
            other => panic!("Expected Error::Method, got {:?}", other),
        }
    }

    #[test]
    fn version_mask_invalid_len() {
        let raw = serde_json::json!([
            "mining.set_version_mask",
            ["123456789"] // len > 8 bytes
        ]);

        let msg: Result<Message, _> = serde_json::from_value(raw);

        if let Ok(msg) = msg {
            let result = Method::try_from(msg);
            assert!(result.is_err(), "Expected error for invalid hex length");

            match result.unwrap_err() {
                MethodError::ParsingMethodError((ParsingMethodError::InvalidHexLen(_), _)) => {}
                other => panic!("Expected InvalidHexLen, got {:?}", other),
            }
        } else {
            panic!("Message parsing failed unexpectedly");
        }
    }
}