Skip to content

Latest commit

 

History

History
1014 lines (803 loc) · 60.6 KB

CONTRIBUTING.md

File metadata and controls

1014 lines (803 loc) · 60.6 KB

Contributing

This file sets the rules and the terms under which you contribute to EthLib. They apply to every contributor, human or AI. How to build and test is in the README.

EthLib is a library of formally verified Ethereum primitives, written in Lean. Each primitive implements a published specification, from whichever part of the protocol it comes. Clients and other Lean projects build on it. A bug here spreads to everything built on top of it. So every line must be correct and justified by its source.

The bar

Work the way the author of a standard would.

  • Read the specification, the surrounding code and the existing proofs before writing anything.
  • Every definition, value and rule has a source. You have read that source.
  • If a source is ambiguous or two sources disagree, stop and say so. Do not pick one silently.
  • Never invent a citation, a section number, a test vector or a known answer.
  • Never claim a check passed unless you ran it and saw it pass.
  • Keep changes small and on topic. Give each pull request one idea.

When you are not sure, ask. A question costs minutes. A plausible guess merged into this library costs far more.

Sources of truth

Each module implements a published specification. It can be an EIP, an RFC, a NIST or SEC standard, an ePrint paper, an ethresear.ch post, or any other primary source. When several exist, use the most authoritative one. That specification is normative. When the code and the specification disagree, the code is wrong until someone shows otherwise.

Cite the exact document and section in the code that implements it. For example: RFC 9380 §5.3.1, or EIP-4844 with the name of its section.

EthLib is a formal specification. ethereum/execution-specs and ethereum/consensus-specs are reference points, not formal specifications, so the code never cites them as the authority for a rule. You can read them to understand a rule and to check your work. If no primary source states a rule, state the rule itself in the doc comment.

The Lean text never names or links execution-specs or consensus-specs, in a doc comment or in any other comment. The READMEs of the modules under EthLib/ never name or link them either. Their pinned commits belong to the test suites that run their vectors, as ARCHITECTURE.md explains. Where execution-specs or consensus-specs is the only text that states a rule, the doc comment or the README states the rule itself, formally. Where a reader needs context, one short line gives it in EthLib's own words, without naming either text. Some EIPs state a rule only through a link to consensus-specs at a pinned commit, as EIP-4844 does for its KZG functions. Such a rule cites the EIP.

Do not cite another implementation as the authority for a behaviour. A byte-for-byte match with a client is a useful test, not a justification.

Step comments

A definition that implements a step-by-step procedure marks each step of its source in a -- comment, right above the line that computes that step. The comment names the step and states it formally, in ASCII, so that an auditor can match the two line by line. For example, the line that computes RFC 6979 §3.2 step d has the comment -- Step d: `K = HMAC_K(V || 0x00 || int2octets(x) || bits2octets(h1))`. above it. A step of the Keccak sponge of FIPS 202 Algorithm 8 reads -- Steps 3 to 6 for i < n - 1: from S = 0^b, S = f(S ^ (P_i || 0^c)), with P_i read from N. Its bound i < n - 1 marks a departure from the source: the last block is absorbed apart.

A step comment is formal, short and precise, like the text of an RFC or a FIPS standard.

  • Where the source states its steps as formulas, as an RFC, a FIPS standard, the Yellow Paper or a paper does, the comment uses the notation of the source.
  • Pseudo-code that the source itself writes, such as v[a] := (v[a] + v[b] + x) mod 2**w in RFC 7693 §3.1, is the notation of the source and stays as the source writes it.
  • Where the source states a step in words, or only in code, the comment states it in mathematical notation or in short, plain words.
  • A step comment never quotes code in a programming language. That covers the Python of ethereum/execution-specs, of ethereum/consensus-specs and of the reference code in an EIP. It also covers a loop, a condition or an assertion written in the syntax of a language, such as for log in receipt.logs: or pubkey_size == 48 and amount_size == 8. The Lean line under the comment is already the code, and the same step in another programming language gives an auditor nothing new to check.
  • A step comment names things in plain words, never by the code identifiers of a source, such as the snake_case field names of EIP-7928. It writes -- A storage key of an account never appears both among its storage changes and among its storage reads. The notation of a formula, such as V, P_i or int2octets, stays.
  • A step that keeps the words of its source writes them as plain text, without quotation marks or Markdown emphasis such as bold. EIP-7928 writes "Record post-transaction nonces for:", so the comment reads -- Record post-transaction nonces for:, followed by its list of accounts.

Step comments never trace ethereum/consensus-specs or ethereum/execution-specs, and never name them or their functions. Where one of those texts is the only one that states a rule, the step comments state each step formally, in EthLib's own terms. A defect found while reading them is reported upstream, as Defects found upstream says, not copied into the code.

Where EthLib departs from the steps of its source, the comment says how and why. Examples are a fork branch folded into one function, an overflow check, a loop bound, or a value computed once and reused. In the RFC 6979 code, one comment above the shared value says that steps d and f reuse it. When the step comments describe a step-by-step procedure, the doc comment of the definition states what the procedure computes and does not repeat its steps.

Defects found upstream

Formal work often finds defects in the documents that EthLib specifies. A proof that does not close, a vector that disagrees, or a definition that contradicts its source can show a bug in an EIP, a specification, an API or a test suite. Such a defect must never stay only in EthLib: report it to the repository that owns the document.

  • Confirm the defect first. Reproduce it at the head of the target repository's default branch, and search its open and closed issues and pull requests.
  • If the fix is clear, open one small pull request in the target repository for each defect, in that repository's style. A minor defect, such as a wrong example or a broken constant, gets a pull request too.
  • If the fix needs a design decision, open an issue there with a concrete example instead.
  • If the defect is a security vulnerability, do not disclose it in public. Report it privately through the target repository's security policy, or through the Ethereum bug bounty program for the protocol specifications.
  • Describe the defect from the documents alone: never name an implementation.
  • Link the upstream pull request or issue from the related EthLib issue, and record any divergence that remains in SOUNDNESS.md.

Bugs come from EthLib's own work. Do not search the upstream repositories for bugs outside of it.

