Proving a rewrite against the C original
by Jon Reyna
A filter generator for BGP routers is the wrong place to guess whether a rewrite agrees with the original. I compiled C bgpq3 and ran it beside Go bgpsieve on 200 deterministic cases and 6 live queries. Along the way, the oracle caught a bug in the C code.
I.Why an oracle, not unit tests§
Network engineers use bgpq3, written and maintained by Alexandre Snarskii (2007–2026), to turn Internet Routing Registry (IRR) records into router prefix lists and AS-path filters.1
A bad filter on a border router drops customer traffic or leaks a full table to a peer, so nobody swaps out a filter generator on faith.
When I rewrote bgpq3 in Go as bgpsieve
to get a standard-library Go package, concurrency safety, and an HTTP service (bgpsieved), unit tests alone weren’t enough. Unit tests check what I
think the spec says. For a drop-in command covering nine router formats and 39 short flags, the spec is 4,756 lines of C in
bgpq3 (v0.1.38), four files of which (bgpq3.c, bgpq_expander.c,
sx_prefix.c, and bgpq3_printer.c) carry almost all of the behavior.
The cleanest proof is differential testing: compile the real C binary, put both commands in front of the same mock IRR server, feed them identical flags and fixtures, and fail if stdout or the exit status differs by a single byte.
II.What exact aggregation has to preserve§
The hardest part of bgpq3 to match isn’t the IRR wire protocol (!i, !g,
!6 over TCP port 43) or the vendor syntax.2
It’s exact prefix-list aggregation (-A), which shrinks a filter without changing which routes the router accepts.
Write for the set of IP addresses covered by a prefix of length , and write for a prefix-list entry that matches any prefix with and . When two sibling prefixes and of length share a parent of length , their address sets partition :
Because of (1), if a router’s filter permits both
and
with the same bounds ,
then replacing both entries with
matches the exact same set of routes. If itself was also in the input (and ), the combined range widens to
.
What if is an exact entry and its children carry a disjoint range
with ?
Then stays exact, and the merged range attaches to as a secondary
son entry so the printer emits both lines without inventing any intermediate lengths.
Given the root node of a binary Patricia radix tree of prefixes, this post-order pass compacts sibling entries into equivalent prefix-length ranges.
- A1.[Recurse.]
If has a left child, run Algorithm A on . If has a right child, run Algorithm A on .
- A2.[Check siblings.]
Let . If either child is missing, or if either child does not have prefix length , return.
- A3.[Merge exact children.]
If both children are active exact prefixes (neither glue nor aggregate), mark both children as glue and set to an aggregate with upper bound . Set ’s lower bound to if was glue, or to if was already active. If both children also carry matching
sonranges, promote one copy to . - A4.[Merge matching ranges.]
Otherwise, if both children (or one child and the other’s
▮son) are active aggregates with identical bounds , mark both as glue. If is glue, copy onto ; else if , promote to ; otherwise attach as .
In Go (radix/tree_aggregate.go), step A2 and the branch dispatch fit in one short function:
func (t *Tree) aggregateNode(n *node) {
if n.left != nil {
t.aggregateNode(n.left)
}
if n.right != nil {
t.aggregateNode(n.right)
}
if n.left == nil || n.right == nil {
return
}
nBits := uint8(n.prefix.Bits())
childBits := int(nBits) + 1
l, r := n.left, n.right
if l.prefix.Bits() != childBits ||
r.prefix.Bits() != childBits {
return
}
// Merge exact siblings, matching ranges, or son chains.
t.mergeSiblings(n, l, r, nBits)
}
The second aggregation flag, -H (hyper-aggregation), runs Algorithm A first and then makes a top-down pass that keeps only the highest active supernet on each path and discards every more-specific descendant. Unlike
-A, -H is intentionally lossy: it shrinks the list further by permitting sub-prefixes that were not registered individually.
III.Wiring the C binary into go test§
The differential suite lives in internal/oracle/diff_test.go and runs on every pull request in CI. A small build script compiles the pinned C
bgpq3 commit (v0.1.38) into .cache/bin/bgpq3, and TestCOracleDifferentialSuite
builds cmd/bgpsieve into a temporary directory and starts an in-process mock IRRd server (irrdtest.Server).
Both binaries talk to that same loopback TCP port with -h 127.0.0.1:<port>. The mock fixtures cover nested AS-sets, circular references (AS-CYC-A
and AS-CYC-B), EXCEPT stoplists, -L depth caps, multi-source shadowing (RIPE
vs. RADB), 32-bit and special ASNs (AS23456, AS64512), route-sets with RPSL range operators (^+,
^-, ^25-26), and empty sets.
cOut, cErr, cCode := runCLI(t, cBin, args, tc.env)
goOut, goErr, goCode := runCLI(t, goBin, args, tc.env)
if tc.expectFail {
if cCode <= 0 || goCode != 1 {
t.Fatalf("exit mismatch: c=%d go=%d", cCode, goCode)
}
return
}
if tc.jsonEqual {
assertJSONSemanticallyEqual(t, cOut, goOut)
return
}
if goOut != cOut {
t.Fatalf("mismatch for %v:\nC:\n%sGo:\n%s",
args, cOut, goOut)
}
Table 1 summarizes the suite as it runs on every commit, alongside the polite live smoke suite (test/integration/live_irrd_test.go) that runs six small queries against
rr.ntt.net:43.
Table 1. Differential checks between C bgpq3 (v0.1.38) and Go bgpsieve.
| Suite | Cases | Comparison | Network |
|---|---|---|---|
| Router formats & flags | 171 | Exact byte-for-byte stdout | 103 via mock IRRd |
JSON output (-j) |
10 | Parsed JSON deep equality | Mock IRRd / static |
| Invalid flag combinations | 19 | Both exit non-zero | None |
Live IRRd smoke (rr.ntt.net) |
6 | Exact byte-for-byte stdout | Live TCP 43 |
IV.When the oracle itself is wrong§
A differential test only tells you that two programs disagree; it doesn’t tell you which one is right. Early on, almost every diff pointed to a subtle detail I had missed in Go: an extra trailing space in a vendor’s empty-list fallback, how
-a and -f interact depending on flag order, or the exact regex grouping of Cisco and JunOS AS-path filters.
Eight times, though, reading the C source behind a diff showed a real bug in bgpq3 v0.1.38. Rather than reproduce crashes or silent data loss, I documented and tested those eight divergences separately in
TestIntentionalCBugFixes.
One of them turned up only because the oracle tested a combination I hadn’t thought to audit by hand. In mixed address-family mode (-x, supported on JunOS, JSON, and
-F), bgpq3 passed maxlen = 0 to sx_prefix_range_parse
when parsing IPv6 prefix ranges such as 2001:db8:2::/48^49-49. The parser clamped the upper bound to zero and silently dropped the route from the generated filter.
The other seven were just as concrete: an /65535 typo in the ASN table that mis-indexed
AS65535; -F reading before the format pointer on a trailing \n; an uninitialized maximum length on single-length ranges like
^25; Cisco and Huawei -f 0 emitting deny .* for a single ASN; Cisco extended ACLs printing
host 0.0.0.0 instead of host 255.255.255.255 for a /32; leading-zero IPv4 octets from RADB being parsed as octal (010.0.0.0/24
turning into 8.0.0.0/24); and Nokia classic -NG omitting its closing exit
and commit.
V.What the oracle doesn’t prove§
Matching a single-shot CLI proves the core math, expansion, and formatting, and it let me add features
bgpq3 never had (bogon stripping, prefix caps, Go templates, and a public HTTP demo at bgpsieve.jonreyna.dev) without drifting from the baseline.3
It does not prove that a long-lived HTTP server survives hostile traffic. Putting bgpsieved
on the internet took a separate round of fuzzing, race testing, and a security audit that caught memory-exhaustion paths, router-config injection in
name and match, and per-IP rate-limit edge cases that a CLI tool never faces. The oracle gives you a floor for correctness; everything above the CLI still has to earn its keep on its own.
Exercises
- 1.
Why does the oracle compare
-jJSON output by unmarshaling both documents instead of checkinggoOut == cOut, while every router-config vendor is compared byte for byte? - ▸2.
Prove that Algorithm A preserves the exact set of permitted prefixes, and give a two-prefix counterexample showing that hyper-aggregation (
-H) does not. - 3.
Suppose you add a new vendor formatter or flag to a drop-in rewrite and generate your differential test cases automatically. What failure mode does a blind “record C’s stdout as golden” harness miss, and how does the
RS-MIXED-V6RANGEcase illustrate it?
Answers to exercises
- 1.
JSON allows arbitrary insignificant whitespace and key ordering, so two encoders can emit different bytes for the same data structure;
reflect.DeepEqualon decoded values tests semantic equality without coupling the Go encoder to C’s formatting quirks. Router configs, by contrast, are often diffed line by line in GitOps pipelines or Ansible checks, so stray spaces or blank lines cause spurious config churn. - 2.
Each step in Algorithm A merges only when two siblings of length cover both halves of their parent of length and carry the exact same length interval (or both are exact prefixes, which is ). By (1), a route has with if and only if or with the same bounds (or when itself was active and the lower bound drops to ). For
-H, take the two prefixes192.0.2.0/24and192.0.2.0/25:-Akeeps them exact, whereas-Hcollapses them to192.0.2.0/24alone, dropping the/25entry (or, with192.0.2.0/25and192.0.2.128/25,-Hemits192.0.2.0/24which permits/24even though only the two/25s were in the input). - 3.
If you treat the C binary as infallible and auto-bless its output as ground truth, you faithfully clone its silent bugs too. In
RS-MIXED-V6RANGE, Cbgpq3 -xreturned exit code 0 and valid JunOS config, simply omitting2001:db8:2::/48^49-49. Catching that requires both independent assertions on expected prefixes and reading the C source whenever a diff appears.
-
Alexandre Snarskii,
bgpq3(v0.1.38), BSD 2-Clause, at github.com/snar/bgpq3. ↩ -
IRRd’s persistent TCP mode starts with
!!, selects sources with!s, expands AS-sets with!i<set>,1, and fetches IPv4 and IPv6 routes with!g<as>and!6<as>. ↩ -
The public demo at bgpsieve.jonreyna.dev runs
bgpsievedon a five-node Raspberry Pi k3s cluster managed with Flux, behind a Cloudflare Tunnel. ↩