Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 14 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,12 +45,12 @@ handshake on, it pings the peer every 2 min.
It drops a peer that does not answer a `ping` within 20 min, or a `getheaders`
within 2 min. It also drops a peer that sends `wtxidrelay` or `sendaddrv2` after
the handshake. When a connection ends, elo logs the reason, waits 5 s and dials
the peer again. Each connection logs the `version` and the `tip` again. The
again. Each connection logs the `version` and the `tip` again. The
chain stays in memory, so the next connection syncs from its tip. A chain below
the minimum work starts again from genesis.

```sh
elo <mainnet|testnet4|signet|regtest> <ip|name>[:port] # IPv6 as [::1]:8333
elo <mainnet|testnet4|signet|regtest> [<ip|name>[:port]] # IPv6 as [::1]:8333
```

The peer is an IP address or a name. Before each dial, elo looks up the name
Expand All @@ -60,6 +60,16 @@ connect. So a name with many addresses, such as a DNS seed, gives a new peer
on each dial. A failed lookup is an `end`, and elo looks up the name again
after 5 s.

With no peer, each dial looks up one DNS seed of the network, at random, as
`x9.<seed>`: a seed answers that name with nodes that serve each block and its
witness data. Some seeds have no such names, so when that lookup fails or gives
no address to dial, elo looks up the seed itself. elo takes at most 32 of its
addresses that the internet routes to, so not this host, a private network, a
link or a test range. A seed chose those peers, and elo trusts them as much as
a peer that you name. A lookup that times out ends the dial at once, because
the resolver does not answer. Regtest has no seeds, so `elo regtest` needs a
peer.

SIGTERM and SIGINT (Ctrl-C) stop elo at any step, also in the wait before a
dial. It logs the signal and exits with 0. elo exits with 1 only on a fault of
this host: its async runtime or its signal handlers do not start, a write to
Expand All @@ -82,14 +92,14 @@ level=info event=stop signal=SIGTERM
| --- | --- | --- |
| `version` | `info` | `peer` `version` `services` `user_agent` `start_height` `relay` |
| `tip` | `info` | `peer` `height` `hash` `work` |
| `end` | `warn` | `destination` `reason` `wait_ms`: elo dials `destination` again after `wait_ms`. `destination` is the peer of the command line, also a name. `peer` is always the address of a connection |
| `end` | `warn` | `destination` `reason` `wait_ms`: elo dials again after `wait_ms`. `destination` is what the dial looked up or dialed: the peer of the command line, also a name, or the seed, such as `seed.bitcoin.sipa.be.:8333`. `peer` is always the address of a connection |
| `exit` | `error` | `reason`: a fault of this host, and elo exits with 1 |
| `stop` | `info` | `signal`: elo exits with 0 |
| `panic` | `error` | `reason`: a bug, and elo exits with 101 |

The names of the events and of the fields are an interface, so a rename breaks the dashboards and
alerts that match on them. `src/logging.rs` holds the one list of them. A value with a space, a `=`,
a `"` or a control character is in quotes, with escapes. A value is at most 256 bytes, so a line is
a `"` or a control character is in quotes, with escapes. A value is at most 260 bytes, so a line is
at most 16 KiB, whatever the peer sends. When a write to stdout fails, elo writes the `exit` line to
stderr only, because the write that failed can leave part of its line on stdout.

Expand Down
31 changes: 31 additions & 0 deletions src/chainparams.rs
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,25 @@ const PORT_TESTNET4: std::num::NonZeroU16 = std::num::NonZeroU16::new(48333).exp
const PORT_SIGNET: std::num::NonZeroU16 = std::num::NonZeroU16::new(38333).expect("not 0");
const PORT_REGTEST: std::num::NonZeroU16 = std::num::NonZeroU16::new(18444).expect("not 0");