Implementations of an affected rule

EthLib is a specification, and no implementation of the protocol is a source for its rules, as Sources of truth says. Their code is worth reading as a check on EthLib's own work. A defect in a specification often lives on in the code built from it. An edge case that an implementation handles with care can point to a proof or a test vector that EthLib lacks.

When EthLib work finds a defect, or a rule with a subtle edge case, look at how the implementations of that rule handle it. For the protocol, these are the consensus and execution clients in production on Ethereum mainnet. For a shared component, such as libp2p, BLS signatures or KZG commitments, they are the libraries that those clients depend on for it. No other project is in scope. Look only at the implementations of the rule that the work touches: do not scan their repositories for other bugs.

  • If the flaw is a security vulnerability, do not disclose it in public. Report it privately through the security policy of that repository, or through the Ethereum bug bounty program when the program covers it.
  • Otherwise, confirm the flaw at the head of the default branch of that repository, and search its open and closed issues and pull requests. Then open a pull request or an issue there, in its style, as for a defect in a document.
  • If an implementation shows a case that EthLib does not prove or test, open an EthLib issue for the missing proof or vector. Take the expected result from the specification, never from the implementation. Describe the case from the documents alone: EthLib's own issues, pull requests and code never name an implementation.
  • Keep reports to an implementation out of EthLib: a link to one names the implementation, and a link to a private report discloses it.

Layout

EthLib/<Domain>/<Module>/            the library code
EthLib/<Domain>/Proofs/<Module>/     theorems about it
EthLib/<Domain>/Exports/             the C exports the bindings call
bindings/python/                     the C extension and the Python package
tests/<domain>/<module>/             generated test vectors

ARCHITECTURE.md says which domain a module belongs to, what it may import and which types it shares. A new domain adds its proof root to the Proofs library in lakefile.lean. The library code never imports the proofs. Proofs live in their own Lake library, so the library code builds and links without them.

The C exports live in a third library, Exports, so a Lean project that imports the specification gets no @[export] symbol. A new domain with exports adds its export tree to the globs of the Exports library in lakefile.lean. A new module under Base/Exports/ is listed there by name, since the conversion core of that tree belongs to another library. Keep EthLib.Exports as its only root so that it remains a native plugin.

The Python conversion core and its law proofs form PythonConversions, which both the exports and the remaining proofs can import without a cycle between native libraries. Its law module lives under Base/Proofs/Exports/ and enters the exports through meta import, so its object does not link into the Python extension. Code that a meta import makes runnable must not reach the specification. scripts/check_layers.py allows one exception: a specification module whose own imports are all in the Lean toolchain. Such a module runs no other specification code, so the conversion core can share it, as it shares the hex reader of Base/HexDigits.lean. That module is a root of PythonConversions, so the exports link no code of the EthLib library.

These four libraries form one package, EthLib. A property or a model may import Mathlib, Batteries or VCVio, and it goes in EthLib/<Domain>/Proofs/<Module>/ like any other property. Among the properties, only a refinement module imports a model directly, as ARCHITECTURE.md explains. The specification and the exports import nothing beyond the Lean toolchain. ARCHITECTURE.md describes the package.

Lean

Library code

  • Write the code to be read first and run second. Clarity wins over speed unless speed is the point of the change.
  • Name things after the specification. If the paper calls it the randomizer, the code does too. Where consensus-specs is the only text that states a rule, a definition may keep the name of that rule, such as process_slots, in Lean's casing.
  • Write the digits of a new name in ASCII, such as h1, x0 and w2, not h₁, x₀ and w₂. Names that Lean, Mathlib or VCVio define, such as mul_inv_cancel₀, keep their own spelling. Prose writes powers and indices in ASCII too, as WRITING.md says.
  • Reject malformed input at the boundary with a typed error. Do not truncate or pad it, and do not replace it silently with a default.
  • Put invariants in types, such as Vector lengths and Fin bounds.
  • Avoid partial def in new code. A function the kernel cannot unfold is a function nobody can prove anything about.
  • Do not use panic! or the ! accessors, such as xs[i]!, get! and set!. Each one hides a failure: it returns a default value, or it changes nothing. Index with Fin or a Vector, walk arrays of equal length together with zip, or return a typed error. No module of the specification uses them, and lake exe check-accessors fails on a new one.
  • Remove such an accessor even when no input that the source accepts reaches its default. A caller of a public function can still reach it, with arguments that break a precondition the type does not state. Change the definition in place, and keep no copy of the old one beside it. Wherever the old index was in range, the result must not change. Existing theorems and tests keep their meaning, and change their statements only where the type of the result changes. If any input reached a default where the source gives another outcome, the change is a fix. It cites the rule of the source that it restores. Take its test vectors from the source's own suite when one holds them. Otherwise take the expected value of each one from that rule, never from EthLib. Describe what each vector pins, and record its origin next to it, as Known answers asks.
  • Do not add an explicit index default, such as xs.getD i d, xs[i]?.getD d, headD or setIfInBounds, for the same reason. Past the end it returns the default or changes nothing, as a ! accessor does, and compiled code prints no message. Use one only where a source defines the value past the end, such as a jump past the end of the code, which is never valid. lake exe check-accessors fails on a new one, unless it joins the list of the sources with that rule.
  • Prefer structural recursion, map and folds to Id.run do with mutable variables. A proof then follows the shape of the definition. A theorem about a do loop restates its elaborated body, so any edit of the loop breaks the statement. For a loop that can stop early, prefer foldlM in Option or Except. This is advice, not a rule: a loop whose speed matters can keep do.
  • Prefer an Except do block for a chain of steps that can fail, so that it reads like the source. In proofs, prefer the success and failure lemmas to unfolding the chain into nested match expressions. bind_ok_iff is in EthLib.Base.Except, and the other lemmas are in EthLib.Base.Proofs.Except.
  • A small decidable fact that Known answers allows, such as a constant checked against its algorithm, evaluates a definition in the kernel. That definition needs a recursion that the kernel can reduce. decide and rfl need structural recursion or fuel, because Lean makes a well-founded definition irreducible. decide +kernel also reduces a well-founded recursion whose measure is a single Nat, which Lean builds on WellFounded.Nat.fix. Do not count on it for a lexicographic measure, such as a pair, which Lean builds on WellFounded.fix. Lean documents only WellFounded.Nat.fix as reducing on closed terms.

