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
2 changes: 1 addition & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "logos-devnet"
version = "0.9.3"
version = "0.9.4"
edition = "2024"
rust-version = "1.89"
description = "A local LEZ chain for Logos development: one command to start it, fund accounts and deploy programs"
Expand Down
6 changes: 3 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ cargo install --locked logos-devnet
Or take a binary from the [latest release](https://github.com/drptbl/logos-devnet/releases/latest), built for macOS (`aarch64-apple-darwin`, `x86_64-apple-darwin`) and Linux (`x86_64-unknown-linux-musl`, `aarch64-unknown-linux-musl`, static, so any distribution), and check it against its `.sha256`:

```bash
v=v0.9.3 t=aarch64-apple-darwin
v=v0.9.4 t=aarch64-apple-darwin
curl -fsSL --remote-name-all https://github.com/drptbl/logos-devnet/releases/download/$v/logos-devnet-$v-$t.tar.gz{,.sha256}
shasum -a 256 -c logos-devnet-$v-$t.tar.gz.sha256 \
&& tar -xzf logos-devnet-$v-$t.tar.gz \
Expand Down Expand Up @@ -101,7 +101,7 @@ modules = ["chat_module"] # or "chat_module@0.3.0" for that version

A program can come from a release instead of a path: `up` downloads its `url` once, with `curl`, into `~/.logos-devnet/downloads`, which every home shares, and deploys it only if its SHA-256 is the `sha256` given (as `shasum -a 256` prints it).

`up` deploys missing programs, makes and funds missing accounts and sessions, and changes nothing the second time (0.6 s). A `mutable` program whose binary changed is updated in place, with the same id. An immutable one keeps its old build, and `up` and `deploy` fail saying so, so tests don't run against it: `reset` deploys the new build. A module added to a session's `modules` is installed into it. Modules come from the catalog at its latest version, `lez_core` at `0.5.1`, unless the file names one: `chat_module@0.3.0`. A session keeps the versions it was made with, so `up` refuses another version for an existing one: `session rm` it, and `up` makes it again. A pin on what it installed unpinned is checked against the version its daemon reports, and recorded when it matches. `up` checks the whole file before it touches the devnet. A stopped sequencer replays its chain's history before it serves, which takes a while on a long chain (166k blocks took about 15 minutes): `up` waits as long as its log grows, up to an hour, and says so.
`up` deploys missing programs, makes and funds missing accounts and sessions, and changes nothing the second time (0.6 s). A `mutable` program whose binary changed is updated in place, with the same id. An immutable one keeps its old build, and `up` and `deploy` fail saying so, so tests don't run against it: `reset` deploys the new build. A module added to a session's `modules` is installed into it. Modules come from the catalog at its latest version, `lez_core` at `0.5.1`, unless the file names one: `chat_module@0.3.0`. A session keeps the versions it was made with, so `up` refuses another version for an existing one: `session rm` it, and `up` makes it again. A pin on what it installed unpinned is checked against the version its daemon reports, and recorded when it matches. `up` checks the whole file before it touches the devnet. A stopped sequencer replays its chain's history before it serves, which takes a while on a long chain (186k blocks took about 34 minutes): `up` waits as long as its log shows something new, up to 4 hours, and says so. A sequencer that only repeats lines it logged lately for 3 minutes, e.g. retrying an error, counts as stuck.

Projects share one devnet, `~/.logos-devnet` on port 3040, unless the file sets `home`, e.g. `home = ".logos-devnet"`, for a devnet of the project's own. Downloads stay shared. Give it `[devnet] port = 0` too: it takes a free port on the first `up` and keeps it, so it runs next to other devnets, and `logos-devnet env` shows it. With a fixed `port` in the file, `--port` applies for that run, and the next `up` goes back to the file's port. With `port = 0`, `--port` is remembered. On a shared devnet, a `[devnet]` section that disagrees with the running chain is refused rather than restarting the chain under the other projects: `down` and `up` apply it, or `reset` for `lez` and `dev_mode`, which only a new chain takes. A `reset` there funds every project's account groups again, and each project's next `up` deploys its programs on the new chain.

Expand Down Expand Up @@ -279,7 +279,7 @@ With `--json`, a command prints one JSON document and nothing else on stdout. No
The repo is a GitHub Action. On a Linux runner it installs `logos-devnet`, starts the devnet from your project file and exports the env into the job:

```yaml
- uses: drptbl/logos-devnet@v0.9.3
- uses: drptbl/logos-devnet@v0.9.4
with:
args: --max-txs-per-block 100 # optional, more options for up
- run: cargo test # LOGOS_DEVNET_SEQUENCER, LOGOS_PROGRAM_*, LOGOS_DEVNET_ACCOUNTS_*, RISC0_DEV_MODE are set
Expand Down
2 changes: 1 addition & 1 deletion examples/github-actions/devnet.yml
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ jobs:
# Installs logos-devnet, starts the devnet from logos-devnet.toml, and exports its env
# (LOGOS_DEVNET_SEQUENCER, LOGOS_PROGRAM_*, LOGOS_DEVNET_ACCOUNTS_*, RISC0_DEV_MODE).
- id: devnet
uses: drptbl/logos-devnet@v0.9.3
uses: drptbl/logos-devnet@v0.9.4
- run: cargo test
- name: The devnet's logs
if: failure()
Expand Down
2 changes: 1 addition & 1 deletion skills/logos-devnet/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ Each refusal changes nothing. `up` prefixes a program's refusal with `program <n
| `the session has <module> <version>, not <version>` or `its daemon has no <module> package` | A session keeps the versions it was made with: `session rm <name>`, then `up` makes it again. |
| `not a RISC Zero program binary` | Deploy the guest's `.bin` from `cargo risczero build`, not its ELF. |
| `no Docker daemon answers` | Start Docker (OrbStack, Docker Desktop or Colima). |
| `no block, and nothing in the sequencer's log` / `the sequencer stopped while starting` | Read `logos-devnet logs`. A long chain loading is no error: `up` waits as long as the log grows. |
| `no block, and nothing new in the sequencer's log` / `the sequencer stopped while starting` | Read `logos-devnet logs`. A long chain loading is no error: `up` waits as long as the log shows something new. |

## Debugging

Expand Down
82 changes: 57 additions & 25 deletions src/devnet.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ use crate::report::{
Sessions, Status, WalletConfig,
};
use crate::rpc::Rpc;
use crate::runtime::{BATCH_CHUNK, Docker, Native, Runtime, WalletArg};
use crate::runtime::{BATCH_CHUNK, Docker, Native, Runtime, WalletArg, log_line_text};
use crate::session::{self, Session, SessionInfo};

/// The faucet's genesis balance in lepta: enough that a devnet never runs dry.
Expand All @@ -32,14 +32,17 @@ const FAUCET_BALANCE: u64 = 1_000_000_000_000_000_000;
const FAUCET_LABEL: &str = "faucet";
/// What `fund`, sessions and account groups send when no amount is given.
pub const DEFAULT_FUND: u64 = 10_000_000_000;
/// How `up` waits for a starting sequencer's first block. A long chain loads for minutes first
/// (166k blocks took 15), logging as it goes, so `up` waits as long as the log grows.
/// How `up` waits for a starting sequencer's first block. A long chain replays first, logging
/// a different line for each block (186k blocks took 34 min), so `up` waits as long as the log
/// shows something new. A sequencer stuck repeating one line counts as quiet.
const READY_WAIT: ReadyWait = ReadyWait {
quiet: Duration::from_secs(180),
limit: Duration::from_secs(3600),
limit: Duration::from_secs(4 * 3600),
poll: Duration::from_millis(500),
log_every: Duration::from_secs(10),
};
/// How many of the sequencer's recent distinct last lines `up` remembers while it waits.
const RECENT_LINES: usize = 32;
/// When `up` says it's still waiting, and then how often.
const LOADING_NOTICE: Duration = Duration::from_secs(30);
const LOADING_NOTICE_EVERY: Duration = Duration::from_secs(120);
Expand Down Expand Up @@ -871,7 +874,7 @@ impl Devnet {
&Startup {
serves: &|| rpc.last_block_id().is_ok_and(|head| head >= 1),
running: &|| self.runtime.running(),
log_mark: &|| self.runtime.log_mark(),
log_mark: &|| self.runtime.last_log_line().map(|l| log_line_text(&l)),
},
&READY_WAIT,
)
Expand Down Expand Up @@ -1837,9 +1840,9 @@ fn labelled(list: &str, label: &str) -> Option<PublicId> {

/// How long `wait_for_blocks` waits.
struct ReadyWait {
/// The longest the sequencer's log may go without a new line.
/// The longest the sequencer's log may go without a line it didn't just write.
quiet: Duration,
/// The longest it waits in all, however busy the log.
/// The longest it waits in all, however busy the log: a last resort, under CI's 6 h.
limit: Duration,
/// How often it asks for a block.
poll: Duration,
Expand All @@ -1853,16 +1856,18 @@ struct Startup<'a> {
serves: &'a dyn Fn() -> bool,
/// Whether it still runs.
running: &'a dyn Fn() -> bool,
/// Something that changes whenever it writes to its log, e.g. its last line.
/// Its last log line, without the time, or `None` when it can't be read.
log_mark: &'a dyn Fn() -> Option<String>,
}

/// Waits until the sequencer serves a block. It may take as long as it keeps writing to its
/// log, up to `wait.limit`: it fails after `wait.quiet` without a new line, or when the
/// Waits until the sequencer serves a block. It may take as long as its log shows something new,
/// up to `wait.limit`: it fails after `wait.quiet` with the same last line, or when the
/// sequencer stops. A log that can't be read counts as busy, since not knowing isn't quiet.
fn wait_for_blocks(startup: &Startup, wait: &ReadyWait) -> Result<()> {
let start = Instant::now();
let mut mark = (startup.log_mark)();
// Recent distinct last lines: one among them is no news, so a sequencer going round a
// short loop, e.g. an error and a retry, counts as quiet.
let mut recent: std::collections::VecDeque<String> = (startup.log_mark)().into_iter().collect();
let mut last_change = start;
let mut last_check = start;
let mut next_notice = LOADING_NOTICE;
Expand All @@ -1875,44 +1880,52 @@ fn wait_for_blocks(startup: &Startup, wait: &ReadyWait) -> Result<()> {
}
if last_check.elapsed() >= wait.log_every {
last_check = Instant::now();
let now = (startup.log_mark)();
if now.is_none() || now != mark {
mark = now;
last_change = last_check;
match (startup.log_mark)() {
// Not knowing isn't quiet.
None => last_change = last_check,
Some(line) if !recent.contains(&line) => {
if recent.len() == RECENT_LINES {
recent.pop_front();
}
recent.push_back(line);
last_change = last_check;
}
Some(_) => {}
}
}
if last_change.elapsed() > wait.quiet {
bail!(
"no block, and nothing in the sequencer's log for {} s. See `logos-devnet logs`",
"no block, and nothing new in the sequencer's log for {} s. See `logos-devnet logs`",
wait.quiet.as_secs()
);
}
let waited = start.elapsed();
if waited > wait.limit {
bail!(
"no block within {} min, though the sequencer keeps logging. See `logos-devnet \
logs`",
wait.limit.as_secs() / 60
"no block within {}, though the sequencer keeps logging. See `logos-devnet logs`",
duration_text(wait.limit)
);
}
if waited >= next_notice {
eprintln!(
"No block yet after {}: a long chain takes a while to load. Waiting as long as \
the sequencer keeps logging, up to {} min; `logos-devnet logs -f` shows it.",
the sequencer's log shows something new, up to {}; `logos-devnet logs -f` shows \
it.",
duration_text(waited),
wait.limit.as_secs() / 60
duration_text(wait.limit)
);
next_notice += LOADING_NOTICE_EVERY;
}
std::thread::sleep(wait.poll);
}
}

/// `30 s`, or `4 min` from two minutes on.
/// `30 s`, `4 min` from two minutes on, or `4 h` from two hours on.
fn duration_text(d: Duration) -> String {
match d.as_secs() {
s if s < 120 => format!("{s} s"),
s => format!("{} min", s / 60),
s if s < 7200 => format!("{} min", s / 60),
s => format!("{} h", s / 3600),
}
}

Expand Down Expand Up @@ -2124,6 +2137,8 @@ mod tests {
enum Log {
Busy,
Quiet,
/// Two lines in turn, as a sequencer retrying an error logs them.
Looping,
Unreadable,
}

Expand All @@ -2135,6 +2150,10 @@ mod tests {
let log_mark = move || match log {
Log::Busy => Some(format!("{:?}", start.elapsed())),
Log::Quiet => Some("the same line".to_owned()),
Log::Looping => Some(
["error: no peer", "retrying in 5s"][start.elapsed().as_millis() as usize / 10 % 2]
.to_owned(),
),
Log::Unreadable => None,
};
wait_for_blocks(
Expand All @@ -2154,15 +2173,27 @@ mod tests {

#[test]
fn waits_while_a_long_chain_loads() {
// Replaying 166k blocks took 15 min, far past the quiet limit, the log busy throughout.
// Replaying 186k blocks took 34 min, far past the quiet limit, the log busy throughout.
starting_for(Duration::from_millis(600), Log::Busy, None).unwrap();
}

#[test]
fn gives_up_on_a_sequencer_that_went_quiet() {
let err = starting_for(Duration::from_secs(60), Log::Quiet, None).unwrap_err();
// A sequencer stuck repeating one line, e.g. retrying an error, never got further.
assert!(
err.to_string()
.contains("nothing new in the sequencer's log"),
"{err}"
);
}

#[test]
fn gives_up_on_a_sequencer_going_round_in_a_loop() {
let err = starting_for(Duration::from_secs(60), Log::Looping, None).unwrap_err();
assert!(
err.to_string().contains("nothing in the sequencer's log"),
err.to_string()
.contains("nothing new in the sequencer's log"),
"{err}"
);
}
Expand All @@ -2185,6 +2216,7 @@ mod tests {
fn says_how_long_it_waited() {
assert_eq!(duration_text(Duration::from_secs(30)), "30 s");
assert_eq!(duration_text(Duration::from_secs(250)), "4 min");
assert_eq!(duration_text(Duration::from_secs(4 * 3600)), "4 h");
}

#[test]
Expand Down
27 changes: 25 additions & 2 deletions src/fetch.rs
Original file line number Diff line number Diff line change
Expand Up @@ -144,15 +144,38 @@ pub(crate) mod tests {
use std::io::{Read, Write};
use std::net::TcpListener;

/// Reads a whole HTTP request, head and body. A server that answers and closes with some
/// of it unread makes the OS reset the connection, and the client sees no answer.
pub(crate) fn read_request(stream: &mut impl Read) {
let mut seen = Vec::new();
let mut chunk = [0u8; 4096];
// The request's length, once its head is in: the head and a Content-Length body.
let length = |seen: &[u8]| {
let end = seen.windows(4).position(|w| w == b"\r\n\r\n")?;
let head = String::from_utf8_lossy(&seen[..end]).to_ascii_lowercase();
let body = head
.lines()
.find_map(|l| l.strip_prefix("content-length:"))
.and_then(|n| n.trim().parse::<usize>().ok())
.unwrap_or(0);
Some(end + 4 + body)
};
while length(&seen).is_none_or(|wanted| seen.len() < wanted) {
match stream.read(&mut chunk) {
Ok(0) | Err(_) => return,
Ok(n) => seen.extend_from_slice(&chunk[..n]),
}
}
}

/// Serves `body` to each of `requests` requests on 127.0.0.1, with `status`.
pub(crate) fn serve(status: &'static str, body: &'static [u8], requests: usize) -> String {
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
let url = format!("http://{}/program.bin", listener.local_addr().unwrap());
std::thread::spawn(move || {
for stream in listener.incoming().take(requests) {
let mut stream = stream.unwrap();
let mut request = [0u8; 1024];
let _ = stream.read(&mut request);
read_request(&mut stream);
let head = format!(
"HTTP/1.1 {status}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
body.len()
Expand Down
5 changes: 2 additions & 3 deletions src/rpc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -101,13 +101,12 @@ mod tests {

/// An Rpc against a one-request server that answers `body`.
fn answering(body: &'static str) -> Rpc {
use std::io::{Read, Write};
use std::io::Write;
let listener = std::net::TcpListener::bind(("127.0.0.1", 0)).unwrap();
let url = format!("http://{}", listener.local_addr().unwrap());
std::thread::spawn(move || {
let (mut stream, _) = listener.accept().unwrap();
let mut request = [0u8; 4096];
let _ = stream.read(&mut request);
crate::fetch::tests::read_request(&mut stream);
let head = format!(
"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
body.len()
Expand Down
12 changes: 2 additions & 10 deletions src/runtime/docker.rs
Original file line number Diff line number Diff line change
Expand Up @@ -275,17 +275,9 @@ impl Runtime for Docker {
run_attached(cmd.arg("sequencer"))
}

fn log_mark(&self) -> Option<String> {
// Its last line, with Docker's timestamp to the nanosecond, so a repeated line counts.
fn last_log_line(&self) -> Option<String> {
let mut cmd = self.compose();
cmd.args([
"logs",
"--tail",
"1",
"--timestamps",
"--no-log-prefix",
"sequencer",
]);
cmd.args(["logs", "--tail", "1", "--no-log-prefix", "sequencer"]);
stdout_within(&mut cmd, Duration::from_secs(10)).ok()
}
}
Expand Down
Loading
Loading