const SEEDS_MAINNET: [&str; 8] = [
"seed.bitcoin.sipa.be.",
"dnsseed.bluematt.me.",
"seed.bitcoin.jonasschnelli.ch.",
"seed.btc.petertodd.net.",
"seed.bitcoin.sprovoost.nl.",
"dnsseed.emzy.de.",
"seed.bitcoin.wiz.biz.",
"seed.mainnet.achownodes.xyz.",
];
const SEEDS_TESTNET4: [&str; 2] = [
"seed.testnet4.bitcoin.sprovoost.nl.",
"seed.testnet4.wiz.biz.",
];
const SEEDS_SIGNET: [&str; 2] = [
"seed.signet.bitcoin.sprovoost.nl.",
"seed.signet.achownodes.xyz.",
];

impl Network {
/// The bytes that start every message.
pub(crate) const fn magic(self) -> [u8; MAGIC_SIZE] {
Expand All @@ -90,6 +109,18 @@ impl Network {
}
}

/// The names of the DNS seeds of the network. A seed answers the lookup of its name with the
/// addresses of nodes of the network that it chose. Regtest has no real network, so it has no
/// seeds.
pub(crate) const fn seeds(self) -> &'static [&'static str] {
match self {
Network::Mainnet => &SEEDS_MAINNET,
Network::Testnet4 => &SEEDS_TESTNET4,
Network::Signet => &SEEDS_SIGNET,
Network::Regtest => &[],
}
}

