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
#[cfg(feature = "default")]
use crate::api::init_api_server;
#[cfg(not(feature = "websockets"))]
use crate::tcp::handle_connection;
#[cfg(feature = "websockets")]
use crate::websockets::handle_connection;
pub use crate::connection::Connection;
use crate::global::Global;
use crate::route::Endpoint;
use crate::router::Router;
use crate::types::ReadyIndicator;
use crate::BanManager;
pub use crate::MinerList;
use crate::Result;
use crate::StratumServerBuilder;
use async_std::net::TcpListener;
use async_std::sync::Arc;
use async_std::sync::Mutex;
use async_std::task;
use async_std::task::JoinHandle;
use futures::channel::mpsc::unbounded;
use futures::io::AsyncReadExt;
use futures::SinkExt;
use futures::StreamExt;
use log::info;
use smol::Async;
use std::os::unix::net::UnixStream;
use std::time::Instant;
use stop_token::{StopSource, StopToken};
#[derive(Clone, Debug, Default)]
pub struct VarDiffConfig {
pub(crate) var_diff: bool,
pub(crate) minimum_difficulty: f64,
pub(crate) maximum_difficulty: f64,
pub(crate) retarget_time: i64,
pub(crate) target_time: f64,
pub(crate) variance_percent: f64,
}
pub struct StratumServer<State, CState>
where
State: Clone + Send + Sync + 'static,
CState: Clone + Send + Sync + 'static,
{
pub(crate) host: String,
pub(crate) port: u16,
pub(crate) expected_port: u16,
pub(crate) proxy: bool,
pub(crate) initial_difficulty: f64,
pub(crate) state: State,
pub(crate) connection_list: Arc<MinerList<CState>>,
pub(crate) ban_manager: Arc<BanManager>,
pub(crate) router: Arc<Router<State, CState>>,
pub(crate) var_diff_config: VarDiffConfig,
pub(crate) initial_connection_state: CState,
pub(crate) stop_source: Arc<Mutex<Option<StopSource>>>,
pub(crate) stop_token: StopToken,
pub(crate) global_thread_list: Vec<JoinHandle<()>>,
pub(crate) ready_indicator: ReadyIndicator,
}
impl<State: Clone + Send + Sync + 'static, CState: Clone + Send + Sync + 'static>
StratumServer<State, CState>
{
pub fn builder(state: State, connection_state: CState) -> StratumServerBuilder<State, CState> {
StratumServerBuilder::new(state, connection_state)
}
async fn init(&self) -> Result<()> {
info!("Initializing...");
if cfg!(feature = "default") {
init_api_server(self.stop_token.clone(), self.ready_indicator.clone()).await?;
info!("API Server Initialized");
}
let (tx, mut rx) = unbounded();
let tx = Arc::new(Mutex::new(tx));
let (a, mut b) = Async::<UnixStream>::pair()?;
signal_hook::pipe::register(signal_hook::SIGINT, a)?;
let (c, mut d) = Async::<UnixStream>::pair()?;
signal_hook::pipe::register(signal_hook::SIGTERM, c)?;
async_std::task::spawn({
let tx = tx.clone();
let stop_token = self.stop_token.clone();
async move {
let mut read = [0];
let read_exact = stop_token.stop_future(b.read_exact(&mut read));
match read_exact.await {
Some(result) => {
result.unwrap();
info!("Received SIGINT. Initiating shutdown...");
tx.lock().await.send(1).await.unwrap();
}
None => {
info!("Closing SIGINT watch task");
}
};
}
});
async_std::task::spawn({
let stop_token = self.stop_token.clone();
async move {
let mut read = [0];
let read_exact = stop_token.stop_future(d.read_exact(&mut read));
match read_exact.await {
Some(result) => {
result.unwrap();
info!("Received SIGTERM. Initiating shutdown...");
tx.lock().await.send(1).await.unwrap();
}
None => {
info!("Closing SIGTERM watch task");
}
}
}
});
async_std::task::spawn({
let stop_source = self.stop_source.clone();
async move {
while let Some(event) = rx.next().await {
info!("Shutting down due to the {} Signal received", event);
*stop_source.lock().await = None;
}
}
});
info!("Initialization Complete");
Ok(())
}
pub fn add(&mut self, method: &str, ep: impl Endpoint<State, CState>) {
let router = Arc::get_mut(&mut self.router)
.expect("Registering routes is not possible after the Server has started");
router.add(method, ep);
}
pub fn global(&mut self, ep: impl Global<State, CState>) {
let state = self.state.clone();
let connection_list = self.connection_list.clone();
let stop_token = self.stop_token.clone();
let handle = async_std::task::spawn(async move {
let call = stop_token.stop_future(ep.call(state, connection_list));
call.await;
});
self.global_thread_list.push(handle);
}
pub async fn start(&mut self) -> Result<()> {
init_metrics_recorder();
self.init().await?;
let listen_url = format!("{}:{}", &self.host, self.port);
let listener = TcpListener::bind(&listen_url).await?;
let incoming = listener.incoming();
info!("Listening on {}", &listen_url);
let mut thread_list = Vec::new();
let mut incoming_with_stop = self.stop_token.stop_stream(incoming);
while let Some(stream) = incoming_with_stop.next().await {
let stream = match stream {
Ok(stream) => stream,
Err(_e) => continue,
};
let addr = match stream.peer_addr() {
Ok(addr) => addr,
Err(_e) => continue,
};
let connection_list = self.connection_list.clone();
let proxy = self.proxy;
let expected_port = self.expected_port;
let initial_difficulty = self.initial_difficulty;
let ban_manager = self.ban_manager.clone();
let router = self.router.clone();
let state = self.state.clone();
let connection_state = self.initial_connection_state.clone();
let var_diff_config = self.var_diff_config.clone();
let handle = task::spawn(async move {
handle_connection(
ban_manager,
addr,
connection_list,
router,
state,
stream,
var_diff_config,
initial_difficulty,
connection_state,
proxy,
expected_port,
)
.await
});
thread_list.push(handle);
}
let start = Instant::now();
self.connection_list.shutdown().await?;
let global_thread_list = self.global_thread_list.drain(..);
info!("Awaiting for all current globals to complete");
for thread in global_thread_list {
thread.await;
}
info!("Awaiting for all current connections to complete");
for thread in thread_list {
thread.await;
}
info!("Shutdown complete in {} ns", start.elapsed().as_nanos());
Ok(())
}
pub fn get_ready_indicator(&self) -> ReadyIndicator {
self.ready_indicator.clone()
}
pub fn get_miner_list(&self) -> Arc<MinerList<CState>> {
self.connection_list.clone()
}
}
pub fn init_metrics_recorder() {
}
impl<State: Clone + Send + Sync + 'static, CState: Clone + Send + Sync + 'static> Drop
for StratumServer<State, CState>
{
fn drop(&mut self) {
info!("Dropping StratumSever with data `{}`!", self.host);
dbg!("DID THIS WORK");
}
}