Failure at an entry point

An entry point is a public operation that a client or another layer calls. Examples are a state transition, a gossip validation and an Engine API method. What an entry point does with a wrong input is part of the protocol, so its source often says what it returns.

  • Where the source defines the outcomes of an operation, return them as a type. For example, the Engine API answers a payload with one of five statuses, and gossip validation returns a ValidationResult: accept, ignore or reject. Map the internal errors to that type with total functions, close to the entry point. For example, after the checks of a payload, newPayloadOnChain maps an execution that aborts to .syncing, and any other failed transition to .invalid.
  • Return a Bool only where the source defines one. A caller that the source requires to tell outcomes apart, for example to import or to queue a block, receives the richer type.
  • Where the source fixes the order of its checks, and the order changes the outcome, follow that order. Pin it with a theorem, or with a test whose input fails two checks. Elsewhere, the source fixes only that the operation rejects the input. The consensus specification, for example, says only which state transitions are invalid. This guide does not say whether EthLib also promises which error such an input gets. Many proofs and Python tests pin the exact error today, and bindings/contract/contract.json lists the error codes of its methods.
  • Where the source requires the state to be unchanged on failure, state that in a theorem. When the operation returns its input state on failure, state it as equality of the returned state. Inside a step, such as an EVM call that fails, state it over the values a caller can read: balances, nonces, code, storage and transient storage. Do not state it over the fields of the representation, since a new representation would break the statement. processMessage_reads_of_error states it for a failed EVM call, over each account, each word of storage and transient storage, and the code at each code hash. processCreateMessage_reads_of_error states the same for a failed creation.

Proofs

  • Do not use sorry, admit or a new axiom. CI builds with --wfail, so an unfinished proof fails the build.
  • Prefer proofs the kernel checks on its own.
  • Do not use a tactic that trusts compiled code, such as native_decide, bv_decide or decide +native. Their computed results are justified by compiler-trusting axioms rather than kernel evaluation. lake exe check-decls fails on any use.
  • Do not use vcgen or mvcgen in library proofs while vcgen is marked experimental. The reason is stability across toolchains, not soundness: the kernel checks a proof that vcgen builds like any other proof. In Lean v4.36.0, mvcgen is deprecated in favour of vcgen, and vcgen warns that it is experimental unless the option experimental.vcgen is set. Check this rule again at each update of the toolchain.
  • After a proof change, check its axioms with lake exe check-decls. The goal is propext, Classical.choice and Quot.sound, nothing else.
  • Do not leave a command such as #print axioms, #eval or #check in a module under EthLib/. It runs at every build of the module, and lake exe check-decls already fails on any theorem that depends on an axiom beyond the three standard ones. scripts/check_lean_commands.py fails on one, unless scripts/check_lean_commands_allowlist.txt lists it with the reason it must run at build time.
  • Name each theorem by the naming conventions of Mathlib. The name is in snake_case and describes the statement: the conclusion first, then _of_ and the hypotheses.
  • Prove what a reader cares about: round trips, injectivity, the rejection of bad input and the invariants of a state transition. Above all, prove agreement with the specification.

Known answers

A known answer pins one input to one output, byte for byte. Known answers never enter the default build: the libraries EthLib, Proofs and Exports, which lake build builds. They may run in three places outside it:

  • The Python test suite, in bindings/python/tests/, runs them through the bindings, which are the surface that clients call.
  • A fixture runner, a Lean executable that no default target builds, may run pinned fixtures through the definitions of the specification. It reaches an internal step that has no C export, and it runs compiled code, as the Python suite does.
  • A Lean library of kernel vectors, which no default target imports, may prove known answers. CI must build it in its own step on every pull request, so that a failure points at the pull request that caused it. It is KernelVectors, in tests/kernel/, and lake build KernelVectors builds it.

In Lean, a known answer is a theorem or an example that evaluates a definition on concrete inputs. It compares the result with an expected value, by rfl, decide, decide +kernel or simp. The build must then run the definition on those inputs. One such proof can need several gigabytes of memory and minutes of build time. It also checks only one input.

So the library of kernel vectors holds such a proof only under a budget. Each proof takes its input from the specification's own vectors, or covers every value of a finite type. Each file of the library elaborates in under 20 s of CPU, with a peak memory under 2 GiB. The budget is for the whole file, run alone with lake env lean after its imports are built, as scripts/check_memory.py runs it.

State each theorem of the default build for all inputs. Test concrete inputs from Python, through the bindings, or through a fixture runner. If a function that clients call has no C export yet, add the export and its binding.

The default build keeps one kind of concrete fact: a small decidable fact that a definition needs to be correct. Examples are a constant checked against the algorithm that generates it, or a Pratt certificate. The order of the fork timeline is another example. Each such proof must take a few seconds at most.

Take the test vectors from the specification's own test vectors when they exist. Otherwise, describe what each vector pins. For example: "one honest signature at epoch 7", or "one empty slot processed". Next to the vectors, record their pinned origin, such as the commit they come from.

Never regenerate an expected value from the code under test and call it a check. A snapshot of values that the code computes, compared in CI, is a change detector and not a check. A pull request that changes such a snapshot names the source of each changed line.

No examples

EthLib proves general statements about the specification, and it keeps no examples. An example is a proof about one particular program, contract, state or value, written to show how a rule or a tool works. Do not add files of such proofs, and do not add them to other modules.

Example logic belongs outside the repository, with the project that needs it. EthLib keeps the general rules and lemmas that such a proof uses. If an example needs a general lemma that EthLib lacks, add the lemma, stated for all inputs.

A new rule or tactic is justified by its general statement. Show its example in the description of the pull request, not in the tree.

No benchmarks

A benchmark is a measurement on one machine, at one commit, against one set of references. It is not part of the specification, and it ages as soon as EthLib or a reference changes. So the repository keeps no benchmark code, benchmark inputs or tables of results.

