1use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
13use std::net::{IpAddr, Shutdown, SocketAddr, TcpListener, TcpStream};
14use std::sync::mpsc::Sender;
15use std::sync::{Arc, Mutex, RwLock};
16use std::time::{Duration, Instant, UNIX_EPOCH};
17
18use heika_block::Block;
19use heika_block::finalization::FinalizationRound;
20use heika_block::finalization::proof::proof_header;
21use heika_core::key::PublicKey;
22use heika_core::network::NetworkParameters;
23use heika_mempool::SharedMempool;
24use heika_mempool::partial::SharedPartialPool;
25use heika_packet::partial::{
26 read_pull_partial_request, split_detached_cosignatures, write_partial_infos,
27};
28use heika_packet::{
29 BlockHashesRequest, ChainStatistics, NetworkTime, PullBlocksRequest, extension, packet_type,
30 read_pull_transactions_request, split_size_prefixed,
31};
32use heika_tls::proxy_protocol::{IpRange, read_header};
33use heika_tls::{Connection, RequestError, ServerConfig};
34use heika_transaction::DetachedCosignature;
35
36use heika_chain::chain::Status;
37use heika_chain::env::Env;
38use heika_chain::event::{ChainEvent, PULL_BLOCKS, PULL_HASHES};
39use heika_chain::verify::verify_alone;
40use heika_store_redb::Db;
41
42use crate::finalization::Observer;
43use crate::partials::Incoming;
44use crate::peer_thread::NodeEvent;
45
46pub const MAX_RESPONSE_BYTES: u32 = 16 * 1024 * 1024;
48const MAX_REQUEST_BYTES: usize = 32 * 1024 * 1024;
50pub const MAX_CONNECTIONS: usize = 16;
52const MAX_PER_KEY: usize = 3;
54const MAX_PER_ADDRESS: usize = 4;
57const ACCEPTS_PER_SECOND: f64 = 2.0;
59const ACCEPT_BURST: f64 = 20.0;
60const HANDSHAKE_TIMEOUT: Duration = Duration::from_secs(10);
62const WRITE_TIMEOUT: Duration = Duration::from_secs(30);
64const IDLE_TIMEOUT: Duration = Duration::from_secs(120);
67const BAN: Duration = Duration::from_secs(12 * 60 * 60);
69const REQUESTS_PER_SECOND: f64 = 5.0;
71const REQUEST_BURST: f64 = 50.0;
72const BYTES_PER_SECOND: f64 = 4.0 * 1024.0 * 1024.0;
74const BYTE_BURST: f64 = 32.0 * 1024.0 * 1024.0;
75const TOTAL_REQUESTS_PER_SECOND: f64 = 30.0;
77const TOTAL_REQUEST_BURST: f64 = 300.0;
78const TOTAL_BYTES_PER_SECOND: f64 = 8.0 * 1024.0 * 1024.0;
79const TOTAL_BYTE_BURST: f64 = 64.0 * 1024.0 * 1024.0;
80const POLL: Duration = Duration::from_millis(200);
82
83pub trait Source: Sync {
85 fn status(&self) -> Status;
86 fn peers(&self) -> Arc<Vec<u8>>;
88 fn block(&self, height: u64) -> Result<Option<Vec<u8>>, String>;
90 fn proof(&self, epoch: u32) -> Result<Option<Vec<u8>>, String>;
92}
93
94#[derive(Debug, PartialEq, Eq)]
96pub enum Answer {
97 Reply(u32, Vec<u8>),
99 Nothing,
101 Pushed(Box<Block>, Vec<u8>),
103 Close(String),
105 Fail(String),
107}
108
109pub struct Responder<'a> {
111 pub source: &'a dyn Source,
112 pub env: &'a (dyn Env + Sync),
113 pub parameters: &'static NetworkParameters,
114 pub node: Vec<u8>,
116 pub pushes: Option<Sender<NodeEvent>>,
118 pub mempool: Option<&'a SharedMempool>,
120 pub partials: Option<&'a SharedPartialPool>,
123 pub votes: Option<&'a Mutex<Observer>>,
126 pub capabilities: &'a [&'static str],
128 pub source_code: Option<&'static [u8]>,
130}
131
132impl Responder<'_> {
133 pub fn answer(&self, request_type: u32, body: &[u8]) -> Answer {
135 let received = self.network_time();
137 match self.answer_inner(request_type, body, received) {
138 Ok(answer) => answer,
139 Err(error) => Answer::Fail(error),
140 }
141 }
142
143 fn answer_inner(
144 &self,
145 request_type: u32,
146 body: &[u8],
147 received: u64,
148 ) -> Result<Answer, String> {
149 let reply = |body: Vec<u8>| Ok(Answer::Reply(request_type, body));
150 let empty = body.is_empty();
152 match request_type {
153 packet_type::CHAIN_STATISTICS if empty => {
154 let status = self.source.status();
155 reply(
156 ChainStatistics {
157 height: status.height,
158 finalized_height: status.finalized.height,
159 score: status.score,
160 }
161 .encode()
162 .to_vec(),
163 )
164 }
165 packet_type::BLOCK_HASHES => match BlockHashesRequest::decode(body) {
166 Ok(request) => reply(self.hashes(request)?),
167 Err(_) => Ok(Answer::Nothing),
168 },
169 packet_type::PULL_BLOCKS => match PullBlocksRequest::decode(body) {
170 Ok(request) => reply(self.blocks(request)?),
171 Err(_) => Ok(Answer::Nothing),
172 },
173 packet_type::PULL_BLOCK => match <[u8; 8]>::try_from(body) {
174 Ok(height) => reply(self.block(u64::from_le_bytes(height))?),
175 Err(_) => Ok(Answer::Nothing),
176 },
177 packet_type::FINALIZATION_STATISTICS if empty => {
178 reply(self.source.status().finalized.to_bytes().to_vec())
179 }
180 packet_type::FINALIZATION_PROOF_AT_EPOCH => match <[u8; 4]>::try_from(body) {
181 Ok(epoch) => Ok(Answer::Reply(
182 packet_type::PULL_FINALIZATION_PROOF,
183 self.proof_at_epoch(u32::from_le_bytes(epoch))?,
184 )),
185 Err(_) => Ok(Answer::Nothing),
186 },
187 packet_type::FINALIZATION_PROOF_AT_HEIGHT => match <[u8; 8]>::try_from(body) {
188 Ok(height) => Ok(Answer::Reply(
189 packet_type::PULL_FINALIZATION_PROOF,
190 self.proof_at_height(u64::from_le_bytes(height))?,
191 )),
192 Err(_) => Ok(Answer::Nothing),
193 },
194 packet_type::NODE_DISCOVERY_PULL_PING if empty => reply(self.node.clone()),
195 packet_type::NODE_DISCOVERY_PULL_PEERS if empty => reply(self.source.peers().to_vec()),
196 packet_type::TIME_SYNC_NETWORK_TIME if empty => reply(
197 NetworkTime {
198 receive: received,
199 send: self.network_time(),
200 }
201 .encode()
202 .to_vec(),
203 ),
204 packet_type::PULL_TRANSACTIONS => {
205 let (min_deadline, min_fee_multiplier, known) =
206 match read_pull_transactions_request(body) {
207 Ok(request) => request,
208 Err(error) => {
209 return Ok(Answer::Close(format!(
210 "未承認のトランザクションの要求を読めません: {error}"
211 )));
212 }
213 };
214 let Some(mempool) = self.mempool else {
215 return reply(Vec::new());
216 };
217 let known: HashSet<u32> = known.into_iter().collect();
218 let mempool = mempool.lock();
219 reply(
220 mempool
221 .pull(min_deadline, min_fee_multiplier, &known)
222 .concat(),
223 )
224 }
225 packet_type::PULL_PARTIAL_TRANSACTION_INFOS => {
226 let Ok((min_deadline, known)) = read_pull_partial_request(body) else {
227 return Ok(Answer::Close(
228 "連署を待つトランザクションの要求を読めません".to_owned(),
229 ));
230 };
231 let Some(partials) = self.partials else {
232 return reply(Vec::new());
233 };
234 let known: HashMap<u32, u32> = known
235 .into_iter()
236 .map(|pair| (pair.transaction, pair.cosignatures))
237 .collect();
238 let partials = partials.lock();
239 reply(write_partial_infos(
240 &partials.unknown_to(min_deadline, &known),
241 ))
242 }
243 packet_type::PULL_FINALIZATION_MESSAGES => {
245 if body.len() < 16 || !(body.len() - 16).is_multiple_of(4) {
246 return Ok(Answer::Close(
247 "投票のメッセージの要求を読めません".to_owned(),
248 ));
249 }
250 let Some(votes) = self.votes else {
251 return reply(Vec::new());
252 };
253 let u32_at = |offset: usize| {
254 u32::from_le_bytes(body[offset..offset + 4].try_into().expect("4 bytes"))
255 };
256 let round = |offset| FinalizationRound {
257 epoch: u32_at(offset),
258 point: u32_at(offset + 4),
259 };
260 let known: BTreeSet<u32> = (16..body.len()).step_by(4).map(u32_at).collect();
261 let votes = votes.lock().expect("not poisoned");
262 reply(votes.unknown_to(round(0), round(8), &known))
263 }
264 packet_type::CHAIN_STATISTICS
265 | packet_type::FINALIZATION_STATISTICS
266 | packet_type::NODE_DISCOVERY_PULL_PING
267 | packet_type::NODE_DISCOVERY_PULL_PEERS
268 | packet_type::TIME_SYNC_NETWORK_TIME => Ok(Answer::Nothing),
269 packet_type::PUSH_BLOCK => {
270 let block = match Block::from_bytes(body) {
271 Ok(block) => block,
272 Err(error) => {
273 return Ok(Answer::Close(format!(
274 "押し付けられたブロックを読めません: {error}"
275 )));
276 }
277 };
278 if let Err(error) = verify_alone(self.parameters, &block) {
279 return Ok(Answer::Close(format!(
280 "押し付けられた高さ {} を弾きます: {error}",
281 block.height
282 )));
283 }
284 Ok(Answer::Pushed(Box::new(block), body.to_vec()))
285 }
286 packet_type::PUSH_TRANSACTIONS => {
287 let Ok(transactions) = split_size_prefixed(body) else {
289 return Ok(Answer::Nothing);
290 };
291 if let Some(mempool) = self.mempool {
292 let height = self.source.status().height + 1;
294 let mut added = Vec::new();
295 {
296 let mut mempool = mempool.lock();
297 for bytes in transactions {
298 if let Ok(hash) = mempool.add(bytes.to_vec(), received, height) {
299 println!("未承認のトランザクション {hash} を受け付けました");
300 added.extend_from_slice(bytes);
301 }
302 }
303 }
304 if !added.is_empty()
306 && let Some(pushes) = &self.pushes
307 {
308 let _ = pushes.send(NodeEvent::Relay {
309 transactions: Arc::new(added),
310 except: None,
311 });
312 }
313 }
314 Ok(Answer::Nothing)
315 }
316 packet_type::PUSH_PARTIAL_TRANSACTIONS => {
318 if let (Ok(transactions), Some(pushes)) = (split_size_prefixed(body), &self.pushes)
319 {
320 let transactions = transactions.into_iter().map(<[u8]>::to_vec).collect();
321 let _ = pushes.send(NodeEvent::Partial {
322 incoming: Incoming::Transactions(transactions),
323 from: None,
324 });
325 }
326 Ok(Answer::Nothing)
327 }
328 packet_type::PUSH_DETACHED_COSIGNATURES => {
329 if let (Ok(cosignatures), Some(pushes)) =
330 (split_detached_cosignatures(body), &self.pushes)
331 {
332 let cosignatures = cosignatures
333 .into_iter()
334 .filter_map(|bytes| DetachedCosignature::from_bytes(bytes).ok())
335 .collect();
336 let _ = pushes.send(NodeEvent::Partial {
337 incoming: Incoming::Cosignatures(cosignatures),
338 from: None,
339 });
340 }
341 Ok(Answer::Nothing)
342 }
343 packet_type::PUSH_FINALIZATION_MESSAGES => {
345 if self.votes.is_some()
346 && let (Ok(messages), Some(pushes)) = (split_size_prefixed(body), &self.pushes)
347 {
348 let _ = pushes.send(NodeEvent::Votes {
349 messages: messages.into_iter().map(<[u8]>::to_vec).collect(),
350 from: None,
351 });
352 }
353 Ok(Answer::Nothing)
354 }
355 extension::ENVELOPE => match extension::read_envelope(body) {
356 Ok((extension::SOURCE_ZIP, [])) => match self.source_code {
357 Some(zip) => reply(extension::envelope_body(extension::SOURCE_ZIP, zip)),
358 None => Ok(Answer::Nothing),
359 },
360 Ok(_) => Ok(Answer::Nothing),
362 Err(error) => Ok(Answer::Close(format!("封筒が読めません: {error}"))),
363 },
364 packet_type::NODE_DISCOVERY_PUSH_PING | packet_type::NODE_DISCOVERY_PUSH_PEERS => {
366 Ok(Answer::Nothing)
367 }
368 _ => Ok(Answer::Close(format!(
369 "知らない種類 {request_type:#x} の要求が来ました"
370 ))),
371 }
372 }
373
374 fn network_time(&self) -> u64 {
376 let epoch = UNIX_EPOCH + self.parameters.epoch_adjustment;
377 let elapsed = self
378 .env
379 .now()
380 .duration_since(epoch)
381 .unwrap_or_default()
382 .as_millis();
383 u64::try_from(elapsed).unwrap_or(u64::MAX)
384 }
385
386 fn available(&self, height: u64) -> Option<u64> {
389 let tip = self.source.status().height;
390 (height != 0 && height <= tip).then(|| tip - height + 1)
391 }
392
393 fn hashes(&self, request: BlockHashesRequest) -> Result<Vec<u8>, String> {
394 let Some(available) = self.available(request.height) else {
395 return Ok(Vec::new());
396 };
397 let count = u64::from(request.num_hashes.min(PULL_HASHES)).min(available);
398 let mut hashes = Vec::new();
399 for height in request.height..request.height + count {
400 let Some(bytes) = self.source.block(height)? else {
402 break;
403 };
404 let block = Block::from_bytes(&bytes).map_err(|error| error.to_string())?;
405 hashes.extend_from_slice(&block.hash().0);
406 }
407 Ok(hashes)
408 }
409
410 fn blocks(&self, request: PullBlocksRequest) -> Result<Vec<u8>, String> {
411 let Some(available) = self.available(request.height) else {
412 return Ok(Vec::new());
413 };
414 let count = u64::from(request.num_blocks.min(PULL_BLOCKS)).min(available);
415 let max_bytes = request.num_response_bytes.min(MAX_RESPONSE_BYTES) as usize;
416 let mut blocks = Vec::new();
417 for height in request.height..request.height + count {
418 let Some(bytes) = self.source.block(height)? else {
419 break;
420 };
421 if !blocks.is_empty() && blocks.len() + bytes.len() > max_bytes {
423 break;
424 }
425 blocks.extend_from_slice(&bytes);
426 }
427 Ok(blocks)
428 }
429
430 fn block(&self, height: u64) -> Result<Vec<u8>, String> {
432 let tip = self.source.status().height;
433 let height = if height == 0 { tip } else { height };
434 if height > tip {
435 return Ok(Vec::new());
436 }
437 Ok(self.source.block(height)?.unwrap_or_default())
438 }
439
440 fn proof_at_epoch(&self, epoch: u32) -> Result<Vec<u8>, String> {
441 if epoch == 0 || epoch > self.source.status().finalized.round.epoch {
442 return Ok(Vec::new());
443 }
444 Ok(self.source.proof(epoch)?.unwrap_or_default())
445 }
446
447 fn proof_at_height(&self, height: u64) -> Result<Vec<u8>, String> {
450 let finalized = self.source.status().finalized;
451 if height == 0 || height > finalized.height {
452 return Ok(Vec::new());
453 }
454 let (mut low, mut high) = (1, finalized.round.epoch);
455 while low <= high {
456 let epoch = low + (high - low) / 2;
457 let Some(proof) = self.source.proof(epoch)? else {
458 return Ok(Vec::new());
459 };
460 let found = proof_header(&proof)
461 .map_err(|error| error.to_string())?
462 .height;
463 match found.cmp(&height) {
464 std::cmp::Ordering::Equal => return Ok(proof),
465 std::cmp::Ordering::Less => low = epoch + 1,
466 std::cmp::Ordering::Greater => high = epoch - 1,
467 }
468 }
469 Ok(Vec::new())
470 }
471}
472
473pub struct DbSource<'a> {
475 pub db: &'a Db,
476 pub status: &'a RwLock<Status>,
477 pub peers: &'a RwLock<Arc<Vec<u8>>>,
478}
479
480impl Source for DbSource<'_> {
481 fn status(&self) -> Status {
482 *self.status.read().expect("not poisoned")
483 }
484
485 fn peers(&self) -> Arc<Vec<u8>> {
486 Arc::clone(&self.peers.read().expect("not poisoned"))
487 }
488
489 fn block(&self, height: u64) -> Result<Option<Vec<u8>>, String> {
490 self.db.block(height).map_err(|error| error.to_string())
491 }
492
493 fn proof(&self, epoch: u32) -> Result<Option<Vec<u8>>, String> {
494 self.db.proof(epoch).map_err(|error| error.to_string())
495 }
496}
497
498pub struct Gate {
501 state: Mutex<GateState>,
502 requests: Mutex<Bucket>,
504 bytes: Mutex<Bucket>,
505 accepts: Mutex<Bucket>,
506 per_address: usize,
508 exempt_local: bool,
509 proxies: Vec<IpRange>,
511}
512
513#[derive(Default)]
514struct GateState {
515 open: Vec<Open>,
516 banned: HashMap<PublicKey, Instant>,
517}
518
519struct Open {
520 id: usize,
521 socket: TcpStream,
523 ip: IpAddr,
524 key: Option<PublicKey>,
526}
527
528impl Default for Gate {
529 fn default() -> Self {
530 let now = Instant::now();
531 Self {
532 state: Mutex::default(),
533 requests: Mutex::new(Bucket::new(
534 TOTAL_REQUEST_BURST,
535 TOTAL_REQUESTS_PER_SECOND,
536 now,
537 )),
538 bytes: Mutex::new(Bucket::new(TOTAL_BYTE_BURST, TOTAL_BYTES_PER_SECOND, now)),
539 accepts: Mutex::new(Bucket::new(ACCEPT_BURST, ACCEPTS_PER_SECOND, now)),
540 per_address: MAX_PER_ADDRESS,
541 exempt_local: true,
542 proxies: Vec::new(),
543 }
544 }
545}
546
547impl Gate {
548 pub fn with_proxies(self, proxies: Vec<IpRange>) -> Self {
550 Self { proxies, ..self }
551 }
552
553 fn full(&self, state: &GateState, ip: IpAddr, id: Option<usize>) -> bool {
555 !(self.exempt_local && is_local(ip))
556 && state
557 .open
558 .iter()
559 .filter(|open| open.ip == ip && Some(open.id) != id)
560 .count()
561 >= self.per_address
562 }
563
564 pub fn cut(&self, key: PublicKey) {
567 let state = self.state.lock().expect("not poisoned");
568 for open in state.open.iter().filter(|open| open.key == Some(key)) {
569 let _ = open.socket.shutdown(Shutdown::Both);
570 }
571 }
572
573 pub fn ban(&self, key: PublicKey) {
576 let mut state = self.state.lock().expect("not poisoned");
577 state.banned.insert(key, Instant::now() + BAN);
578 for open in state.open.iter().filter(|open| open.key == Some(key)) {
579 let _ = open.socket.shutdown(Shutdown::Both);
580 }
581 }
582
583 fn take(bucket: &Mutex<Bucket>, amount: f64) -> Duration {
585 bucket
586 .lock()
587 .expect("not poisoned")
588 .take(amount, Instant::now())
589 }
590}
591
592enum Ending {
594 Closed,
595 Failed(String),
597 Misbehaved(String),
599}
600
601pub fn serve(
604 listener: TcpListener,
605 config: Arc<ServerConfig>,
606 responder: &Responder<'_>,
607 gate: &Gate,
608 stopping: &(dyn Fn() -> bool + Sync),
609) -> std::io::Result<()> {
610 listener.set_nonblocking(true)?;
611 std::thread::scope(|scope| {
612 let mut next = 0;
613 while !stopping() {
614 let (socket, address) = match listener.accept() {
615 Ok(accepted) => accepted,
616 Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => {
617 std::thread::sleep(POLL);
618 continue;
619 }
620 Err(error) => {
621 eprintln!("接続を受けられませんでした: {error}");
622 std::thread::sleep(POLL);
623 continue;
624 }
625 };
626 let accepted = gate
629 .accepts
630 .lock()
631 .expect("not poisoned")
632 .try_take(1.0, Instant::now());
633 if !accepted {
634 eprintln!("{address} からの接続は、新しい接続が多すぎるので切ります");
635 continue;
636 }
637 let mut locked = gate.state.lock().expect("not poisoned");
638 if locked.open.len() >= MAX_CONNECTIONS {
639 eprintln!(
640 "{address} からの接続は、もう {MAX_CONNECTIONS} 本受けているので切ります"
641 );
642 continue;
643 }
644 let ip = address.ip();
645 let proxied = gate.proxies.iter().any(|range| range.contains(ip));
647 if !proxied && gate.full(&locked, ip, None) {
648 eprintln!(
649 "{address} からの接続は、同じアドレスからもう {} 本受けているので切ります",
650 gate.per_address
651 );
652 continue;
653 }
654 let Ok(handle) = socket
655 .set_nonblocking(false)
656 .and_then(|()| socket.try_clone())
657 else {
658 continue;
659 };
660 let id = next;
661 next += 1;
662 locked.open.push(Open {
663 id,
664 socket: handle,
665 ip,
666 key: None,
667 });
668 drop(locked);
669 let config = Arc::clone(&config);
670 scope.spawn(move || {
671 let started = Instant::now();
672 let mut requests = BTreeMap::new();
673 let mut address = address;
674 let ending = respond(
675 socket,
676 &mut address,
677 proxied,
678 config,
679 responder,
680 gate,
681 id,
682 stopping,
683 &mut requests,
684 );
685 let mut locked = gate.state.lock().expect("not poisoned");
686 let index = locked.open.iter().position(|open| open.id == id);
687 let key = index.and_then(|index| locked.open.remove(index).key);
688 let who = key.map_or_else(String::new, |key| {
690 format!("、鍵 {}…", &key.to_string()[..8])
691 });
692 let reason = match ending {
693 _ if stopping() => "止めるので切りました".to_owned(),
695 Ending::Closed => "相手が閉じました".to_owned(),
696 Ending::Failed(error) => error,
697 Ending::Misbehaved(error) => match key {
698 Some(key) => {
699 locked.banned.insert(key, Instant::now() + BAN);
700 format!("{error}。この鍵は {} 時間受けません", BAN.as_secs() / 3600)
701 }
702 None => error,
703 },
704 };
705 drop(locked);
706 let requests: Vec<String> = requests
707 .iter()
708 .map(|(request_type, count)| format!("{request_type:#x}×{count}"))
709 .collect();
710 println!(
711 "{address} からの接続を終えました: {reason}({:.1} 秒{who}、要求 {})",
712 started.elapsed().as_secs_f64(),
713 if requests.is_empty() {
714 "なし".to_owned()
715 } else {
716 requests.join(" ")
717 }
718 );
719 });
720 }
721 for open in &gate.state.lock().expect("not poisoned").open {
722 let _ = open.socket.shutdown(Shutdown::Both);
723 }
724 });
725 Ok(())
726}
727
728#[allow(clippy::too_many_arguments)]
731fn respond(
732 mut socket: TcpStream,
733 address: &mut SocketAddr,
734 proxied: bool,
735 config: Arc<ServerConfig>,
736 responder: &Responder<'_>,
737 gate: &Gate,
738 id: usize,
739 stopping: &(dyn Fn() -> bool + Sync),
740 requests: &mut BTreeMap<u32, usize>,
741) -> Ending {
742 let failed = |error: &dyn std::fmt::Display| Ending::Failed(error.to_string());
743 if let Err(error) = socket.set_read_timeout(Some(HANDSHAKE_TIMEOUT)) {
744 return failed(&error);
745 }
746 if proxied {
747 let source = match read_header(&mut socket) {
748 Ok(header) => header.source_or(*address),
749 Err(error) => return failed(&error),
750 };
751 let mut state = gate.state.lock().expect("not poisoned");
752 if gate.full(&state, source.ip(), Some(id)) {
753 return Ending::Failed(format!(
754 "{source} からは、同じアドレスからもう {} 本受けているので切ります({address} の中継)",
755 gate.per_address
756 ));
757 }
758 if let Some(open) = state.open.iter_mut().find(|open| open.id == id) {
759 open.ip = source.ip();
760 }
761 *address = source;
762 }
763 let started = socket.peek(&mut [0]);
765 match started {
766 Ok(0) => return Ending::Failed("TLS を始めずに閉じました".to_owned()),
767 Ok(_) => {}
768 Err(error) => return failed(&error),
769 }
770 let mut connection =
771 match Connection::accept(socket, config, responder.capabilities, HANDSHAKE_TIMEOUT) {
772 Ok(connection) => connection,
773 Err(error) => return failed(&error),
774 };
775 let Some(key) = connection.peer_key() else {
776 return Ending::Failed("相手の鍵を読めません".to_owned());
777 };
778 if let Err(reason) = admit(gate, id, key) {
779 return Ending::Failed(reason);
780 }
781 let heika = if connection.is_heika() {
782 "、heika"
783 } else {
784 ""
785 };
786 println!("{address} から接続を受けました(鍵 {key}{heika})");
787 if let Err(error) = connection
788 .set_read_timeout(Some(IDLE_TIMEOUT))
789 .and_then(|()| connection.set_write_timeout(Some(WRITE_TIMEOUT)))
790 {
791 return failed(&error);
792 }
793 let now = Instant::now();
794 let mut request_budget = Bucket::new(REQUEST_BURST, REQUESTS_PER_SECOND, now);
795 let mut byte_budget = Bucket::new(BYTE_BURST, BYTES_PER_SECOND, now);
796 loop {
797 let (request_type, body) = match connection.receive_packet(MAX_REQUEST_BYTES) {
798 Ok(packet) => packet,
799 Err(RequestError::Io(error)) => {
800 return match error.kind() {
801 std::io::ErrorKind::UnexpectedEof => Ending::Closed,
802 std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut => {
803 Ending::Failed(format!(
804 "要求が {} 秒来なかったので切りました",
805 IDLE_TIMEOUT.as_secs()
806 ))
807 }
808 _ => failed(&error),
809 };
810 }
811 Err(
813 error @ (RequestError::TooLarge(_)
814 | RequestError::InvalidSize(_)
815 | RequestError::Malformed(_)),
816 ) => {
817 return Ending::Misbehaved(error.to_string());
818 }
819 Err(error) => return failed(&error),
820 };
821 *requests.entry(request_type).or_default() += 1;
822 throttle(
823 request_budget
824 .take(1.0, Instant::now())
825 .max(Gate::take(&gate.requests, 1.0)),
826 stopping,
827 );
828 let reply = match responder.answer(request_type, &body) {
829 Answer::Reply(reply_type, reply) => (reply_type, reply),
830 Answer::Nothing => continue,
831 Answer::Pushed(block, bytes) => {
832 if let Some(pushes) = &responder.pushes {
833 let _ = pushes.send(NodeEvent::Chain(ChainEvent::Pushed {
835 block,
836 bytes,
837 from: Some(key),
838 }));
839 }
840 continue;
841 }
842 Answer::Close(reason) => return Ending::Misbehaved(reason),
843 Answer::Fail(reason) => return Ending::Failed(reason),
844 };
845 let size = reply.1.len() as f64;
846 throttle(
847 byte_budget
848 .take(size, Instant::now())
849 .max(Gate::take(&gate.bytes, size)),
850 stopping,
851 );
852 if let Err(error) = connection.send_packet(reply.0, &reply.1) {
853 return failed(&error);
854 }
855 }
856}
857
858fn admit(gate: &Gate, id: usize, key: PublicKey) -> Result<(), String> {
860 let mut gate = gate.state.lock().expect("not poisoned");
861 let now = Instant::now();
862 gate.banned.retain(|_, until| *until > now);
863 if gate.banned.contains_key(&key) {
864 return Err(format!("鍵 {key} は、決まりを破ったのでしばらく受けません"));
865 }
866 let same = gate
867 .open
868 .iter()
869 .filter(|open| open.key == Some(key))
870 .count();
871 if same >= MAX_PER_KEY {
872 return Err(format!(
873 "鍵 {key} からは、もう {MAX_PER_KEY} 本受けているので切ります"
874 ));
875 }
876 if let Some(open) = gate.open.iter_mut().find(|open| open.id == id) {
877 open.key = Some(key);
878 }
879 Ok(())
880}
881
882fn is_local(ip: IpAddr) -> bool {
885 match ip {
886 IpAddr::V4(ip) => ip.is_loopback() || ip.is_private() || ip.is_link_local(),
887 IpAddr::V6(ip) => {
888 ip.is_loopback()
889 || ip.is_unique_local()
890 || ip.is_unicast_link_local()
891 || ip
892 .to_ipv4_mapped()
893 .is_some_and(|ip| is_local(IpAddr::V4(ip)))
894 }
895 }
896}
897
898fn throttle(delay: Duration, stopping: &(dyn Fn() -> bool + Sync)) {
900 let until = Instant::now() + delay;
901 while !stopping() {
902 let now = Instant::now();
903 if now >= until {
904 return;
905 }
906 std::thread::sleep((until - now).min(POLL));
907 }
908}
909
910struct Bucket {
912 level: f64,
913 burst: f64,
914 rate: f64,
915 last: Instant,
916}
917
918impl Bucket {
919 fn new(burst: f64, rate: f64, now: Instant) -> Self {
920 Self {
921 level: burst,
922 burst,
923 rate,
924 last: now,
925 }
926 }
927
928 fn try_take(&mut self, amount: f64, now: Instant) -> bool {
930 let elapsed = now.saturating_duration_since(self.last).as_secs_f64();
931 self.level = (self.level + elapsed * self.rate).min(self.burst);
932 self.last = now;
933 let enough = self.level >= amount;
934 if enough {
935 self.level -= amount;
936 }
937 enough
938 }
939
940 fn take(&mut self, amount: f64, now: Instant) -> Duration {
942 let elapsed = now.saturating_duration_since(self.last).as_secs_f64();
943 self.level = (self.level + elapsed * self.rate).min(self.burst) - amount;
944 self.last = now;
945 if self.level >= 0.0 {
946 Duration::ZERO
947 } else {
948 Duration::from_secs_f64(-self.level / self.rate)
949 }
950 }
951}
952
953#[cfg(test)]
954mod tests {
955 use std::time::SystemTime;
956
957 use heika_block::finalization::FinalizationRound;
958 use heika_core::address::Address;
959 use heika_core::hash::Hash256;
960 use heika_core::key::PrivateKey;
961 use heika_mempool::Mempool;
962 use heika_packet::{pull_blocks_request, pull_transactions_request, short_hash};
963 use heika_transaction::{Body, Transaction, Transfer, UnresolvedMosaicId};
964
965 use heika_block::finalization::FinalizedBlockHeader;
966
967 use super::*;
968
969 struct Memory {
971 blocks: BTreeMap<u64, Vec<u8>>,
972 proofs: BTreeMap<u32, Vec<u8>>,
973 status: Status,
974 }
975
976 fn block(height: u64) -> Vec<u8> {
978 let mut bytes = vec![0; 376];
979 bytes[..4].copy_from_slice(&376u32.to_le_bytes());
980 bytes[108] = 1;
981 bytes[109] = 0x98;
982 bytes[110..112].copy_from_slice(&0x8143u16.to_le_bytes());
983 bytes[112..120].copy_from_slice(&height.to_le_bytes());
984 bytes
985 }
986
987 fn proof(epoch: u32) -> Vec<u8> {
988 let header = FinalizedBlockHeader {
989 round: FinalizationRound { epoch, point: 1 },
990 height: u64::from(epoch) * 10,
991 hash: Hash256([epoch as u8; 32]),
992 };
993 let mut proof = Vec::new();
994 proof.extend_from_slice(&56u32.to_le_bytes());
995 proof.extend_from_slice(&1u32.to_le_bytes());
996 proof.extend_from_slice(&header.to_bytes());
997 proof
998 }
999
1000 fn memory(from: u64, to: u64, epochs: std::ops::RangeInclusive<u32>) -> Memory {
1001 let last = *epochs.end();
1002 Memory {
1003 blocks: (from..=to).map(|height| (height, block(height))).collect(),
1004 proofs: epochs.map(|epoch| (epoch, proof(epoch))).collect(),
1005 status: Status {
1006 height: to,
1007 score: (1 << 64) | 2,
1008 finalized: proof_header(&proof(last)).unwrap(),
1009 },
1010 }
1011 }
1012
1013 impl Source for Memory {
1014 fn status(&self) -> Status {
1015 self.status
1016 }
1017
1018 fn peers(&self) -> Arc<Vec<u8>> {
1019 Arc::new(b"peers".to_vec())
1020 }
1021
1022 fn block(&self, height: u64) -> Result<Option<Vec<u8>>, String> {
1023 Ok(self.blocks.get(&height).cloned())
1024 }
1025
1026 fn proof(&self, epoch: u32) -> Result<Option<Vec<u8>>, String> {
1027 Ok(self.proofs.get(&epoch).cloned())
1028 }
1029 }
1030
1031 struct FixedEnv(SystemTime);
1033
1034 impl Env for FixedEnv {
1035 fn now(&self) -> SystemTime {
1036 self.0
1037 }
1038 }
1039
1040 fn answer(source: &Memory, request_type: u32, body: &[u8]) -> Answer {
1041 answer_with(source, None, request_type, body)
1042 }
1043
1044 fn answer_with(
1046 source: &Memory,
1047 mempool: Option<&SharedMempool>,
1048 request_type: u32,
1049 body: &[u8],
1050 ) -> Answer {
1051 answer_pushing(source, mempool, None, request_type, body)
1052 }
1053
1054 fn answer_pushing(
1056 source: &Memory,
1057 mempool: Option<&SharedMempool>,
1058 pushes: Option<Sender<NodeEvent>>,
1059 request_type: u32,
1060 body: &[u8],
1061 ) -> Answer {
1062 let parameters = &NetworkParameters::TESTNET;
1063 let env = FixedEnv(parameters.epoch() + Duration::from_millis(1234));
1064 Responder {
1065 source,
1066 env: &env,
1067 parameters,
1068 node: b"node".to_vec(),
1069 pushes,
1070 mempool,
1071 partials: None,
1072 votes: None,
1073 capabilities: &[],
1074 source_code: None,
1075 }
1076 .answer(request_type, body)
1077 }
1078
1079 fn signed_transfer(key: u8) -> Vec<u8> {
1081 let parameters = &NetworkParameters::TESTNET;
1082 let private_key = PrivateKey::from_bytes(&[key; 32]);
1083 let public_key = PublicKey::from_private_key(&private_key);
1084 let recipient = Address::from_public_key(&public_key, parameters.identifier).into();
1085 let mosaics = BTreeMap::from([(UnresolvedMosaicId(parameters.currency_mosaic_id), 1)]);
1086 let body = Body::Transfer(Transfer::new(recipient, mosaics, Vec::new()).unwrap());
1087 let deadline = 1234 + 60 * 60 * 1000;
1088 let mut transaction =
1089 Transaction::new(public_key, parameters.identifier, 0, deadline, body);
1090 transaction
1091 .sign(&private_key, ¶meters.generation_hash_seed)
1092 .unwrap();
1093 transaction.to_bytes()
1094 }
1095
1096 fn reply(answer: Answer) -> Vec<u8> {
1097 match answer {
1098 Answer::Reply(_, body) => body,
1099 other => panic!("{other:?}"),
1100 }
1101 }
1102
1103 fn hashes_request(height: u64, count: u32) -> Vec<u8> {
1104 [&height.to_le_bytes()[..], &count.to_le_bytes()].concat()
1105 }
1106
1107 fn hash(height: u64) -> Vec<u8> {
1108 Block::from_bytes(&block(height)).unwrap().hash().0.to_vec()
1109 }
1110
1111 #[test]
1112 fn answers_chain_and_finalization_statistics() {
1113 let source = memory(1, 30, 1..=2);
1114 let body = reply(answer(&source, packet_type::CHAIN_STATISTICS, &[]));
1115 assert_eq!(
1116 ChainStatistics::decode(&body).unwrap(),
1117 ChainStatistics {
1118 height: 30,
1119 finalized_height: 20,
1120 score: (1 << 64) | 2
1121 }
1122 );
1123 let body = reply(answer(&source, packet_type::FINALIZATION_STATISTICS, &[]));
1124 assert_eq!(FinalizedBlockHeader::from_bytes(&body).unwrap().height, 20);
1125 assert_eq!(
1127 answer(&source, packet_type::CHAIN_STATISTICS, &[0]),
1128 Answer::Nothing
1129 );
1130 }
1131
1132 #[test]
1133 fn answers_hashes_and_blocks_like_catapult() {
1134 let source = memory(1, 30, 1..=2);
1135 let body = reply(answer(
1136 &source,
1137 packet_type::BLOCK_HASHES,
1138 &hashes_request(28, 10),
1139 ));
1140 assert_eq!(body, [hash(28), hash(29), hash(30)].concat());
1141 for height in [0, 31] {
1143 assert_eq!(
1144 reply(answer(
1145 &source,
1146 packet_type::BLOCK_HASHES,
1147 &hashes_request(height, 10)
1148 )),
1149 b""
1150 );
1151 }
1152 let body = reply(answer(
1153 &source,
1154 packet_type::PULL_BLOCKS,
1155 &pull_blocks_request(29, 10, 1 << 20),
1156 ));
1157 assert_eq!(body, [block(29), block(30)].concat());
1158 let body = reply(answer(
1160 &source,
1161 packet_type::PULL_BLOCKS,
1162 &pull_blocks_request(10, 10, 1),
1163 ));
1164 assert_eq!(body, block(10));
1165 let size = block(10).len() as u32;
1166 let body = reply(answer(
1167 &source,
1168 packet_type::PULL_BLOCKS,
1169 &pull_blocks_request(10, 10, 2 * size),
1170 ));
1171 assert_eq!(body, [block(10), block(11)].concat());
1172 assert_eq!(
1174 reply(answer(
1175 &source,
1176 packet_type::PULL_BLOCK,
1177 &0u64.to_le_bytes()
1178 )),
1179 block(30)
1180 );
1181 }
1182
1183 #[test]
1184 fn stops_at_pruned_blocks() {
1185 let source = memory(20, 30, 1..=2);
1186 assert_eq!(
1187 reply(answer(
1188 &source,
1189 packet_type::PULL_BLOCKS,
1190 &pull_blocks_request(10, 10, 1 << 20)
1191 )),
1192 b""
1193 );
1194 assert_eq!(
1195 reply(answer(
1196 &source,
1197 packet_type::BLOCK_HASHES,
1198 &hashes_request(19, 3)
1199 )),
1200 b""
1201 );
1202 }
1203
1204 #[test]
1205 fn answers_proofs_by_epoch_and_height() {
1206 let source = memory(1, 50, 1..=4);
1207 let at_epoch = |epoch: u32| match answer(
1208 &source,
1209 packet_type::FINALIZATION_PROOF_AT_EPOCH,
1210 &epoch.to_le_bytes(),
1211 ) {
1212 Answer::Reply(packet_type::PULL_FINALIZATION_PROOF, body) => body,
1213 other => panic!("{other:?}"),
1214 };
1215 assert_eq!(at_epoch(3), proof(3));
1216 assert_eq!(at_epoch(0), b"");
1217 assert_eq!(at_epoch(5), b"");
1218 let at_height = |height: u64| {
1219 reply_of(answer(
1220 &source,
1221 packet_type::FINALIZATION_PROOF_AT_HEIGHT,
1222 &height.to_le_bytes(),
1223 ))
1224 };
1225 for epoch in 1..=4 {
1226 assert_eq!(at_height(u64::from(epoch) * 10), proof(epoch));
1227 }
1228 assert_eq!(at_height(25), b"");
1229 assert_eq!(at_height(50), b"");
1230 }
1231
1232 fn reply_of(answer: Answer) -> Vec<u8> {
1233 match answer {
1234 Answer::Reply(packet_type::PULL_FINALIZATION_PROOF, body) => body,
1235 other => panic!("{other:?}"),
1236 }
1237 }
1238
1239 #[test]
1240 fn answers_ping_time_peers_and_empty_lists() {
1241 let source = memory(1, 10, 1..=1);
1242 assert_eq!(
1243 reply(answer(&source, packet_type::NODE_DISCOVERY_PULL_PING, &[])),
1244 b"node"
1245 );
1246 let time = NetworkTime::decode(&reply(answer(
1247 &source,
1248 packet_type::TIME_SYNC_NETWORK_TIME,
1249 &[],
1250 )))
1251 .unwrap();
1252 assert_eq!((time.receive, time.send), (1234, 1234));
1253 assert_eq!(
1254 reply(answer(&source, packet_type::NODE_DISCOVERY_PULL_PEERS, &[])),
1255 b"peers"
1256 );
1257 for (request_type, body) in [
1258 (packet_type::PULL_TRANSACTIONS, &[0; 12][..]),
1259 (packet_type::PULL_PARTIAL_TRANSACTION_INFOS, &[0; 16][..]),
1260 (packet_type::PULL_FINALIZATION_MESSAGES, &[0; 16][..]),
1261 ] {
1262 assert_eq!(
1263 answer(&source, request_type, body),
1264 Answer::Reply(request_type, Vec::new())
1265 );
1266 }
1267 assert!(matches!(
1269 answer(&source, packet_type::PULL_FINALIZATION_MESSAGES, &[0; 12]),
1270 Answer::Close(_)
1271 ));
1272 assert!(matches!(
1274 answer(
1275 &source,
1276 packet_type::PULL_PARTIAL_TRANSACTION_INFOS,
1277 &[0; 12]
1278 ),
1279 Answer::Close(_)
1280 ));
1281 }
1282
1283 fn identity(seed: u8) -> heika_tls::Identity {
1285 use heika_cert::certificate::{Certificate, Template, Version};
1286 use heika_core::key::{PrivateKey, PublicKey};
1287 let now = SystemTime::now();
1288 let template = |subject| Template {
1289 subject,
1290 not_before: now - std::time::Duration::from_secs(60),
1291 not_after: now + std::time::Duration::from_secs(60 * 60),
1292 serial_number: &[1],
1293 version: Version::V1,
1294 };
1295 let ca_key = PrivateKey::from_bytes(&[seed; 32]);
1296 let node_key = PrivateKey::from_bytes(&[seed + 1; 32]);
1297 let ca = Certificate::self_signed(&ca_key, &template("CN=CA")).unwrap();
1298 let node = Certificate::issue(
1299 &ca,
1300 &ca_key,
1301 &PublicKey::from_private_key(&node_key),
1302 &template("CN=node"),
1303 )
1304 .unwrap();
1305 heika_tls::Identity::new(&[node, ca], &node_key).unwrap()
1306 }
1307
1308 #[test]
1309 fn serves_over_tls_until_stopped() {
1310 let source = memory(1, 30, 1..=2);
1311 let parameters = &NetworkParameters::TESTNET;
1312 let env = FixedEnv(parameters.epoch());
1313 let responder = Responder {
1314 source: &source,
1315 env: &env,
1316 parameters,
1317 node: Vec::new(),
1318 pushes: None,
1319 mempool: None,
1320 partials: None,
1321 votes: None,
1322 capabilities: &[heika_packet::extension::BLOCKS_ALL],
1323 source_code: None,
1324 };
1325 let listener = TcpListener::bind("127.0.0.1:0").unwrap();
1326 let address = listener.local_addr().unwrap().to_string();
1327 let config = Arc::new(heika_tls::server_config(&identity(1)));
1328 let stop = std::sync::atomic::AtomicBool::new(false);
1329 let stopping = || stop.load(std::sync::atomic::Ordering::SeqCst);
1330 let gate = Gate::default();
1331 std::thread::scope(|scope| {
1332 let server = scope.spawn(|| serve(listener, config, &responder, &gate, &stopping));
1333 let mut client = heika_peer_protocol::ClientConnection::connect(
1334 &address,
1335 &identity(3),
1336 std::time::Duration::from_secs(5),
1337 )
1338 .unwrap();
1339 assert_eq!(client.chain_statistics().unwrap().height, 30);
1340 assert!(client.is_heika());
1342 assert_eq!(
1343 client.peer_capabilities(),
1344 Some(&[heika_packet::extension::BLOCKS_ALL.to_owned()][..])
1345 );
1346 assert_eq!(
1347 client.pull_blocks(29, 10, 1 << 20).unwrap(),
1348 [block(29), block(30)]
1349 );
1350 assert_eq!(client.finalization_statistics().unwrap().height, 20);
1351 let time = client.network_time().unwrap();
1352 assert_eq!((time.receive, time.send), (0, 0));
1353 stop.store(true, std::sync::atomic::Ordering::SeqCst);
1355 server.join().unwrap().unwrap();
1356 assert!(client.chain_statistics().is_err());
1357 });
1358 }
1359
1360 #[test]
1361 fn catching_up_prefers_peers_with_all_blocks() {
1362 let source = memory(1, 30, 1..=2);
1363 let parameters = &NetworkParameters::TESTNET;
1364 let env = FixedEnv(parameters.epoch());
1365 let responder = |capabilities| Responder {
1366 source: &source,
1367 env: &env,
1368 parameters,
1369 node: Vec::new(),
1370 pushes: None,
1371 mempool: None,
1372 partials: None,
1373 votes: None,
1374 capabilities,
1375 source_code: None,
1376 };
1377 let (light, full) = (
1378 responder(&[]),
1379 responder(&[heika_packet::extension::BLOCKS_ALL]),
1380 );
1381 let stop = std::sync::atomic::AtomicBool::new(false);
1382 let stopping = || stop.load(std::sync::atomic::Ordering::SeqCst);
1383 let (light_gate, full_gate) = (Gate::default(), Gate::default());
1384 std::thread::scope(|scope| {
1385 let mut addresses = Vec::new();
1386 for (responder, gate) in [(&light, &light_gate), (&full, &full_gate)] {
1387 let listener = TcpListener::bind("127.0.0.1:0").unwrap();
1388 addresses.push(listener.local_addr().unwrap().to_string());
1389 let config = Arc::new(heika_tls::server_config(&identity(1)));
1390 let stopping = &stopping;
1391 scope.spawn(move || serve(listener, config, responder, gate, stopping));
1392 }
1393 let timeout = std::time::Duration::from_secs(5);
1394 let chosen = crate::catch_up::connect_any(&addresses, &identity(3), 1, timeout);
1395 let chosen: Vec<_> = chosen.iter().map(|peer| peer.address.as_str()).collect();
1396 assert_eq!(chosen, [addresses[1].as_str()]);
1397 let chosen = crate::catch_up::connect_any(&addresses, &identity(3), 2, timeout);
1399 let chosen: Vec<_> = chosen.iter().map(|peer| peer.address.as_str()).collect();
1400 assert_eq!(chosen, [addresses[1].as_str(), addresses[0].as_str()]);
1401 stop.store(true, std::sync::atomic::Ordering::SeqCst);
1402 });
1403 }
1404
1405 #[test]
1406 fn hands_out_the_source_over_peer() {
1407 let source = memory(1, 30, 1..=2);
1408 let parameters = &NetworkParameters::TESTNET;
1409 let env = FixedEnv(parameters.epoch());
1410 let responder = |capabilities, source_code| Responder {
1411 source: &source,
1412 env: &env,
1413 parameters,
1414 node: Vec::new(),
1415 pushes: None,
1416 mempool: None,
1417 partials: None,
1418 votes: None,
1419 capabilities,
1420 source_code,
1421 };
1422 let with = responder(&[extension::SOURCE_ZIP], Some(&b"PK\x05\x06"[..]));
1423 let without = responder(&[], None);
1424 let stop = std::sync::atomic::AtomicBool::new(false);
1425 let stopping = || stop.load(std::sync::atomic::Ordering::SeqCst);
1426 let gates = [Gate::default(), Gate::default()];
1427 std::thread::scope(|scope| {
1428 let mut addresses = Vec::new();
1429 for (responder, gate) in [(&with, &gates[0]), (&without, &gates[1])] {
1430 let listener = TcpListener::bind("127.0.0.1:0").unwrap();
1431 addresses.push(listener.local_addr().unwrap().to_string());
1432 let config = Arc::new(heika_tls::server_config(&identity(1)));
1433 let stopping = &stopping;
1434 scope.spawn(move || serve(listener, config, responder, gate, stopping));
1435 }
1436 let connect = |address: &str| {
1437 heika_peer_protocol::ClientConnection::connect(
1438 address,
1439 &identity(3),
1440 std::time::Duration::from_secs(5),
1441 )
1442 .unwrap()
1443 };
1444 let mut client = connect(&addresses[0]);
1445 assert_eq!(client.source_zip().unwrap().unwrap(), b"PK\x05\x06");
1446 assert_eq!(client.chain_statistics().unwrap().height, 30);
1448 assert_eq!(connect(&addresses[1]).source_zip().unwrap(), None);
1449 stop.store(true, std::sync::atomic::Ordering::SeqCst);
1450 });
1451 }
1452
1453 #[test]
1454 fn a_bucket_lends_and_asks_to_wait_until_repaid() {
1455 let start = Instant::now();
1456 let mut bucket = Bucket::new(10.0, 5.0, start);
1457 assert_eq!(bucket.take(10.0, start), Duration::ZERO);
1458 assert_eq!(bucket.take(2.0, start), Duration::from_millis(400));
1460 assert_eq!(
1462 bucket.take(3.0, start + Duration::from_secs(1)),
1463 Duration::ZERO
1464 );
1465 assert_eq!(
1467 bucket.take(11.0, start + Duration::from_secs(100)),
1468 Duration::from_millis(200)
1469 );
1470 }
1471
1472 #[test]
1473 fn a_refused_take_does_not_borrow() {
1474 let start = Instant::now();
1475 let mut bucket = Bucket::new(2.0, 1.0, start);
1476 assert!(bucket.try_take(1.0, start));
1477 assert!(bucket.try_take(1.0, start));
1478 for _ in 0..1000 {
1480 assert!(!bucket.try_take(1.0, start));
1481 }
1482 assert!(bucket.try_take(1.0, start + Duration::from_secs(1)));
1483 }
1484
1485 fn with_server(per_address: usize, run: impl FnOnce(&str, &Gate)) {
1488 with_proxies(per_address, Vec::new(), run);
1489 }
1490
1491 fn with_proxies(per_address: usize, proxies: Vec<IpRange>, run: impl FnOnce(&str, &Gate)) {
1493 let source = memory(1, 30, 1..=2);
1494 let parameters = &NetworkParameters::TESTNET;
1495 let env = FixedEnv(parameters.epoch());
1496 let responder = Responder {
1497 source: &source,
1498 env: &env,
1499 parameters,
1500 node: Vec::new(),
1501 pushes: None,
1502 mempool: None,
1503 partials: None,
1504 votes: None,
1505 capabilities: &[],
1506 source_code: None,
1507 };
1508 let listener = TcpListener::bind("127.0.0.1:0").unwrap();
1509 let address = listener.local_addr().unwrap().to_string();
1510 let config = Arc::new(heika_tls::server_config(&identity(1)));
1511 let stop = std::sync::atomic::AtomicBool::new(false);
1512 let stopping = || stop.load(std::sync::atomic::Ordering::SeqCst);
1513 let gate = Gate {
1515 per_address,
1516 exempt_local: false,
1517 proxies,
1518 ..Gate::default()
1519 };
1520 std::thread::scope(|scope| {
1521 let server = scope.spawn(|| serve(listener, config, &responder, &gate, &stopping));
1522 run(&address, &gate);
1523 stop.store(true, std::sync::atomic::Ordering::SeqCst);
1524 server.join().unwrap().unwrap();
1525 });
1526 }
1527
1528 fn connect(address: &str, seed: u8) -> heika_peer_protocol::ClientConnection {
1529 heika_peer_protocol::ClientConnection::connect(
1530 address,
1531 &identity(seed),
1532 std::time::Duration::from_secs(5),
1533 )
1534 .unwrap()
1535 }
1536
1537 #[test]
1538 fn refuses_more_connections_from_the_same_key() {
1539 with_server(MAX_CONNECTIONS, |address, _| {
1540 let mut kept: Vec<_> = (0..MAX_PER_KEY).map(|_| connect(address, 3)).collect();
1541 for connection in &mut kept {
1542 assert!(connection.chain_statistics().is_ok());
1543 }
1544 assert!(connect(address, 3).chain_statistics().is_err());
1546 assert!(connect(address, 5).chain_statistics().is_ok());
1547 });
1548 }
1549
1550 #[test]
1551 fn refuses_more_connections_from_the_same_address() {
1552 with_server(2, |address, _| {
1553 let mut kept = [connect(address, 3), connect(address, 5)];
1554 for connection in &mut kept {
1555 assert!(connection.chain_statistics().is_ok());
1556 }
1557 assert!(
1559 heika_peer_protocol::ClientConnection::connect(
1560 address,
1561 &identity(7),
1562 std::time::Duration::from_secs(5)
1563 )
1564 .is_err()
1565 );
1566 });
1567 }
1568
1569 fn relay(server: &str, source: SocketAddr, v1: bool) -> String {
1573 let listener = TcpListener::bind("127.0.0.1:0").unwrap();
1574 let address = listener.local_addr().unwrap().to_string();
1575 let server = server.to_owned();
1576 std::thread::spawn(move || {
1577 for client in listener.incoming() {
1578 let Ok(mut client) = client else { return };
1579 let mut upstream = TcpStream::connect(&server).unwrap();
1580 let (SocketAddr::V4(from), SocketAddr::V4(to)) =
1581 (source, upstream.peer_addr().unwrap())
1582 else {
1583 panic!("IPv4 only");
1584 };
1585 let header = if v1 {
1586 format!(
1587 "PROXY TCP4 {} {} {} {}\r\n",
1588 from.ip(),
1589 to.ip(),
1590 from.port(),
1591 to.port()
1592 )
1593 .into_bytes()
1594 } else {
1595 [
1596 &heika_tls::proxy_protocol::SIGNATURE[..],
1597 &[0x21, 0x11, 0, 12],
1598 &from.ip().octets(),
1599 &to.ip().octets(),
1600 &from.port().to_be_bytes(),
1601 &to.port().to_be_bytes(),
1602 ]
1603 .concat()
1604 };
1605 std::io::Write::write_all(&mut upstream, &header).unwrap();
1606 let (mut client_back, mut upstream_back) =
1607 (client.try_clone().unwrap(), upstream.try_clone().unwrap());
1608 std::thread::spawn(move || std::io::copy(&mut upstream_back, &mut client_back));
1609 std::thread::spawn(move || std::io::copy(&mut client, &mut upstream));
1610 }
1611 });
1612 address
1613 }
1614
1615 #[test]
1616 fn counts_proxied_connections_by_their_original_source() {
1617 let source = |text: &str| text.parse::<SocketAddr>().unwrap();
1618 with_proxies(1, vec!["127.0.0.1".parse().unwrap()], |address, _| {
1619 let first = relay(address, source("192.0.2.1:40000"), false);
1620 let mut kept = connect(&first, 3);
1621 assert!(kept.chain_statistics().is_ok());
1622 assert!(
1624 heika_peer_protocol::ClientConnection::connect(
1625 &first,
1626 &identity(5),
1627 Duration::from_secs(5)
1628 )
1629 .is_err()
1630 );
1631 let second = relay(address, source("192.0.2.2:40000"), false);
1633 assert!(connect(&second, 5).chain_statistics().is_ok());
1634 let third = relay(address, source("192.0.2.3:40000"), true);
1635 let mut kept_v1 = connect(&third, 7);
1636 assert!(kept_v1.chain_statistics().is_ok());
1637 assert!(
1638 heika_peer_protocol::ClientConnection::connect(
1639 &third,
1640 &identity(9),
1641 Duration::from_secs(5)
1642 )
1643 .is_err()
1644 );
1645 assert!(
1647 heika_peer_protocol::ClientConnection::connect(
1648 address,
1649 &identity(11),
1650 Duration::from_secs(5)
1651 )
1652 .is_err()
1653 );
1654 });
1655 }
1656
1657 #[test]
1658 fn ignores_proxy_headers_unless_configured() {
1659 with_server(MAX_CONNECTIONS, |address, _| {
1660 let proxied = relay(address, "192.0.2.1:40000".parse().unwrap(), false);
1662 assert!(
1663 heika_peer_protocol::ClientConnection::connect(
1664 &proxied,
1665 &identity(3),
1666 Duration::from_secs(5)
1667 )
1668 .is_err()
1669 );
1670 assert!(connect(address, 3).chain_statistics().is_ok());
1671 });
1672 }
1673
1674 #[test]
1675 fn local_addresses_are_not_counted_per_address() {
1676 for local in [
1677 "127.0.0.1",
1678 "10.1.2.3",
1679 "192.168.0.2",
1680 "::1",
1681 "fd00::1",
1682 "::ffff:10.0.0.1",
1683 ] {
1684 assert!(is_local(local.parse().unwrap()), "{local}");
1685 }
1686 for public in ["8.8.8.8", "2001:db8::1", "::ffff:8.8.8.8"] {
1687 assert!(!is_local(public.parse().unwrap()), "{public}");
1688 }
1689 }
1690
1691 #[test]
1692 fn cuts_a_key_from_outside_without_banning_it() {
1693 with_server(MAX_CONNECTIONS, |address, gate| {
1694 let mut kept = connect(address, 3);
1695 assert!(kept.chain_statistics().is_ok());
1696 gate.cut(*identity(3).key());
1697 assert!(kept.chain_statistics().is_err());
1698 assert!(connect(address, 3).chain_statistics().is_ok());
1700 });
1701 }
1702
1703 #[test]
1704 fn bans_a_key_from_outside_and_closes_its_connections() {
1705 with_server(MAX_CONNECTIONS, |address, gate| {
1706 let mut kept = connect(address, 3);
1707 assert!(kept.chain_statistics().is_ok());
1708 gate.ban(*identity(3).key());
1709 assert!(kept.chain_statistics().is_err());
1710 assert!(connect(address, 3).chain_statistics().is_err());
1711 assert!(connect(address, 5).chain_statistics().is_ok());
1712 });
1713 }
1714
1715 #[test]
1716 fn bans_a_key_that_breaks_the_rules() {
1717 with_server(MAX_CONNECTIONS, |address, _| {
1718 let mut connection = heika_tls::Connection::open(
1719 address,
1720 &identity(3),
1721 std::time::Duration::from_secs(5),
1722 )
1723 .unwrap();
1724 connection.send_packet(0x999, &[]).unwrap();
1725 assert!(connection.receive_packet(1024).is_err());
1726 std::thread::sleep(std::time::Duration::from_millis(300));
1728 assert!(connect(address, 3).chain_statistics().is_err());
1729 assert!(connect(address, 5).chain_statistics().is_ok());
1730 });
1731 }
1732
1733 #[test]
1734 fn hands_pushed_cosignatures_to_the_driver() {
1735 let source = memory(1, 10, 1..=1);
1736 let (pushes, events) = std::sync::mpsc::channel();
1737 let detached = heika_transaction::DetachedCosignature::sign(
1738 &PrivateKey::from_bytes(&[3; 32]),
1739 &heika_core::hash::Hash256([5; 32]),
1740 );
1741 let push = |body: &[u8]| {
1742 answer_pushing(
1743 &source,
1744 None,
1745 Some(pushes.clone()),
1746 packet_type::PUSH_DETACHED_COSIGNATURES,
1747 body,
1748 )
1749 };
1750 assert_eq!(push(&detached.to_bytes()), Answer::Nothing);
1751 match events.try_recv() {
1752 Ok(NodeEvent::Partial {
1753 incoming: Incoming::Cosignatures(cosignatures),
1754 from: None,
1755 }) => assert_eq!(cosignatures, [detached]),
1756 _ => panic!("連署を渡していません"),
1757 }
1758 assert_eq!(push(&[0; 10]), Answer::Nothing);
1760 assert!(events.try_recv().is_err());
1761 }
1762
1763 #[test]
1764 fn takes_pushed_transactions_and_answers_pulls() {
1765 let source = memory(1, 10, 1..=1);
1766 let parameters = &NetworkParameters::TESTNET;
1767 let mempool =
1768 SharedMempool::new(Mempool::new(parameters, heika_mempool::Config::default()));
1769 let (first, second) = (signed_transfer(1), signed_transfer(2));
1770 let pushed = [first.clone(), second.clone()].concat();
1771 let (pushes, events) = std::sync::mpsc::channel();
1772 let push = |body: &[u8]| {
1773 answer_pushing(
1774 &source,
1775 Some(&mempool),
1776 Some(pushes.clone()),
1777 packet_type::PUSH_TRANSACTIONS,
1778 body,
1779 )
1780 };
1781 assert_eq!(push(&pushed), Answer::Nothing);
1782 assert_eq!(mempool.lock().len(), 2);
1783 let relayed = |events: &std::sync::mpsc::Receiver<NodeEvent>| -> Vec<Vec<u8>> {
1785 events
1786 .try_iter()
1787 .map(|event| match event {
1788 NodeEvent::Relay {
1789 transactions,
1790 except: None,
1791 } => transactions.to_vec(),
1792 _ => panic!("流す頼み以外が来ました"),
1793 })
1794 .collect()
1795 };
1796 assert_eq!(relayed(&events), std::slice::from_ref(&pushed));
1797 let third = signed_transfer(3);
1798 assert_eq!(
1799 push(&[second.clone(), third.clone()].concat()),
1800 Answer::Nothing
1801 );
1802 assert_eq!(relayed(&events), std::slice::from_ref(&third));
1803 assert_eq!(push(&first), Answer::Nothing);
1804 assert!(relayed(&events).is_empty());
1805 let pull = |known: &[u32]| {
1806 reply(answer_with(
1807 &source,
1808 Some(&mempool),
1809 packet_type::PULL_TRANSACTIONS,
1810 &pull_transactions_request(0, 0, known),
1811 ))
1812 };
1813 assert_eq!(pull(&[]), [pushed.as_slice(), &third].concat());
1814 let known = short_hash(
1815 &Transaction::from_bytes(&first)
1816 .unwrap()
1817 .hash(¶meters.generation_hash_seed),
1818 );
1819 assert_eq!(pull(&[known]), [second.as_slice(), &third].concat());
1820 assert!(matches!(
1822 answer_with(
1823 &source,
1824 Some(&mempool),
1825 packet_type::PULL_TRANSACTIONS,
1826 &[0; 5]
1827 ),
1828 Answer::Close(_)
1829 ));
1830 assert_eq!(
1832 reply(answer(
1833 &source,
1834 packet_type::PULL_TRANSACTIONS,
1835 &pull_transactions_request(0, 0, &[])
1836 )),
1837 Vec::<u8>::new()
1838 );
1839 }
1840
1841 #[test]
1842 fn ignores_pushes_and_closes_on_unknown_types() {
1843 let source = memory(1, 10, 1..=1);
1844 assert_eq!(
1845 answer(&source, packet_type::PUSH_TRANSACTIONS, &[0; 8]),
1846 Answer::Nothing
1847 );
1848 assert!(matches!(
1850 answer(&source, packet_type::PUSH_BLOCK, &block(11)),
1851 Answer::Close(reason) if reason.contains("高さ 11")
1852 ));
1853 assert!(matches!(answer(&source, 0x999, &[]), Answer::Close(_)));
1854 }
1855}