forked from romanz/electrs
-
Notifications
You must be signed in to change notification settings - Fork 166
Expand file tree
/
Copy pathserver.rs
More file actions
890 lines (793 loc) · 33.1 KB
/
server.rs
File metadata and controls
890 lines (793 loc) · 33.1 KB
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
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
use std::collections::HashMap;
use std::io::{BufRead, BufReader, Write};
use std::net::{Shutdown, SocketAddr, TcpListener, TcpStream};
use std::sync::atomic::AtomicBool;
use std::sync::mpsc::{Receiver, Sender};
use std::sync::{Arc, Mutex};
use std::thread;
use bitcoin::hashes::sha256d::Hash as Sha256dHash;
use crypto::digest::Digest;
use crypto::sha2::Sha256;
use error_chain::ChainedError;
use hex;
use serde_json::{from_str, Value};
#[cfg(not(feature = "liquid"))]
use bitcoin::consensus::encode::serialize;
#[cfg(feature = "liquid")]
use elements::encode::serialize;
use crate::chain::Txid;
use crate::config::Config;
use crate::electrum::{get_electrum_height, ProtocolVersion};
use crate::errors::*;
use crate::metrics::{Gauge, HistogramOpts, HistogramVec, MetricOpts, Metrics};
use crate::new_index::{Query, Utxo};
use crate::util::electrum_merkle::{get_header_merkle_proof, get_id_from_pos, get_tx_merkle_proof};
use crate::util::{
create_socket, full_hash, spawn_thread, BlockId, BoolThen, Channel, FullHash, HeaderEntry,
SyncChannel,
};
const ELECTRS_VERSION: &str = env!("CARGO_PKG_VERSION");
const PROTOCOL_VERSION: ProtocolVersion = ProtocolVersion::new(1, 4);
const MAX_HEADERS: usize = 2016;
#[cfg(feature = "electrum-discovery")]
use crate::electrum::{DiscoveryManager, ServerFeatures};
// TODO: Sha256dHash should be a generic hash-container (since script hash is single SHA256)
fn hash_from_value(val: Option<&Value>) -> Result<Sha256dHash> {
let script_hash = val.chain_err(|| "missing hash")?;
let script_hash = script_hash.as_str().chain_err(|| "non-string hash")?;
let script_hash = script_hash.parse().chain_err(|| "non-hex hash")?;
Ok(script_hash)
}
fn usize_from_value(val: Option<&Value>, name: &str) -> Result<usize> {
let val = val.chain_err(|| format!("missing {}", name))?;
let val = val.as_u64().chain_err(|| format!("non-integer {}", name))?;
Ok(val as usize)
}
fn usize_from_value_or(val: Option<&Value>, name: &str, default: usize) -> Result<usize> {
if val.is_none() {
return Ok(default);
}
usize_from_value(val, name)
}
fn bool_from_value(val: Option<&Value>, name: &str) -> Result<bool> {
let val = val.chain_err(|| format!("missing {}", name))?;
let val = val.as_bool().chain_err(|| format!("not a bool {}", name))?;
Ok(val)
}
fn bool_from_value_or(val: Option<&Value>, name: &str, default: bool) -> Result<bool> {
if val.is_none() {
return Ok(default);
}
bool_from_value(val, name)
}
// TODO: implement caching and delta updates
fn get_status_hash(txs: Vec<(Txid, Option<BlockId>)>, query: &Query) -> Option<FullHash> {
if txs.is_empty() {
None
} else {
let mut hash = FullHash::default();
let mut sha2 = Sha256::new();
for (txid, blockid) in txs {
let is_mempool = blockid.is_none();
let has_unconfirmed_parents = is_mempool
.and_then(|| Some(query.has_unconfirmed_parents(&txid)))
.unwrap_or(false);
let height = get_electrum_height(blockid, has_unconfirmed_parents);
let part = format!("{}:{}:", txid, height);
sha2.input(part.as_bytes());
}
sha2.result(&mut hash);
Some(hash)
}
}
struct Connection {
query: Arc<Query>,
last_header_entry: Option<HeaderEntry>,
status_hashes: HashMap<Sha256dHash, Value>, // ScriptHash -> StatusHash
stream: TcpStream,
addr: SocketAddr,
chan: SyncChannel<Message>,
stats: Arc<Stats>,
txs_limit: usize,
die_please: Option<Receiver<()>>,
#[cfg(feature = "electrum-discovery")]
discovery: Option<Arc<DiscoveryManager>>,
}
impl Connection {
pub fn new(
query: Arc<Query>,
stream: TcpStream,
addr: SocketAddr,
stats: Arc<Stats>,
txs_limit: usize,
die_please: Receiver<()>,
#[cfg(feature = "electrum-discovery")] discovery: Option<Arc<DiscoveryManager>>,
) -> Connection {
Connection {
query,
last_header_entry: None, // disable header subscription for now
status_hashes: HashMap::new(),
stream,
addr,
chan: SyncChannel::new(10),
stats,
txs_limit,
die_please: Some(die_please),
#[cfg(feature = "electrum-discovery")]
discovery,
}
}
fn blockchain_headers_subscribe(&mut self) -> Result<Value> {
let entry = self.query.chain().best_header();
let hex_header = hex::encode(serialize(entry.header()));
let result = json!({"hex": hex_header, "height": entry.height()});
self.last_header_entry = Some(entry);
Ok(result)
}
fn server_version(&self) -> Result<Value> {
Ok(json!([
format!("electrs-esplora {}", ELECTRS_VERSION),
PROTOCOL_VERSION
]))
}
fn server_banner(&self) -> Result<Value> {
Ok(json!(self.query.config().electrum_banner.clone()))
}
#[cfg(feature = "electrum-discovery")]
fn server_features(&self) -> Result<Value> {
let discovery = self
.discovery
.as_ref()
.chain_err(|| "discovery is disabled")?;
Ok(json!(discovery.our_features()))
}
fn server_donation_address(&self) -> Result<Value> {
Ok(Value::Null)
}
fn server_peers_subscribe(&self) -> Result<Value> {
#[cfg(feature = "electrum-discovery")]
let servers = self
.discovery
.as_ref()
.map_or_else(|| json!([]), |d| json!(d.get_servers()));
#[cfg(not(feature = "electrum-discovery"))]
let servers = json!([]);
Ok(servers)
}
#[cfg(feature = "electrum-discovery")]
fn server_add_peer(&self, params: &[Value]) -> Result<Value> {
let discovery = self
.discovery
.as_ref()
.chain_err(|| "discovery is disabled")?;
let features = params
.get(0)
.chain_err(|| "missing features param")?
.clone();
let features = serde_json::from_value(features).chain_err(|| "invalid features")?;
discovery.add_server_request(self.addr.ip(), features)?;
Ok(json!(true))
}
fn mempool_get_fee_histogram(&self) -> Result<Value> {
Ok(json!(&self.query.mempool().backlog_stats().fee_histogram))
}
fn blockchain_block_header(&self, params: &[Value]) -> Result<Value> {
let height = usize_from_value(params.get(0), "height")?;
let cp_height = usize_from_value_or(params.get(1), "cp_height", 0)?;
let raw_header_hex: String = self
.query
.chain()
.header_by_height(height)
.map(|entry| hex::encode(&serialize(entry.header())))
.chain_err(|| "missing header")?;
if cp_height == 0 {
return Ok(json!(raw_header_hex));
}
let (branch, root) = get_header_merkle_proof(self.query.chain(), height, cp_height)?;
Ok(json!({
"header": raw_header_hex,
"root": root,
"branch": branch
}))
}
fn blockchain_block_headers(&self, params: &[Value]) -> Result<Value> {
let start_height = usize_from_value(params.get(0), "start_height")?;
let count = MAX_HEADERS.min(usize_from_value(params.get(1), "count")?);
let cp_height = usize_from_value_or(params.get(2), "cp_height", 0)?;
let heights: Vec<usize> = (start_height..(start_height + count)).collect();
let headers: Vec<String> = heights
.into_iter()
.filter_map(|height| {
self.query
.chain()
.header_by_height(height)
.map(|entry| hex::encode(&serialize(entry.header())))
})
.collect();
if count == 0 || cp_height == 0 {
return Ok(json!({
"count": headers.len(),
"hex": headers.join(""),
"max": MAX_HEADERS,
}));
}
let (branch, root) =
get_header_merkle_proof(self.query.chain(), start_height + (count - 1), cp_height)?;
Ok(json!({
"count": headers.len(),
"hex": headers.join(""),
"max": MAX_HEADERS,
"root": root,
"branch" : branch,
}))
}
fn blockchain_estimatefee(&self, params: &[Value]) -> Result<Value> {
let conf_target = usize_from_value(params.get(0), "blocks_count")?;
let fee_rate = self
.query
.estimate_fee(conf_target as u16)
.chain_err(|| format!("cannot estimate fee for {} blocks", conf_target))?;
// convert from sat/b to BTC/kB, as expected by Electrum clients
Ok(json!(fee_rate / 100_000f64))
}
fn blockchain_relayfee(&self) -> Result<Value> {
let relayfee = self.query.get_relayfee()?;
// convert from sat/b to BTC/kB, as expected by Electrum clients
Ok(json!(relayfee / 100_000f64))
}
fn blockchain_scripthash_subscribe(&mut self, params: &[Value]) -> Result<Value> {
let script_hash = hash_from_value(params.get(0)).chain_err(|| "bad script_hash")?;
let history_txids = get_history(&self.query, &script_hash[..], self.txs_limit)?;
let status_hash = get_status_hash(history_txids, &self.query)
.map_or(Value::Null, |h| json!(hex::encode(full_hash(&h[..]))));
if let None = self.status_hashes.insert(script_hash, status_hash.clone()) {
self.stats.subscriptions.inc();
}
Ok(status_hash)
}
#[cfg(not(feature = "liquid"))]
fn blockchain_scripthash_get_balance(&self, params: &[Value]) -> Result<Value> {
let script_hash = hash_from_value(params.get(0)).chain_err(|| "bad script_hash")?;
let (chain_stats, mempool_stats) = self.query.stats(&script_hash[..]);
Ok(json!({
"confirmed": chain_stats.funded_txo_sum - chain_stats.spent_txo_sum,
"unconfirmed": mempool_stats.funded_txo_sum as i64 - mempool_stats.spent_txo_sum as i64,
}))
}
fn blockchain_scripthash_get_history(&self, params: &[Value]) -> Result<Value> {
let script_hash = hash_from_value(params.get(0)).chain_err(|| "bad script_hash")?;
let history_txids = get_history(&self.query, &script_hash[..], self.txs_limit)?;
Ok(json!(history_txids
.into_iter()
.map(|(txid, blockid)| {
let is_mempool = blockid.is_none();
let fee = is_mempool.and_then(|| self.query.get_mempool_tx_fee(&txid));
let has_unconfirmed_parents = is_mempool
.and_then(|| Some(self.query.has_unconfirmed_parents(&txid)))
.unwrap_or(false);
let height = get_electrum_height(blockid, has_unconfirmed_parents);
GetHistoryResult { txid, height, fee }
})
.collect::<Vec<_>>()))
}
fn blockchain_scripthash_listunspent(&self, params: &[Value]) -> Result<Value> {
let script_hash = hash_from_value(params.get(0)).chain_err(|| "bad script_hash")?;
let utxos = self.query.utxo(&script_hash[..])?;
let to_json = |utxo: Utxo| {
let json = json!({
"height": utxo.confirmed.map_or(0, |b| b.height),
"tx_pos": utxo.vout,
"tx_hash": utxo.txid,
"value": utxo.value,
});
#[cfg(feature = "liquid")]
let json = {
let mut json = json;
json["asset"] = json!(utxo.asset);
json["nonce"] = json!(utxo.nonce);
json
};
json
};
Ok(json!(Value::Array(
utxos.into_iter().map(to_json).collect()
)))
}
fn blockchain_transaction_broadcast(&self, params: &[Value]) -> Result<Value> {
let tx = params.get(0).chain_err(|| "missing tx")?;
let tx = tx.as_str().chain_err(|| "non-string tx")?.to_string();
let txid = self.query.broadcast_raw(&tx)?;
if let Err(e) = self.chan.sender().try_send(Message::PeriodicUpdate) {
warn!("failed to issue PeriodicUpdate after broadcast: {}", e);
}
Ok(json!(txid))
}
fn blockchain_transaction_get(&self, params: &[Value]) -> Result<Value> {
let tx_hash = Txid::from(hash_from_value(params.get(0)).chain_err(|| "bad tx_hash")?);
let verbose = match params.get(1) {
Some(value) => value.as_bool().chain_err(|| "non-bool verbose value")?,
None => false,
};
// FIXME: implement verbose support
if verbose {
bail!("verbose transactions are currently unsupported");
}
let tx = self
.query
.lookup_raw_txn(&tx_hash)
.chain_err(|| "missing transaction")?;
Ok(json!(hex::encode(tx)))
}
fn blockchain_transaction_get_merkle(&self, params: &[Value]) -> Result<Value> {
let txid = Txid::from(hash_from_value(params.get(0)).chain_err(|| "bad tx_hash")?);
let height = usize_from_value(params.get(1), "height")?;
let blockid = self
.query
.chain()
.tx_confirming_block(&txid)
.ok_or_else(|| "tx not found or is unconfirmed")?;
if blockid.height != height {
bail!("invalid confirmation height provided");
}
let (merkle, pos) = get_tx_merkle_proof(self.query.chain(), &txid, &blockid.hash)
.chain_err(|| "cannot create merkle proof")?;
Ok(json!({
"block_height": blockid.height,
"merkle": merkle,
"pos": pos}))
}
fn blockchain_transaction_id_from_pos(&self, params: &[Value]) -> Result<Value> {
let height = usize_from_value(params.get(0), "height")?;
let tx_pos = usize_from_value(params.get(1), "tx_pos")?;
let want_merkle = bool_from_value_or(params.get(2), "merkle", false)?;
let (txid, merkle) = get_id_from_pos(self.query.chain(), height, tx_pos, want_merkle)?;
if !want_merkle {
return Ok(json!(txid));
}
Ok(json!({
"tx_hash": txid,
"merkle" : merkle}))
}
fn handle_command(&mut self, method: &str, params: &[Value], id: &Value) -> Result<Value> {
let timer = self
.stats
.latency
.with_label_values(&[method])
.start_timer();
let result = match method {
"blockchain.block.header" => self.blockchain_block_header(¶ms),
"blockchain.block.headers" => self.blockchain_block_headers(¶ms),
"blockchain.estimatefee" => self.blockchain_estimatefee(¶ms),
"blockchain.headers.subscribe" => self.blockchain_headers_subscribe(),
"blockchain.relayfee" => self.blockchain_relayfee(),
#[cfg(not(feature = "liquid"))]
"blockchain.scripthash.get_balance" => self.blockchain_scripthash_get_balance(¶ms),
"blockchain.scripthash.get_history" => self.blockchain_scripthash_get_history(¶ms),
"blockchain.scripthash.listunspent" => self.blockchain_scripthash_listunspent(¶ms),
"blockchain.scripthash.subscribe" => self.blockchain_scripthash_subscribe(¶ms),
"blockchain.transaction.broadcast" => self.blockchain_transaction_broadcast(¶ms),
"blockchain.transaction.get" => self.blockchain_transaction_get(¶ms),
"blockchain.transaction.get_merkle" => self.blockchain_transaction_get_merkle(¶ms),
"blockchain.transaction.id_from_pos" => {
self.blockchain_transaction_id_from_pos(¶ms)
}
"mempool.get_fee_histogram" => self.mempool_get_fee_histogram(),
"server.banner" => self.server_banner(),
"server.donation_address" => self.server_donation_address(),
"server.peers.subscribe" => self.server_peers_subscribe(),
"server.ping" => Ok(Value::Null),
"server.version" => self.server_version(),
#[cfg(feature = "electrum-discovery")]
"server.features" => self.server_features(),
#[cfg(feature = "electrum-discovery")]
"server.add_peer" => self.server_add_peer(¶ms),
&_ => bail!("unknown method {} {:?}", method, params),
};
timer.observe_duration();
// TODO: return application errors should be sent to the client
Ok(match result {
Ok(result) => json!({"jsonrpc": "2.0", "id": id, "result": result}),
Err(e) => {
warn!(
"rpc #{} {} {:?} failed: {}",
id,
method,
params,
e.display_chain()
);
json!({"jsonrpc": "2.0", "id": id, "error": format!("{}", e)})
}
})
}
fn update_subscriptions(&mut self) -> Result<Vec<Value>> {
let timer = self
.stats
.latency
.with_label_values(&["periodic_update"])
.start_timer();
let mut result = vec![];
if let Some(ref mut last_entry) = self.last_header_entry {
let entry = self.query.chain().best_header();
if *last_entry != entry {
*last_entry = entry;
let hex_header = hex::encode(serialize(last_entry.header()));
let header = json!({"hex": hex_header, "height": last_entry.height()});
result.push(json!({
"jsonrpc": "2.0",
"method": "blockchain.headers.subscribe",
"params": [header]}));
}
}
for (script_hash, status_hash) in self.status_hashes.iter_mut() {
let history_txids = get_history(&self.query, &script_hash[..], self.txs_limit)?;
let new_status_hash = get_status_hash(history_txids, &self.query)
.map_or(Value::Null, |h| json!(hex::encode(full_hash(&h[..]))));
if new_status_hash == *status_hash {
continue;
}
result.push(json!({
"jsonrpc": "2.0",
"method": "blockchain.scripthash.subscribe",
"params": [script_hash, new_status_hash]}));
*status_hash = new_status_hash;
}
timer.observe_duration();
Ok(result)
}
fn send_values(&mut self, values: &[Value]) -> Result<()> {
for value in values {
let line = value.to_string() + "\n";
self.stream
.write_all(line.as_bytes())
.chain_err(|| format!("failed to send {}", value))?;
}
Ok(())
}
fn handle_replies(&mut self, shutdown: crossbeam_channel::Receiver<()>) -> Result<()> {
let empty_params = json!([]);
loop {
crossbeam_channel::select! {
recv(self.chan.receiver()) -> msg => {
let msg = msg.chain_err(|| "channel closed")?;
trace!("RPC {:?}", msg);
match msg {
Message::Request(line) => {
let cmd: Value = from_str(&line).chain_err(|| "invalid JSON format")?;
let reply = match (
cmd.get("method"),
cmd.get("params").unwrap_or(&empty_params),
cmd.get("id"),
) {
(Some(Value::String(method)), Value::Array(params), Some(id)) => {
self.handle_command(method, params, id)?
}
_ => bail!("invalid command: {}", cmd),
};
self.send_values(&[reply])?
}
Message::PeriodicUpdate => {
let values = self
.update_subscriptions()
.chain_err(|| "failed to update subscriptions")?;
self.send_values(&values)?
}
Message::Done => {
self.chan.close();
return Ok(());
}
}
}
recv(shutdown) -> _ => {
self.chan.close();
return Ok(());
}
}
}
}
fn handle_requests(
mut reader: BufReader<TcpStream>,
tx: crossbeam_channel::Sender<Message>,
) -> Result<()> {
loop {
let mut line = Vec::<u8>::new();
reader
.read_until(b'\n', &mut line)
.chain_err(|| "failed to read a request")?;
if line.is_empty() {
tx.send(Message::Done).chain_err(|| "channel closed")?;
return Ok(());
} else {
if line.starts_with(&[22, 3, 1]) {
// (very) naive SSL handshake detection
let _ = tx.send(Message::Done);
bail!("invalid request - maybe SSL-encrypted data?: {:?}", line)
}
match String::from_utf8(line) {
Ok(req) => tx
.send(Message::Request(req))
.chain_err(|| "channel closed")?,
Err(err) => {
let _ = tx.send(Message::Done);
bail!("invalid UTF8: {}", err)
}
}
}
}
}
pub fn run(mut self) {
self.stats.clients.inc();
let reader = BufReader::new(self.stream.try_clone().expect("failed to clone TcpStream"));
let tx = self.chan.sender();
let die_please = self.die_please.take().unwrap();
let (reply_killer, reply_receiver) = crossbeam_channel::unbounded();
// We create a clone of the stream and put it in an Arc
// This will drop at the end of the function.
let arc_stream = Arc::new(self.stream.try_clone().expect("failed to clone TcpStream"));
// We don't want to keep the stream alive until SIGINT
// It should drop (close) no matter what.
let maybe_stream = Arc::downgrade(&arc_stream);
spawn_thread("properly-die", move || {
let _ = die_please.recv();
let _ = maybe_stream.upgrade().map(|s| s.shutdown(Shutdown::Both));
let _ = reply_killer.send(());
});
let child = spawn_thread("reader", || Connection::handle_requests(reader, tx));
if let Err(e) = self.handle_replies(reply_receiver) {
error!(
"[{}] connection handling failed: {}",
self.addr,
e.display_chain().to_string()
);
}
self.stats.clients.dec();
self.stats
.subscriptions
.sub(self.status_hashes.len() as i64);
debug!("[{}] shutting down connection", self.addr);
// Drop the Arc so that the stream properly closes.
drop(arc_stream);
let _ = self.stream.shutdown(Shutdown::Both);
if let Err(err) = child.join().expect("receiver panicked") {
error!("[{}] receiver failed: {}", self.addr, err);
}
}
}
fn get_history(
query: &Query,
scripthash: &[u8],
txs_limit: usize,
) -> Result<Vec<(Txid, Option<BlockId>)>> {
// to avoid silently trunacting history entries, ask for one extra more than the limit and fail if it exists
let history_txids = query.history_txids(scripthash, txs_limit + 1);
ensure!(history_txids.len() <= txs_limit, ErrorKind::TooPopular);
Ok(history_txids)
}
#[derive(Serialize, Debug)]
struct GetHistoryResult {
#[serde(rename = "tx_hash")]
txid: Txid,
height: isize,
#[serde(skip_serializing_if = "Option::is_none")]
fee: Option<u64>,
}
#[derive(Debug)]
pub enum Message {
Request(String),
PeriodicUpdate,
Done,
}
pub enum Notification {
Periodic,
Exit,
}
pub struct RPC {
notification: Sender<Notification>,
server: Option<thread::JoinHandle<()>>, // so we can join the server while dropping this ojbect
}
struct Stats {
latency: HistogramVec,
clients: Gauge,
subscriptions: Gauge,
}
impl RPC {
fn start_notifier(
notification: Channel<Notification>,
senders: Arc<Mutex<Vec<crossbeam_channel::Sender<Message>>>>,
acceptor: Sender<Option<(TcpStream, SocketAddr)>>,
acceptor_shutdown: Sender<()>,
) {
spawn_thread("notification", move || {
for msg in notification.receiver().iter() {
let mut senders = senders.lock().unwrap();
match msg {
Notification::Periodic => {
for sender in senders.split_off(0) {
if let Err(crossbeam_channel::TrySendError::Disconnected(_)) =
sender.try_send(Message::PeriodicUpdate)
{
continue;
}
senders.push(sender);
}
}
Notification::Exit => {
acceptor_shutdown.send(()).unwrap(); // Stop the acceptor itself
acceptor.send(None).unwrap(); // mark acceptor as done
break;
}
}
}
});
}
fn start_acceptor(
addr: SocketAddr,
shutdown_channel: Channel<()>,
) -> Channel<Option<(TcpStream, SocketAddr)>> {
let chan = Channel::unbounded();
let acceptor = chan.sender();
spawn_thread("acceptor", move || {
let socket = create_socket(&addr);
socket.listen(511).expect("setting backlog failed");
socket
.set_nonblocking(false)
.expect("cannot set nonblocking to false");
let listener = TcpListener::from(socket);
let local_addr = listener.local_addr().unwrap();
let shutdown_bool = Arc::new(AtomicBool::new(false));
{
let shutdown_bool = Arc::clone(&shutdown_bool);
crate::util::spawn_thread("shutdown-acceptor", move || {
// Block until shutdown is sent.
let _ = shutdown_channel.receiver().recv();
// Store the bool so after the next accept it will break the loop
shutdown_bool.store(true, std::sync::atomic::Ordering::Release);
// Connect to the socket to cause it to unblock
let _ = TcpStream::connect(local_addr);
});
}
info!("Electrum RPC server running on {}", addr);
loop {
let (stream, addr) = listener.accept().expect("accept failed");
if shutdown_bool.load(std::sync::atomic::Ordering::Acquire) {
break;
}
stream
.set_nonblocking(false)
.expect("failed to set connection as blocking");
acceptor.send(Some((stream, addr))).expect("send failed");
}
});
chan
}
pub fn start(config: Arc<Config>, query: Arc<Query>, metrics: &Metrics) -> RPC {
let stats = Arc::new(Stats {
latency: metrics.histogram_vec(
HistogramOpts::new("electrum_rpc", "Electrum RPC latency (seconds)"),
&["method"],
),
clients: metrics.gauge(MetricOpts::new("electrum_clients", "# of Electrum clients")),
subscriptions: metrics.gauge(MetricOpts::new(
"electrum_subscriptions",
"# of Electrum subscriptions",
)),
});
stats.clients.set(0);
stats.subscriptions.set(0);
let notification = Channel::unbounded();
// Discovery is enabled when electrum-public-hosts is set
#[cfg(feature = "electrum-discovery")]
let discovery = config.electrum_public_hosts.clone().map(|hosts| {
use crate::chain::genesis_hash;
let features = ServerFeatures {
hosts,
server_version: format!("electrs-esplora {}", ELECTRS_VERSION),
genesis_hash: genesis_hash(config.network_type),
protocol_min: PROTOCOL_VERSION,
protocol_max: PROTOCOL_VERSION,
hash_function: "sha256".into(),
pruning: None,
};
let discovery = Arc::new(DiscoveryManager::new(
config.network_type,
features,
PROTOCOL_VERSION,
config.electrum_announce,
config.tor_proxy,
));
DiscoveryManager::spawn_jobs_thread(Arc::clone(&discovery));
discovery
});
let rpc_addr = config.electrum_rpc_addr;
let txs_limit = config.electrum_txs_limit;
RPC {
notification: notification.sender(),
server: Some(spawn_thread("rpc", move || {
let senders =
Arc::new(Mutex::new(Vec::<crossbeam_channel::Sender<Message>>::new()));
let acceptor_shutdown = Channel::unbounded();
let acceptor_shutdown_sender = acceptor_shutdown.sender();
let acceptor = RPC::start_acceptor(rpc_addr, acceptor_shutdown);
RPC::start_notifier(
notification,
senders.clone(),
acceptor.sender(),
acceptor_shutdown_sender,
);
let mut threads = HashMap::new();
let (garbage_sender, garbage_receiver) = crossbeam_channel::unbounded();
while let Some((stream, addr)) = acceptor.receiver().recv().unwrap() {
// explicitely scope the shadowed variables for the new thread
let query = Arc::clone(&query);
let senders = Arc::clone(&senders);
let stats = Arc::clone(&stats);
let garbage_sender = garbage_sender.clone();
// Kill the peers properly
let (killer, peace_receiver) = std::sync::mpsc::channel();
let killer_clone = killer.clone();
#[cfg(feature = "electrum-discovery")]
let discovery = discovery.clone();
let spawned = spawn_thread("peer", move || {
info!("[{}] connected peer", addr);
let conn = Connection::new(
query,
stream,
addr,
stats,
txs_limit,
peace_receiver,
#[cfg(feature = "electrum-discovery")]
discovery,
);
senders.lock().unwrap().push(conn.chan.sender());
conn.run();
info!("[{}] disconnected peer", addr);
let _ = killer_clone.send(());
let _ = garbage_sender.send(std::thread::current().id());
});
trace!("[{}] spawned {:?}", addr, spawned.thread().id());
threads.insert(spawned.thread().id(), (spawned, killer));
while let Ok(id) = garbage_receiver.try_recv() {
if let Some((thread, killer)) = threads.remove(&id) {
trace!("[{}] joining {:?}", addr, id);
let _ = killer.send(());
if let Err(error) = thread.join() {
error!("failed to join {:?}: {:?}", id, error);
}
}
}
}
// Drop these
drop(acceptor);
drop(garbage_receiver);
trace!("closing {} RPC connections", senders.lock().unwrap().len());
for sender in senders.lock().unwrap().iter() {
let _ = sender.try_send(Message::Done);
}
for (id, (thread, killer)) in threads {
trace!("joining {:?}", id);
let _ = killer.send(());
if let Err(error) = thread.join() {
error!("failed to join {:?}: {:?}", id, error);
}
}
trace!("RPC connections are closed");
})),
}
}
pub fn notify(&self) {
self.notification.send(Notification::Periodic).unwrap();
}
}
impl Drop for RPC {
fn drop(&mut self) {
trace!("stop accepting new RPCs");
self.notification.send(Notification::Exit).unwrap();
if let Some(handle) = self.server.take() {
handle.join().unwrap();
}
trace!("RPC server is stopped");
crate::util::with_spawned_threads(|threads| {
trace!("Threads after dropping RPC: {:?}", threads);
});
}
}