Benchmarking is welcome for a given problem or pull request. Run it locally, outside the tree, and keep its scripts and data out of your commits. Give the numbers in the description of the pull request, with the machine and the command that produced them.

Writing

Developers all over the world read EthLib, many of them in their second language. The writing guide offers advice for clear, precise and correct prose: documents, comments, commit messages, contribution descriptions and reviews. Its vocabulary helps distinguish technical meanings. For advice about sentence structure and punctuation, use the guide in context. The source, proof, citation and testing requirements elsewhere in this file still apply.

Claim only what the code, a theorem or a check that you ran shows.

Leave clear, correct text alone, even when it does not follow a writing rule. Read the surrounding passage before an edit, and preserve its meaning, conditions and requirement strength. Correct real clarity or accuracy problems; leave unrelated prose for a separate change. Technical accuracy and established terminology take priority. Repository habit alone does not justify unclear writing.

The optional scripts/check_writing.py reports vocabulary, phrasal-verb, Latin-abbreviation, contraction, reference-history and approximate sentence-length suggestions. It reads Markdown and Lean comments; review other prose manually. It also reports each Lean doc comment that is too long (rule D1). That is a module or section doc of more than six lines, or a declaration doc of more than four. Blank lines, link reference definitions and fenced blocks do not count. With --base, D1 reads every Lean file that the branch changes or renames, also on the lines that the branch does not change. With file arguments, it reads each Lean file given. For a local editing aid, run:

uv run --no-project --python 3.12 python scripts/check_writing.py --base origin/master

For a stacked pull request, give its actual parent branch. Read suggestions in context and leave clear, correct text alone. CI reports suggestions on changed prose and pull request descriptions as warnings. Suggestions and unsupported-input notices return success; Git, usage and configuration errors remain failures. The checker does not establish clarity, technical accuracy or STE conformance.

When you change the checker, also run its tests:

uv run --no-project --python 3.12 python -m unittest discover -s scripts -p 'test_check_writing.py'

Documentation

Write for a smart reader who has never seen the file.

Two kinds of documentation live here, and they are read differently. A doc comment in Lean sits next to the code and is read a few lines at a time, so it is terse. A Markdown file is read from top to bottom, like a chapter, so it is prose.

These rules hold for both:

  • Use short, plain words. Define a term the first time it appears.
  • Explain why, not what. The code already says what.
  • Use ASCII for math and layouts: x_i, 2^32, sum_i.
  • In a Markdown file, draw a byte layout in a fenced text block. In Lean, each field of a layout has its comment above the line that writes or reads it.
  • Do not add marketing or filler. Words such as "robust", "seamless", "comprehensive" and "it is worth noting" go.
  • Do not hedge a claim that the evidence supports, and keep an uncertainty that the evidence does not resolve.
  • Do not write editorial headings such as # Why this matters.
  • Describe the code as it is now, without words such as "previously", "the fix" or "as discussed".

Doc comments in Lean

A reader of a Lean file reads the code and the comment next to it, a few lines at a time. So the documentation sits next to the code that it describes. A long block at the top of a module or a declaration goes unread, and it drifts apart from the code.

Each piece of documentation has one place:

  • A module header is a title, one or two lines on what the module provides, and its source. As a rule, it has at most about five lines, and the writing check flags more than six. It does not restate the proofs, the algorithm or each definition of the module. A section comment /-! ## ... -/ is a title, with at most a line or two under it.
  • The doc comment of a definition or a theorem is one line, or a few short lines. The writing check flags more than four. It says what the definition returns or what the theorem states, with the hypotheses in words.
  • Each detail of a procedure is in a -- comment right above the line that does it. A detail is a step, an offset, a size, a check or an edge case. Step comments gives the form of a step of a source.
  • Each other non-obvious step of a definition has its comment above the line that does it.
  • In a proof, each non-obvious step has its comment above the tactic that does it.

When you shorten a header or a doc comment, move each fact that it held to the line that it describes, and delete none. A fact about the declaration as a whole, such as what it does not verify, stays in its doc comment, in a few words.

Shortening never makes a comment harder to read. A list stays a list: each source keeps its bullet with what it gives, and each case or field keeps its own line. Two sentences are never joined with a semicolon or a comma to save a line. A list of sources or cases can run past the line count of the writing check. That count is advice, not a target.

The rules of form are these:

  • Write one sentence per line. A sentence that wraps onto a second line is too long, so split it. This holds for list items too.
  • Keep each line to at most 100 characters. A URL alone on its line is the only exception.
  • Leave a blank line between the sentences of a comment. Space makes a dense subject readable, and the layout check fails when two sentence lines touch.
  • Refer to a definition, a theorem or a field by what it does, not by its name, because names change and the comment goes stale. Notation such as (X, Y, Z) and a type that the sentence is about, such as G1, can be in backticks.
  • Write math in ASCII, and do not quote code in another programming language, as Step comments says.
  • Keep a long link out of the sentence. Write [text][ref] in the sentence, and the definition [ref]: <url> at the end of the comment.
  • Put formulas that span several lines in a fenced text block. The layout check reads a line of a comment outside such a block as prose.

The example is the encoder of a signature layout. The doc comment says what the definition returns. The comment above each line gives the size and the order of the field that the line writes:

/-- Encode one layer's signature: 1156 bytes on a lower layer, 1188 on the top one. -/
def encodeLayerSignature {layer : Layer} (sig : LayerSignature layer) : ByteArray :=
  -- The counter `BE_32(c)`, a big-endian 32-bit word: 4 bytes.
  packBytes (toByte COUNTER_LEN sig.counter.toNat)
    -- The 64 chain values, in chain order: 1024 bytes.
    ++ packDigests sig.chainValues
    -- The `h` siblings, from the leaf up to the root: `16 h` bytes.
    ++ packDigests sig.path

In each changed Lean file, the writing check flags a long header or doc comment, as Writing describes.

Markdown files