/// The highest target that a header of the network may have, big-endian.
pub(crate) const fn pow_limit(self) -> [u8; 32] {
match self {
Expand Down
7 changes: 4 additions & 3 deletions src/logging.rs
Original file line number Diff line number Diff line change
Expand Up @@ -55,9 +55,10 @@ pub enum Event<'a> {
peer: std::net::SocketAddr,
tip: &'a crate::chain::Tip,
},
/// The connection to `destination` ended for `reason`, and elo dials it again after `wait`.
/// `destination` is the peer of the command line: an IP address, or a name that elo looks up
/// again. It has its own key, so `peer` is always the address of a connection.
/// The connection to `destination` ended for `reason`, and elo dials again after `wait`.
/// `destination` is what the dial looked up or dialed: the IP address or the name of the
/// command line, or a seed of the network. It has its own key, so `peer` is always the address
/// of a connection.
End {
destination: &'a crate::net::Destination,
reason: &'a dyn std::fmt::Display,
Expand Down
107 changes: 71 additions & 36 deletions src/main.rs
Original file line number Diff line number Diff line change
@@ -1,20 +1,22 @@
//! `elo <network> <host>[:port]`: dials one peer, does the handshake, and logs the peer's
//! `version`. The host is an IP address or a name. Before each dial, elo looks up the name, and
//! dials its addresses in a random order until one takes the connect. Then it syncs the header
//! chain from the peer and logs the tip. It asks the peer to announce each new header, takes it on
//! the tip, and logs the tip when it moves. It pings the peer and answers its `ping` messages
//! until the connection ends. Then it waits and dials the peer again. The chain stays in memory,
//! so the next connection syncs from its tip. SIGTERM and SIGINT stop it at any of these steps.
//! Each step writes a line of `elo::logging` to stdout.
//! `elo <network> [<host>[:port]]`: dials one peer, does the handshake, and logs the peer's
//! `version`. The host is an IP address or a name. With no host, each dial takes a seed of the
//! network, at random. Before each dial, elo looks up the name or the seed, and dials its addresses
//! in a random order until one takes the connect. Then it syncs the header chain from the peer and
//! logs the tip. It asks the peer to announce each new header, takes it on the tip, and logs the
//! tip when it moves. It pings the peer and answers its `ping` messages until the connection ends.
//! Then it waits and dials again. The chain stays in memory, so the next connection syncs from its
//! tip. SIGTERM and SIGINT stop it at any of these steps. Each step writes a line of
//! `elo::logging` to stdout.

const USAGE: &str = "usage: elo <mainnet|testnet4|signet|regtest> <ip|name>[:port]";
const USAGE: &str = "usage: elo <mainnet|testnet4|signet|regtest> [<ip|name>[:port]]
regtest has no seeds, so it needs a peer";

/// The exit code for bad usage. A stop by a signal exits with 0, and a panic with 101. Every
/// other exit is 1, because only a fault of this host ends elo.
const EXIT_USAGE: u8 = 2;

/// How long elo waits after a connection ends before it dials the peer again. So a peer that is
/// down, or that ends each connection at once, gets at most one try in each wait.
/// How long elo waits after a connection ends before it dials again. So a peer that is down, or
/// that ends each connection at once, gets at most one try in each wait.
const RECONNECT_WAIT: std::time::Duration = std::time::Duration::from_secs(5);

fn main() -> std::process::ExitCode {
Expand All @@ -28,7 +30,7 @@ fn main() -> std::process::ExitCode {
}));

let args: Vec<std::ffi::OsString> = std::env::args_os().skip(1).collect();
let Some((network, destination)) = parse(&args) else {
let Some((network, source)) = parse(&args) else {
eprintln!("{USAGE}");
return std::process::ExitCode::from(EXIT_USAGE);
};
Expand All @@ -42,17 +44,18 @@ fn main() -> std::process::ExitCode {
Ok(runtime) => runtime,
Err(error) => return exit(&format_args!("runtime: {error}")),
};
let code = runtime.block_on(run(network, destination));
let code = runtime.block_on(run(network, source));
// A lookup runs on a blocking thread of the runtime, and a stop or a lookup timeout does not
// end it. The drop of the runtime would wait for that thread, so the runtime does not wait.
runtime.shutdown_background();
code
}

/// Dials `destination` again after each end that retries, until a signal or an end that exits.
/// Dials a destination of `source` again after each end that retries, until a signal or an end
/// that exits.
async fn run(
network: elo::chainparams::Network,
destination: elo::net::Destination,
source: elo::net::Source,
) -> std::process::ExitCode {
// Before the first dial, so a signal from here on stops elo. As PID 1 in a container, a
// process with no handler never sees a SIGTERM: the kernel drops it, and the stop ends in
Expand All @@ -67,6 +70,7 @@ async fn run(
// The loop has no count bound, because elo keeps its one peer for as long as it runs. Only
// a signal or an end that a new connection cannot fix gets out.
loop {
let destination = source.destination();
// The drop of the connection closes its socket. elo keeps nothing on disk, so the stop
// has nothing else to finish.
let end = match signals.unless(dial(&destination, &mut chain)).await {
Expand All @@ -79,8 +83,8 @@ async fn run(
if !end.retries() {
return exit(&end);
}
// The destination of the command line, and not the address of the connection: the next
// dial looks up a name again.
// The destination of the dial, and not the address of the connection: the next dial looks
// up a name again, and a seed shows which seed gave the peer.
let logged = log(&elo::logging::Event::End {
destination: &destination,
reason: &end,
Expand Down Expand Up @@ -213,7 +217,7 @@ impl End {
End::Handshake(
elo::net::HandshakeError::Lookup(
elo::net::LookupError::Failed(_)
| elo::net::LookupError::Timeout
| elo::net::LookupError::Timeout { .. }
| elo::net::LookupError::Empty,
)
| elo::net::HandshakeError::Connect {
Expand Down Expand Up @@ -281,15 +285,13 @@ async fn dial(
}
}

/// The args after the program name. `None` is bad usage.
///
/// An IPv6 address needs brackets even without a port, because `::1:8333` is an IPv6 address
/// and not `::1` with a port.
fn parse(
args: &[std::ffi::OsString],
) -> Option<(elo::chainparams::Network, elo::net::Destination)> {
let [network, peer] = args else {
return None;
/// The args after the program name. `None` is bad usage. With no peer, the source is the seeds
/// of the network, so a network with no seeds needs a peer.
fn parse(args: &[std::ffi::OsString]) -> Option<(elo::chainparams::Network, elo::net::Source)> {
let (network, peer) = match args {
[network] => (network, None),
[network, peer] => (network, Some(peer)),
_ => return None,
};
let network = match network.to_str()? {
"mainnet" => elo::chainparams::Network::Mainnet,
Expand All @@ -298,8 +300,18 @@ fn parse(
"regtest" => elo::chainparams::Network::Regtest,
_ => return None,
};
let source = match peer {
Some(peer) => elo::net::Source::Destination(destination(peer.to_str()?, network)?),
None => elo::net::Source::Seeds(elo::net::Seeds::new(network)?),
};
Some((network, source))
}

let peer = peer.to_str()?;
/// `peer` as the destination of each dial, or `None` if it is no IP address and no name.
///
/// An IPv6 address needs brackets even without a port, because `::1:8333` is an IPv6 address
/// and not `::1` with a port.
fn destination(peer: &str, network: elo::chainparams::Network) -> Option<elo::net::Destination> {
let destination = if let Some(address) = address(peer, network.default_port()) {
// Port 0, `0.0.0.0`, `[::]` and `[::ffff:0.0.0.0]` name no peer.
elo::net::Destination::Address(elo::net::PeerAddress::new(address)?)
Expand All @@ -314,7 +326,7 @@ fn parse(
port,
}
};
Some((network, destination))
Some(destination)
}

/// `peer` as an IP address with an optional port, or `None` if it is no IP address.
Expand All @@ -331,7 +343,7 @@ fn address(peer: &str, default_port: std::num::NonZeroU16) -> Option<std::net::S

#[cfg(test)]
mod tests {
fn parse(args: &[&str]) -> Option<(elo::chainparams::Network, elo::net::Destination)> {
fn parse(args: &[&str]) -> Option<(elo::chainparams::Network, elo::net::Source)> {
let args: Vec<std::ffi::OsString> = args.iter().map(std::ffi::OsString::from).collect();
super::parse(&args)
}
Expand All @@ -357,7 +369,9 @@ mod tests {
),
(
super::End::Handshake(elo::net::HandshakeError::Lookup(
elo::net::LookupError::Timeout,
elo::net::LookupError::Timeout {
host: String::from("localhost"),
},
)),
true,
),
Expand Down Expand Up @@ -390,7 +404,7 @@ mod tests {
elo::net::Destination::Address(elo::net::PeerAddress::new(address).unwrap());
assert_eq!(
parse(&[name, "127.0.0.1"]),
Some((network, destination)),
Some((network, elo::net::Source::Destination(destination))),
"{name}"
);
let destination = elo::net::Destination::Name {
Expand All @@ -399,7 +413,7 @@ mod tests {
};
assert_eq!(
parse(&[name, "localhost"]),
Some((network, destination)),
Some((network, elo::net::Source::Destination(destination))),
"{name}"
);
}
Expand Down Expand Up @@ -472,16 +486,37 @@ mod tests {
("0x7f.example", name("0x7f.example", 18444)),
("", None),
] {
let parsed = parse(&["regtest", peer]).map(|(_, destination)| destination);
assert_eq!(parsed, expected, "{peer}");
let parsed = parse(&["regtest", peer]).map(|(_, source)| source);
assert_eq!(
parsed,
expected.map(elo::net::Source::Destination),
"{peer}"
);
}
}

#[test]
fn no_peer_is_the_seeds_of_the_network() {
for (name, network) in [
("mainnet", elo::chainparams::Network::Mainnet),
("testnet4", elo::chainparams::Network::Testnet4),
("signet", elo::chainparams::Network::Signet),
] {
let seeds = elo::net::Seeds::new(network).unwrap();
assert_eq!(
parse(&[name]),
Some((network, elo::net::Source::Seeds(seeds))),
"{name}"
);
}
}

#[test]
fn usage_is_a_network_name_and_a_peer() {
fn usage_is_a_network_name_and_a_peer_and_regtest_needs_the_peer() {
for args in [
&[][..],
&["regtest"],
&["testnet3"],
&["testnet3", "127.0.0.1"],
&["regtest", "127.0.0.1", "127.0.0.1"],
] {
Expand Down
Loading