A README, SOUNDNESS.md or a guide such as this one reads like a short chapter of a good mathematics textbook. It is precise, concise and written to teach.

  • Write paragraphs. A paragraph develops one idea over several sentences that lead into each other. A blank line after every sentence breaks that thread, so leave one only between paragraphs.
  • In the source, start each sentence on a new line. Markdown joins the lines of a paragraph, and a diff then shows one sentence per line.
  • Lead with the problem, then the idea, then the details. The reader should know why an object exists before meeting its definition.
  • Show one small, concrete example where it helps, with the steps written out. Take its values from the specification or work them out by hand, never from the code under test.
  • Keep bullets for content that is a list: operations, cases, files, commands. A bullet holds a full thought, not a fragment of a sentence.
  • Use a Markdown table for tabular content.
  • Name a file or a theorem where the reader needs to find it, not in every sentence.

When a module does not follow these rules, apply them to what you change. Do not reformat untouched code in an unrelated pull request.

Bindings

The C exports and the Python package are the public surface for clients.

  • Export the operations a client calls, under the specification's names, and the object sizes. Keep internal steps, such as one hash or one helper of a state transition, inside Lean.
  • Read every size from Lean at load time. Never hard-code a length in C or Python.
  • The generated C frees each argument itself. A wrapper must not free what it passes to an export.
  • The extension runs without the GIL on a free-threaded build of CPython. So a wrapper never reads the items of a list in place, since another thread may change the list. It reads them through sequence_snapshot, which copies a list into a tuple, or it passes the list to the generic converter, which copies it too. In the table of bindings in EthLib/Base/Exports/Bindings.lean, a signature writes an argument that its wrapper reads through sequence_snapshot as a Sequence. That function copies any iterable, but these arguments are ordered batches, so a set or another unordered iterable must not type-check. A list argument of the converter is written list[T], and lake exe gen-bindings lets the stub accept a tuple there too. tests/contract/test_sequence_readers.py checks each signature against the C wrapper. A wrapper of the package takes a list[T] argument of the converter as a Sequence[T] and copies it into a list for the extension, and it passes a Sequence argument of the stub on unchanged. When a str could be an item, as for str, Any, object or a union that holds str, the wrapper takes list[T] | tuple[T, ...] and passes it on, since a bare str is itself a Sequence[str]: the extension then still rejects it.
  • A Python function passes its arguments to the export and returns its result. It never encodes or decodes bytes by hand: no slices, no integers or text to or from bytes, no JSON text. Lean then defines every value that crosses the boundary, and its proofs can cover that value.

scripts/check_python_boundary.py finds the usual forms of such conversions in bindings/python/ethlib. It fails on any conversion in the package that scripts/check_python_boundary_allowlist.txt does not list. That list names the conversions that remain from before the rule. A new entry is an exception that a maintainer approves, so the list only shrinks otherwise.

Checks

Run these checks before you open a pull request:

lake build

It builds the library and every proof, with warnings treated as errors in CI.

Then check the compiled declarations:

lake exe check-decls

It reports any axiom beyond the standard three, and any partial, opaque, unsafe, @[extern], @[implemented_by] or @[csimp]. It also reports a definition of the specification that cannot unfold in the kernel, for example because it uses while or IO.

scripts/check_decls_baseline.txt lists the findings that exist today, and the goal is to remove each one. A pull request that removes a finding removes its line, or the check fails on the stale entry. A new finding is fixed, never added to the list.

When you change the check, also run scripts/test_check_decls.sh.

Then check the defaulting accessors of the specification:

lake exe check-accessors

It lists each use of a ! accessor, such as xs[i]!, get! or set!, or of panic, in the elaborated declarations of the specification, with its count. It also lists each explicit index default, such as xs.getD i d, xs[i]?.getD d, headD or setIfInBounds. scripts/check_accessors_baseline.txt is the exact list of the sites that remain to fix, and it holds no ! accessor. scripts/check_accessors_sources.txt is the exact list of the index defaults whose value past the end a source defines. Each of its entries gives that rule and its source after #. A new site is fixed, never added to the baseline. It joins the list of the sources only with the rule of its source.

When you change the check, also run scripts/test_check_accessors.sh.

Then check the values of the rules that forks change:

lake exe rule-history --check

It fails when, at some fork, a rule of the execution layer computes a value other than the one that tests/execution/history/rules.tsv records. The README next to that file says how to update it.

When you change the tool, also run scripts/test_rule_history.sh.

Then check which theorems the specification keeps:

lake exe check-theorems
uv run --no-project --python 3.12 python scripts/check_theorems_baseline.py --base origin/master

The check follows the dependencies of definitions, instances and persistent @[simp] theorems. It reads private proof terms and resolved references from Lean's .ilean files, including named lemmas that simplification erases from a proof term. Helpers of retained theorems stay with their consumers. The .ilean references can miss a lemma named only in a tactic macro; review those dependencies before moving a reported theorem. The attribute guard permits simp, deprecated and inherit_doc. Deprecation and documentation metadata do not retain an otherwise unused theorem. An unsupported persistent attribute written on a theorem or in an attribute command stops the check. Review custom command macros for attributes they generate, since the source guard does not expand them. Other theorems belong under Proofs/, as ARCHITECTURE.md explains.

To inspect the findings and their source locations, run lake exe check-theorems --list. It prints tab-separated columns for the defining module, theorem name, source path and first and last lines.

scripts/check_theorems_baseline.txt lists the findings awaiting migration, and may only shrink. A new finding or a stale baseline entry fails the check. The baseline check rejects entries added since the base revision, after the initial creation of the file. It also rejects removing a baseline that the base revision has. For a stacked branch, compare with its actual parent instead of origin/master. Moving a public theorem can change the imports a downstream project needs, so review that public surface too.

On pull requests, CI compares with the first parent of the merge commit. On pushes to an existing branch, it compares with the revision before the whole push and fetches that commit if the checkout lacks it. Other runs use HEAD^1.

When you change either check, also run its tests:

scripts/test_check_theorems.sh
uv run --no-project --python 3.12 python -m unittest discover -s scripts -p 'test_check_theorems_baseline.py'

Then check which consensus rules the theorems reach, fork by fork:

lake exe proof-coverage --check

A rule is a definition that a person wrote in a specification module under EthLib/Consensus/, other than an instance or a field of a structure. The report grades each pair of a rule and a fork of the beacon chain in three tiers. Every pair is executable, because the rule runs at that fork. A pair is touched when the statement of a theorem in a property module mentions the rule, and the theorem holds at that fork. A pair is characterized when coverage/characterizes.txt claims that such a theorem states the main contract of the rule. The report reads statements only, never proofs, so a proof that unfolds a rule does not touch it.

The forks at which a rule or a theorem holds come from its type. A binder such as .altair ≤ fork, fork < .pectra or fork = .phase0 keeps the forks that the bound allows. A type with no fork variable holds at the forks that it names, such as .glamsterdam, or at every fork if it names none. Any other hypothesis on the fork alone, such as fork ≠ .altair, leaves the forks unread. Such a declaration counts at no fork, and lake exe proof-coverage lists it.

Add a claim, a line with the rule and then the theorem, when the theorem states the whole result of the rule. A theorem of the form rule … = .ok r ↔ … usually does. A theorem that states one property of the result, such as the fields that a step leaves unchanged, stays touched. The report fails on a wrong claim:

  • the rule is no rule;
  • the theorem is no theorem of a property module;
  • the statement of the theorem does not mention the rule.

scripts/proof_coverage_baseline.txt is the exact list of the pairs above executable, each with its tier. The check fails when a pair drops a tier, and also when one rises, so each change of coverage is a line that a reviewer reads. When the change is intended, run lake exe proof-coverage --update, then regenerate SOUNDNESS.md as below.

When you change the report, also run scripts/test_proof_coverage.sh.

Then check that SOUNDNESS.md still holds:

uv run --no-project --python 3.12 python scripts/soundness_facts.py --check
uv run --no-project --python 3.12 python -m unittest discover -s scripts -p 'test_soundness_facts.py'

It fails when a fact it generates, such as the theorems that still use native_decide, no longer matches the repository. Run it without --check to regenerate them.

It also fails when pyproject.toml declares a package version other than the one SOUNDNESS.md describes. Then review the whole document for the new version, and update its version line by hand.

A release has one version, in the form MAJOR.MINOR.PATCH. It appears twice: in pyproject.toml for the Python package, and in lakefile.lean for Lake. A version bump changes both, and this check fails when they differ:

uv run --no-project --python 3.12 python scripts/release_manifest.py --check
uv run --no-project --python 3.12 python -m unittest discover -s scripts -p 'test_release_manifest.py'

When a tag v<version> is pushed, publish.yml runs the same check against the tag. It then attaches release-manifest.json to the GitHub release. The manifest records the version, the Lean toolchain, the revision of each Lake package, the fixture pins of tests/sources.toml and the exported C symbols.

Then check the imports of every Lean module:

uv run --no-project --python 3.12 python scripts/check_layers.py

It fails on an import that breaks a rule of ARCHITECTURE.md, and on a module that no library root imports. An import that must break a rule goes in scripts/check_layers_baseline.txt, with the reason in a comment and in the pull request. Each entry starts with the label of the rule that the import breaks, and it allows the import to break only that rule. The file lists the labels. An entry whose import no longer breaks its rule fails the check, so remove it with the import. A new model directory or a new refinement module goes in coverage/kinds.toml, which the same check reads, and an entry leaves with its module.

When you add or change a C export that reads a fork name, check that it rejects the forks whose rules EthLib lacks:

uv run --no-project --python 3.12 python scripts/check_fork_cap.py

An export caps its fork with forkUpTo in EthLib/Base/Exports.lean, which names the last fork whose rules the export holds. Without the cap, a later fork would get the rules of the fork before it. An export may read the fork without a cap only if its rule does not change at the next fork, or if it already rejects that fork. Such an export goes in scripts/check_fork_cap_allowlist.txt, with the reason on the same line. An entry that no longer reads a fork name fails the check, so remove it with the code.

When you touch test vectors or fixtures, also check their sources:

uv run --no-project --python 3.12 python scripts/check_fixture_pins.py

tests/sources.toml records one pinned commit for each repository that tests read from. The check fails when a test cites another commit, and when a directory with a SHA256SUMS file does not name its sources. The file also pins each release archive that is too large to vendor, by its URL, its size and its sha256. The check fails when no test names an archive.

tests/generators.toml records which program computed the expected values of each pinned directory and archive. Where no record names the program, it says so, with what was read. It also lists the modules that the Python tests import, and the version of each one that computes expected values while the tests run. The check fails when a directory or an archive has no entry, and when a pinned file belongs to no group of cases. It also fails when a test imports a module that the file does not list. A module that computes no expected value is a tool, and it needs a reason. So a new vector directory, or a new library in the tests, comes with its generator.

The check downloads no archive. With ETHLIB_ARCHIVES set, it also checks the groups of each archive against the member list in that cache.

Then check the layout of the Lean lines that your branch changes:

uv run --no-project --python 3.12 python scripts/check_lean_layout.py --base origin/master

It fails on a changed line longer than 100 characters, unless the line holds only a URL. It also checks the pairs of lines in a comment where at least one line is changed. It fails when a sentence runs from one line onto the next, and when two sentence lines touch. Lines that your branch does not change are not checked. A Lean file that git does not track yet counts as changed on every line.

With --all in place of --base, the check reads every line of every Lean file that git tracks. --rule wrap runs only the check of wrapped sentences; the other rules are length and touching. CI also runs --all --rule wrap, so no Lean file in the tree may hold a wrapped sentence.

These commands use uv and Python 3.12, with only the standard library. See prerequisites for setup.

When you touch bindings or test vectors, also run the Python suite:

uv sync --frozen --extra test
uv run --no-sync pytest -n auto

The suite rewrites the vectors, so then check that the pinned ones are unchanged:

uv run --no-project --python 3.12 python tests/cryptography/check_vectors.py

A test marked archive reads a release archive, and the suite skips it by default. To run such tests, set ETHLIB_ARCHIVES to a cache directory:

ETHLIB_ARCHIVES=~/.cache/ethlib/archives uv run --no-sync pytest -m archive

The first run downloads each archive that the tests name, and checks its size and digest. Each test then unpacks only the paths that it reads. The vectors-slow workflow runs these tests every Monday.

The parity tests in bindings/python/tests/parity are archive tests too. They run every case of execution-spec-tests and consensus-spec-tests at the forks in scope. They also run the fork choice compliance tests of the pinned release of consensus-specs. A case passes, fails, waits for a runner, or disagrees for a reason listed in tests/parity/disagreements.toml. Set ETHLIB_PARITY_REPORT to a file name to get the report of these outcomes for each fork and runner.

A gas rule is a named case in the calculation of a gas charge or refund. At each fork, the gas coverage report lists the instrumented rules that fixtures exercise or miss. From Berlin, for example, it counts warm and cold SLOAD separately. Build the fixture runner and run the report from the repository root.

lake build gas-coverage
ETHLIB_ARCHIVES=~/.cache/ethlib/archives PYTHONPATH=bindings/python/tests \
  uv run --no-sync python -m parity.gas_coverage --jobs 4 > /tmp/ethlib-gas-coverage.md

The report reads the pinned execution release and selected legacy and devnet block fixtures. It checks the observed run of a block against every header field that the body gives. These include the state and receipt roots and, from Pectra, the requests hash. It also checks the encoded block receipts when the fixture supplies them. It counts a block at its active fork after these checks pass.

Block events come only from included transactions, which may call system contracts. The system calls that a block makes itself run during replay, but their steps are not counted. From Dencun, the block calls the beacon roots contract. From Pectra, it also calls the history storage, withdrawal request and consolidation request contracts. From Glamsterdam, it also calls the builder deposit and builder exit contracts.

For a state test, it checks the state root and logs hash. It checks the encoded receipt, cumulative gas used and status when the fixture supplies them. Use --suite, --network, --format or --group to limit the replay. The command exits with status 1 if a fixture fails its checks.

When you change Python code, format it, lint it, check its types and its spelling, and run the tests of the scripts:

uv sync --frozen --extra test --group lint
uv run --no-sync ruff format
uv run --no-sync ruff check
uv run --no-sync ty check
uv run --no-sync ty check --python-version 3.10 bindings/python/ethlib
git ls-files -z '*.py' | xargs -0 uv run --no-sync codespell
uv run --no-sync python scripts/check_raises.py
uv run --no-sync python scripts/check_docstrings.py
uv run --no-project --python 3.12 python scripts/check_python_boundary.py
uv run --no-project --python 3.12 python scripts/check_python_comments.py --all
uv run --no-sync python -m unittest discover -s scripts

A test expects an exception through raises of bindings/python/tests/raising.py, which matches the whole message. Where the decoder computes a number from malformed bytes, raises_shape matches the whole message with any number at each {n} of its template. scripts/check_raises.py fails on any other use of pytest.raises, except a bare call in a function that scripts/check_raises_allowlist.txt lists with its reason. It also fails on a template with |, .*, a brace or a backslash outside {n}.

A test may pass an argument of a type that the stub does not admit, to check what the extension does with it at run time. It silences the type checker on the one line that the checker reports, with # ty: ignore[<rule>] naming the reported rule. A comment above that line says that the test asserts the runtime behaviour, and one comment above the first such line of a test or of a table of cases covers the rest of it. Two other kinds of line carry an ignore, each with a comment above it that says why. A type test checks that the checker rejects a misuse, and its ignore is the assertion. A line may read an attribute of the standard library that the stubs of the checked Python version lack. unused-ignore-comment fails on an ignore that no longer matches a diagnostic.

pyproject.toml turns every rule of ty into an error for the package, its tests, the scripts under tests/ and setup.py. So a weak type fails too: a bare dict or list, a value of json.loads returned as a typed value, or an override without @override. A new or changed test reads a JSON or YAML document through json_values.py or yaml_values.py of bindings/python/tests, which give a JsonValue and narrow it at each read. ty cannot catch the Any of a bare json.loads passed on as an argument, so a reviewer checks it.

A Python module docstring is one line that says what the module is. A fact that the code needs goes in a comment next to that code, or in the --help text of a script. A class or function docstring is one line when possible. Otherwise it has short sentences, one per line, with a blank line between groups. scripts/check_docstrings.py fails on a module docstring of more than one line, and on a docstring sentence that wraps onto a second line.

A comment follows the same rule: each sentence fits on one line. scripts/check_python_comments.py fails when a sentence of a comment runs onto the next line. The two checks find a wrapped sentence by one rule, which scripts/sentences.py defines. A list item and a field of a provenance record, such as Commit: <hash>, continue no sentence. After a line that ends with a colon, a line that starts in lowercase continues the sentence. The rule skips code blocks, doctests, headings, table rows and lines that hold only a URL. With --all, the comment check reads every Python file that git tracks or would add, as CI does. The docstring check, and the comment check with --all, read no symbolic link.

pyproject.toml configures each tool, and uv.lock pins its version.

Report what you ran and what it printed. If you skipped a check, say so.

Commits and pull requests

A reviewer should know in fifteen seconds what the change does and where to look.

Titles

Titles follow Conventional Commits 1.0.0. That holds for commit subjects and pull request titles alike. A squash merge turns the pull request title into the commit on master.

<type>(<scope>): <summary>

The type says what kind of change it is:

  • feat: new behaviour, such as a new function, module or export.
  • fix: behaviour that disagreed with the specification now agrees.
  • proof: new or changed theorems, with no change to the library code.
  • perf: the same results, computed faster.
  • refactor: the same behaviour, with the code restructured.
  • test: test vectors, known answers or the Python suite.
  • docs: documentation only.
  • build: Lake, the Lean toolchain, dependencies or packaging.
  • ci: the GitHub workflows.
  • chore: anything else that touches no library code, proof or test.

Conventional Commits defines only feat and fix. The other types are the common ones, plus proof, which this repository needs.

The scope names the domain or module, in lowercase: kzg, bls, ssz, rlp, bindings. Leave the scope out when the change spans the repository.

The summary is an imperative phrase, such as "add strict scalar decoding", or a noun phrase for the result, such as "strict scalar decoding for RLP". It starts lowercase and has no trailing period. A name in the summary keeps its own case, such as KZG or U256. The whole title fits in 72 characters.

A change that breaks consumers adds ! before the colon. That covers a new wire format, a renamed or removed export, or a new test-vector layout. Its commit body then ends with a BREAKING CHANGE: footer that says what to change.

feat(kzg): add the cell proofs of EIP-7594
fix(rlp)!: reject a length prefix that is not canonical
proof(ssz): prove that the encoding of a container is injective
build: pin ssz-specs to a23a239
docs: add AGENTS.md

CI builds tests/downstream, a separate Lake package that requires EthLib, as a downstream project does. Its file Consumer.lean states the declarations that such projects rely on, and unfolds the definitions whose bodies their proofs read. When it fails, the change has altered that public surface. Either keep the old declaration, statement or exposed body, or update Consumer.lean and mark the change breaking as above.

Bodies

The commit body says why, when the subject cannot.

Write the pull request body for a human who has never seen the change. Its length follows the change.

  • A typo or a dependency bump needs one line, or none.
  • An ordinary fix needs a few sentences.
  • A new module, a wire-format change or a subtle proof needs more. Then explain it the way a good teacher would.

A longer body follows this order:

  1. The problem. What is wrong or missing, and why it matters, in plain words.
  2. The idea. The one insight the change rests on.
  3. One concrete example. Real values traced step by step: bytes, a slot, an epoch, a gas cost. A short text block often says it best.
  4. What reviewers and implementers must know. The case a reviewer could miss, and what consumers must change, if anything.

For example, a body for a wire-format change:

A signature is 1208 bytes, and the order of its three fields is part of the wire format.

The paper writes a signature as (randomizer, chain values, path).
The verifier also needs the randomizer first, to recompute the encoding.
So the encoding now follows that order:

```text
before:  [ 42 chain values: 672 | randomizer: 24 | 32 siblings: 512 ]
after:   [ randomizer: 24 | 42 chain values: 672 | 32 siblings: 512 ]
```

The sizes are unchanged, so a length check cannot catch the old layout.
Every implementation that encodes or decodes signatures must switch.

Rules for every body:

  • Use plain words and short sentences, as Writing describes. Define a term the first time it appears.
  • Use a heading only when the body has several distinct parts.
  • Leave out what the diff already shows: file lists, renamed symbols, the code retold.
  • Do not add checklists, the phrase "this PR" or tables of unchanged values.
  • Link the issue it closes: Closes #22.
  • Stacked pull requests say so: Stacked on #43.

Read the body aloud before you post it. If it sounds like a report, cut it.

Labels

Workflows label issues and pull requests, so you do not need to set these labels yourself.

  • The paths that a pull request changes give its area labels, such as crypto and crypto: keccak. .github/labeler.yml maps the paths to the labels. After each push, the workflow also removes an area label whose paths the pull request no longer changes.
  • The type of a title gives a label such as type: proof, and a ! before the colon gives statement-change. On an issue, the scope also gives the area labels, since an issue changes no paths. On an issue, the older prefixes proofs:, specs:, specs+proofs:, bindings: and meta: also give labels; meta: gives meta, for a tracking issue. .github/workflows/labeler.yml holds the tables of scopes and prefixes. It sets the title labels after the path labels, so that neither overwrites the other.
  • .github/labels.yml defines each label with its color and description. A change to it on master creates or updates labels, and never deletes one.

Other labels, such as leanVM and bug, stay manual.

leanVM work

The leanVM specification is large, and people review it one small pull request at a time. EthLib/Cryptography/LeanVm/README.md records what it covers, its security model and its layout. These rules hold for every leanVM issue and pull request:

  • Each leanVM issue becomes exactly one pull request, which closes it. If the work outgrows the issue, split the issue first.
  • Issues carry the title prefix [leanVM] and the label leanVM.
  • Pull requests carry the label leanVM and a title in the form of Titles, with the scope leanvm: feat(leanvm): ... for definitions, proof(leanvm): ... for theorems, test(leanvm): ... for vectors, docs(leanvm): ... for documentation.
  • Definitions and their theorems land in separate pull requests. A definitions pull request contains no sorry, and its theorems have their own issue.
  • Each pull request needs two approvals: a cryptographer's, for its definitions and statements, and a Lean reviewer's, for its proofs.
  • Automated review agents do not review anything labelled leanVM, unless a person asks them to.
  • The description links the section of the leanVM whitepaper and the leanVM code it was compared with, at the commit that tests/sources.toml pins. Doc comments cite the papers, never leanVM.
  • If EthLib and leanVM disagree, report it on the issue, with the file and line on both sides. Do not change either side to make them agree.

Licence

EthLib's own material is distributed under CC0 1.0 Universal. The legal text is in LICENSE. pyproject.toml declares CC0-1.0 AND MIT AND Apache-2.0 AND Unicode-3.0 for the Python package. It ships the MIT-licensed RLP, hex-prefix and trie test cases from ethereum/tests, and the Apache-licensed test sets from C2SP/wycheproof. The normalization tables derive from Unicode 16.0.0 data under the Unicode License V3. Material from other projects keeps its own terms, as Material from other projects explains.

By submitting a contribution, you agree to make it available under CC0 1.0 Universal. You must have the authority to do so. CC0 covers only rights its affirmer holds, so you cannot dedicate work that is not yours to dedicate.

Copyright notices

EthLib's own material carries no copyright notice in each file. That is a choice of this project. The CC0 FAQ recommends a notice at the top of each source file, but CC0 does not require one.

A file of EthLib's own may still need a notice, for example when it is distributed on its own. That notice names "The EthLib Contributors", not a person or an organisation. Do not add an AI-attribution line to a file header or its copyright notice. The name is a convention for notices. It does not say who holds which rights; the git history records who contributed what.

Material from other projects

Code, data or text taken from another project keeps its own licence and notices. The CC0 terms and the naming convention above do not apply to it.

Identify such material separately: mark where it starts and ends, name its author and give its licence. The CC0 FAQ asks the same for third-party work inside a CC0 work. Do not remove or reword its notice.

Say in the pull request where the material comes from and under which licence. Maintainers then check that the licence allows it to ship with EthLib.