8000 feat: add a C API over the stratum crates by vincenzopalazzo · Pull Request #1 · stratum-mining/sv2-ffi · GitHub
[go: up one dir, main page]

Skip to content

feat: add a C API over the stratum crates - #1

Merged
plebhash merged 2 commits into
stratum-mining:mainfrom
vincenzopalazzo:c-bindings
Nov 27, 2026
Merged

plebhash merged 2 commits into
stratum-mining:mainfrom
vincenzopalazzo:c-bindings

Conversation

@vincenzopalazzo
@vincenzopalazzo vincenzopalazzo commented Nov 25, 2026 •
Copy link
Copy Markdown
Contributor

What

The C API from stratum#2131, first opened as stratum-mining/sv2-uniffi#15 and moved here as suggested in the discussion. A hand-written FFI over the crates released with stratum v1.13.0, with its header generated by cbindgen and committed: libsv2_ffi.a and include/sv2_ffi.h, 40 functions, C11.

  • codec: the Noise handshake, as responder and as initiator, and the encrypted transport, through codec_sv2. A session takes a message record to send (sv2_ffi_noise_encode()) and hands out the record of each message it receives (sv2_ffi_noise_try_decode()), so the caller reads and writes its own socket and never sees a frame header.
  • messages: the 5 common and 21 mining messages as plain C records; parsers_sv2 decides what a frame holds, and the subprotocol crates the message type and channel_msg bit a record goes out with.
  • channels: the server-side extended and standard channels of channels_sv2 and their extranonce allocator; a channel takes each job as the bytes the server sends (PrebuiltJob), hands out the target the crate derives from the hashrate (for OpenMiningChannel.Success and the SetTarget after an UpdateChannel), validates the shares and keeps the share accounting a SubmitShares.Success is built from.

Record shapes

The record fields carry the names of the mining_sv2 13 and common_messages_sv2 10 structs, and the records the names sv2-uniffi uses (Sv2FfiSetNewPrevHashMining, so template distribution's SetNewPrevHash can come later without a rename). Where C has no type for a field, the shape differs from the struct:

  • Option<u32> ntime_start is has_ntime_start + ntime_start (NewMiningJob, NewExtendedMiningJob);
  • Seq0255<U256> is merkle_path_count + merkle_path, the hashes back to back (NewExtendedMiningJob, SetCustomMiningJob);
  • Seq064K<u32> is channel_ids_count + channel_ids, the little endian values (SetGroupChannel).

Not in this PR

  • Records for template distribution, job declaration and the extensions: a well-formed frame of one of those decodes to SV2_FFI_ERR_UNSUPPORTED and the session goes on.
  • The template-driven job path of the channels (on_new_template, on_set_new_prev_hash), custom jobs on a channel (on_set_custom_mining_job), and the job and chain-tip getters.
  • Group channels and client channels.
  • A responder from a static key and a pre-issued certificate: stratum#2497 is merged but not released (noise_sv2 3.0.0), and this repository follows crates.io, so it is its own PR after the release.
  • Prefixes kept reserved under one prev_hash: with channels_sv2 9 a freed channel's extranonce prefix can go to the next channel opened, and accepted shares are remembered per channel, so the same share would be accepted on both. stratum#2515 fixes it in channels_sv2 10; until that is released, the header says to keep a closed channel until the next SetNewPrevHash before freeing it.

Against AGENTS.md and CONTRIBUTING.md

  • The stratum crates come from crates.io (the v1.13.0 releases), no git revision. Cargo.lock is resolved for Rust 1.75.
  • The header is generated with cbindgen 0.29.4, pinned in CI, and build.sh fails when the committed header differs from the sources.
  • The caller owns every buffer it passes, and the only Rust allocations it holds are the objects of the _new() functions; a decoded record points into the frame its session keeps until the next decode, and none of its byte fields is NULL. Every exported function runs under catch_unwind and reports a panic as SV2_FFI_ERR_INTERNAL (NULL from a constructor). tests/capi_test.c calls every function and covers the error paths from C under ASan and UBSan.
  • Threads: each object is used by one thread at a time and may move to another between calls, an allocator and its channels counting as one object; a compile-time check keeps every object Send.
  • No handlers_sv2, buffer_sv2 or framing_sv2 in the API: the frame header stays between codec_sv2 and parsers_sv2.
  • One rule is the binding's own, as a stopgap: a SetupConnection whose protocol byte common_messages_sv2 has no value for still decodes, so a server can answer unsupported-protocol (spec §3.6.1). A stratum issue for the crate to decode the byte itself is on its way; the stopgap goes when it lands.
  • Each exported function has a doc comment, which is what cbindgen puts in the header.

Testing

  • cargo fmt --check and cargo clippy --release --all-targets --locked -- -D warnings on Rust 1.85.
  • CARGO_TERM_COLOR=always SANITIZE=1 ./test.sh, with the workflow's environment, on macOS (arm64) and in the rust:1.85 image (Debian 12, gcc 12.2), with cbindgen 0.29.4 checking the header: 19 Rust tests, then the C test, which calls every exported function, under ASan and UBSan.
  • cargo test --release --locked on Rust 1.75.
  • cargo +nightly miri test --lib under Stacked Borrows and Tree Borrows: the 14 tests Miri can run. The codec tests go through libsecp256k1's C code, and the random-payload test is too slow under Miri.
  • 60 seconds of message_decode and noise_transport and 180 of channel_share on nightly-2026-08-07, the toolchain CI pins, no crash.

The workflow is on main since #2 (the same ci.yml); a run on this PR waits on a maintainer's approval.

Where it runs

An earlier cut of this API, with the frame functions this review removed, is the SV2 server of a DATUM Gateway pooled to OCEAN on mainnet: 2,518 shares accepted and 0 rejected in 13.7 hours, from two Bitaxes on extended channels and a Braiins OS+ machine on a standard channel. That build is on stratum 7b85f90, two PRs before v1.13.0; it has not been repeated on the released crates or on this API yet.

vincenzopalazzo added a commit to vincenzopalazzo/sri-c-ffi that referenced this pull request Nov 25, 2026
Proposed upstream as stratum-mining/sv2-ffi#1; this repository is archived.

Signed-off-by: Vincenzo Palazzo <vincenzopalazzodev@gmail.com>
Comment thread src/messages.rs Resolved
Comment thread src/messages.rs Outdated
Comment on lines +1001 to +1028
let (record, size) = match unsafe { parse(header, payload, len) } {
Ok(v) => v,
// common_messages_sv2 refuses a `protocol` it does not know
// rather than decoding the byte, so the role could not answer
// SetupConnection.Error (unsupported-protocol) as §3.6.1
// requires. Decode the rest with the byte masked and hand
// the real value back.
Err(code)
if code != SV2_SRI_ERR_UNSUPPORTED
&& header.ext_type_without_channel_msg() == 0
&& msg_type == SV2_SRI_MSG_SETUP_CONNECTION
&& len > 0
// SAFETY: `len` > 0 readable bytes at `payload`
&& Protocol::try_from(unsafe { *payload }).is_err() =>
{
// SAFETY: as above, and the slice from `parse` is gone
let raw = unsafe { *payload };
unsafe { *payload = 0 };
// SAFETY: forwarded to the caller
let parsed = unsafe { parse(header, payload, len) };
// SAFETY: the mutable slice of the retry is gone too
unsafe { *payload = raw };
let (mut record, size) = parsed?;
record.u.setup_connection.protocol = raw;
(record, size)
}
Err(code) => return Err(code),
};
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This retry decides something the crates do not: common_messages_sv2 10.0.0 refuses an unknown protocol (setup_connection.rs:386-391) and parsers_sv2 returns BinaryError(ValueIsNotAValidProtocol(n)), while this API returns OK with the raw byte. The spec reason holds (§3.6.1), but per AGENTS.md the fix belongs in stratum, with this binding following the release. Could you open that issue in stratum and link it here, and mark the retry as the stopgap it is? Two smaller things on the same block: the restore at line 1022 is skipped if the second parse() unwinds, so a scope guard would keep the SV2_SRI_ERR_INTERNAL promise; and the guard needs the NULL check from the comment above.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Partially addressed in fbf685f. The retry is marked as the stopgap it is, in decode() and in the commit message, the restore is a drop guard (RestoreProtocol) so an unwind puts the byte back too, and the guard reads payload.first(). The stratum issue is next, I'll link it here once it is open.

10BC8

Comment thread src/messages.rs Resolved
Comment thread src/messages.rs Resolved
Comment thread src/messages.rs Resolved
Comment thread src/channels/server/mod.rs Resolved
Comment thread src/codec.rs Resolved
Comment thread tests/capi_test.c Resolved
Comment thread tests/capi_test.c Resolved
Comment thread .github/workflows/ci.yml Resolved
Comment thread fuzz/Cargo.toml Resolved
Comment thread .cargo/config.toml Resolved
Comment thread src/channels/server/extended.rs Resolved
Comment thread src/channels/mod.rs Resolved
Comment thread src/channels/server/extended.rs Resolved
Comment thread src/keys.rs Resolved
Comment thread README.md Resolved
Comment thread src/channels/server/extended.rs Resolved
Comment thread src/channels/server/standard.rs Resolved
@plebhash
plebhash commented Nov 26, 2026 •
1798
Copy link
Copy Markdown
Member

Thanks for moving this. The inline comments are the line-level things; this is the shape-level answer to the four open questions, measured against what sv2-uniffi exposes today (main 5ffea8d), since the C API was meant to mirror that surface.

Names. Rename to sv2_ffi: crate, libsv2_ffi.a, include/sv2_ffi.h, the sv2_ffi_ prefix and the SV2_FFI_ constants, matching the repo, before anything depends on the header.

Scope. Server side only is fine for the first PR. Two things inside that scope are missing and should either land here or be named in the PR body and README as not there yet:

  • mining_sv2 13.0.0 has 21 message types and the records cover 18. SetCustomMiningJob, .Success and .Error (0x22 to 0x24) are missing; a pool-side server receives SetCustomMiningJob from a JDC and has to answer it. sv2-uniffi has them.
  • Share accounting. Sv2SriChannelOpen.share_batch_size tells the crate how many accepted shares one SubmitShares.Success acknowledges, but nothing lets the caller ask the crate when to send it or with which last_sequence_number, new_submits_accepted_count and new_shares_sum. So a C server keeps its own counters, which is the ShareAccounting the crate already runs on every validated share. sv2-uniffi exposes it (get_share_accounting(): should_acknowledge, get_last_share_sequence_number, get_shares_accepted, get_share_work_sum, ...) and channels_sv2 9.0.0 still has it (server/extended.rs:599). A handful of getters would close this in this PR.

Also missing, fine as follow-ups if listed: the template-driven job path (on_new_template, on_set_new_prev_hash, which the crate still has next to on_prebuilt_job), the job and chain-tip getters, group and client channels.

Record shapes. The names are right. Two shape points:

  • Sv2SriSetNewPrevHash / SV2_SRI_MSG_SET_NEW_PREV_HASH is the mining one. When template distribution arrives there is a second SetNewPrevHash, and a header rename is a breaking change, so name it Sv2SriSetNewPrevHashMining now, as sv2-uniffi (SetNewPrevHashMining) and the crate's own constant (MESSAGE_TYPE_MINING_SET_NEW_PREV_HASH) do.
  • The PR body should also mention the two shape changes beyond has_ntime_start: Seq0255<U256> became merkle_path_count + merkle_path, and Seq064K<u32> became channel_ids_count + channel_ids.

The 6 byte frame header (your question from the sv2-uniffi PR). In sv2-uniffi the transport hands out whole messages: Sv2Encoder::encode(message) gives wire bytes, Sv2Decoder::buffer_size() + try_decode(bytes) give a message, and the application reads its own socket there too without ever seeing a header. framing_sv2 stays inside, which is where the API boundary on stratum#2131 put it. Here the caller decodes the header on every message, so Sv2SriFrameHeader, sv2_sri_frame_header_decode/encode, sv2_sri_msg_has_channel_bit, SV2_SRI_FRAME_HEADER_SIZE and SV2_SRI_CHANNEL_MSG_BIT are all public. I'd rather have one sv2_sri_noise_encode(n, const Sv2SriMessage *, out, cap) and one sv2_sri_noise_try_decode(n, in, in_len, consumed, Sv2SriMessage *) (NEED_MORE as today), with the frame functions gone; the decoded record's byte fields then point into the session's frame buffer, valid until the next decode, which is the same contract as today's "valid as long as the payload is". It also removes the three places where this crate currently decides instead of parsers_sv2 (the channel-bit check, the TRAILING rule, the hand-written bit table). If plaintext SV2 without Noise is something you want to keep possible, say so; that is a reason to keep message encode/decode on plaintext frames, not a reason to expose the header. This is the one shape decision that gets more expensive with every dependant, so let's settle it in this PR rather than after.

The responder's certificate. stratum#2497 merged on main (8228904) and is not released yet: noise_sv2 3.0.0 removes from_authority_kp, without_pk and step_1_with_now_rng, which are what sv2_sri_noise_responder_new, sv2_sri_noise_initiator_new(NULL) and responder_step1's now sit on. Per AGENTS.md this crate follows crates.io, so that is its own PR after the release. One thing worth doing now: drop the NULL initiator (and sv2_sri_noise_is_authenticated with it). sv2-uniffi's new_initiator always pinned, 3.0.0 removes the unauthenticated path, and taking it out now is one fewer breaking header change later.

Two utilities. sv2_sri_random and sv2_sri_sha256 have no SV2 content and the C side already links a crypto library for both; dropping them keeps the header to what only SRI provides. The four sv2_sri_authority_* functions are SRI-specific (key-utils' base58check format) and belong.

@vincenzopalazzo
Copy link
Copy Markdown
Contributor Author

Thanks, all of it is in the force-push: the review is folded into the three commits as CONTRIBUTING asks (fbf685f feat, 01a395e test, 4cfd482 ci). Point by point:

Names. sv2_ffi everywhere: the crate, libsv2_ffi.a, include/sv2_ffi.h, sv2_ffi.pc, the sv2_ffi_ prefix, the SV2_FFI_ constants and the Sv2Ffi records.

Scope.

  • SetCustomMiningJob, .Success and .Error have records now, so the mining records are 21 of 21.
  • Share accounting: Sv2FfiShareAccounting and sv2_ffi_{extended,standard}_channel_share_accounting(). I went with one record filled in one call rather than a getter per field, since a C server reads it after every share anyway: should_acknowledge, last_share_sequence_number, last_batch_accepted, last_batch_work_sum (what the Success carries), plus share_batch_size, shares_accepted, share_work_sum, shares_rejected, best_diff, blocks_found. The doc also says to send a Success after a block whatever should_acknowledge says, since the crate calls mark_batch_acknowledged() there. The C test and channel_share fuzz target check it counts exactly the accepted shares.
  • The follow-ups are listed in the PR body and the README: the template path, custom jobs on a channel (on_set_custom_mining_job), the job and chain-tip getters, group and client channels.

Record shapes. Sv2FfiSetNewPrevHashMining / SV2_FFI_MSG_SET_NEW_PREV_HASH_MINING, and the PR body lists the three shape changes (has_ntime_start, merkle_path_count + merkle_path, channel_ids_count + channel_ids).

The frame header. Done as you sketched, Noise only: nothing here needs plaintext SV2 (DATUM always runs Noise), so I did not keep message encode/decode public.

  • sv2_ffi_noise_encode(n, m, out, cap) and sv2_ffi_noise_try_decode(n, in, in_len, consumed, out), with NEED_MORE as before, plus sv2_ffi_noise_encoded_size(m) so a caller can size out (it serializes the record, so it agrees with encode on what encode refuses; the fuzzer caught a negative hash rate being sized and then refused).
  • A decoded record points into the frame the session keeps, valid until the next try_decode or the free.
  • Gone: Sv2SriFrameHeader, frame_header_decode/encode, msg_has_channel_bit, FRAME_HEADER_SIZE, CHANNEL_MSG_BIT, and with them message_encode/decode, encrypt_frame/read_frame, the two encrypted size helpers and the AEAD/encrypted-header/chunk constants. The channel-bit check and the TRAILING rule went too (SV2_FFI_ERR_TRAILING is out of the header), and what follows a message is left to parsers_sv2.
  • Two behaviours worth a look. A frame that decrypts but holds a message this API returns no record for, or one that does not decode, gives SV2_FFI_ERR_UNSUPPORTED / _INVALID / _TRUNCATED with the session still in transport mode, so a server can skip it and go on. And the old out_cap bound on an incoming frame went with the output buffer: the decoder takes a frame a chunk at a time, so memory follows what a peer actually sends, and a caller that wants a cap counts consumed across NEED_MORE. Happy to add a per-session limit instead if you think it belongs in the API.
  • The fuzz targets that need a peer sending frames the API would never encode now use a codec_sv2 initiator as the miner.

The responder's certificate. Agreed, its own PR after noise_sv2 3.0.0 is out. The NULL initiator is gone (sv2_ffi_noise_initiator_new(NULL) returns NULL) and sv2_ffi_noise_is_authenticated with it.

Two utilities. sv2_ffi_random and sv2_ffi_sha256 are gone; the four authority functions stay.

The unknown-protocol retry stays, marked as a stopgap, until the stratum issue lands (in its thread). Checked with fmt and clippy on 1.85, cargo test on 1.75, SANITIZE=1 ./test.sh on macOS and Ubuntu 24.04, and 60 to 90 seconds of each fuzz target.

@plebhash
Copy link
Copy Markdown
Member

Thanks for the fast turnaround; I'll go through 4cfd482 against the point-by-point above.

One coordination note, since sv2.cc #57 landed on the same day: #57's first commit imports sri-capi from this PR's previous head (a8afa57), so sv2.cc now carries the sv2_sri_* names and the frame-level API (frame_header_*, message_encode/decode, noise_encrypt_frame/noise_read_frame, msg_has_channel_bit, random, sha256, noise_is_authenticated) that this push removed. Its shim calls 14 functions that no longer exist here. That's fine for #57 itself (sv2.cc builds its own copy), but I want us to agree on direction so the two don't drift:

  • sv2-ffi is the source of truth. sv2.cc re-syncs from here after this merges and moves its shim to sv2_ffi_noise_encode / sv2_ffi_noise_try_decode, rather than evolving its copy independently.
  • The certificate API in #57 (certificate_sign/certificate_verify, responder_new(static_sk, certificate), initiator_new(authority_pk)) is exactly the follow-up you deferred here. When noise_sv2 3.0.0 is on crates.io, that lands as its own PR in the sv2_ffi dialect, on top of the Noise-only surface.
  • The review fixes you made here (hash checked before validate_share, extranonce-size error mapping, xonly_of erasure, share accounting) aren't in #57's copy; they come back to sv2.cc through that re-sync, not by patching twice.

I've left the same note on #57 so both threads point at each other.

Separately: CI still shows no runs on this PR after the push, and main has no workflow yet. I'll look at why from the repo side; if it's the fork/first-PR gate, getting ci.yml onto main first will unblock it.

plebhash added a commit that referenced this pull request Nov 26, 2026
Workflow from #1, landed on main first so it is registered and runs on that PR.
@plebhash
Copy link
Copy Markdown
Member

CI is now registered on main (#2, merged as 078d035): it's your ci.yml from 4cfd482, byte for byte, landed first because a workflow that exists only on a fork branch never ran here. The run on main itself is red for the obvious reason (no Cargo.toml there yet); this PR is the first one that can go green.

Nothing has triggered on this PR yet, since checks only fire on a push. Rebase onto main: your ci: commit becomes empty and can be dropped, the other two carry over unchanged. If the run then sits on "approval required" (first contribution from a fork), ping me and I'll approve it. Once it's green I'll add "Build and test" and "Rust 1.75" to the required checks and finish the review of the new head.

@vincenzopalazzo
Copy link
Copy Markdown
Contributor Author

Rebased onto main (078d035). The ci: commit dropped out as empty, since ci.yml on main is the same blob, and the other two carried over unchanged: a72211a feat and 79b340d test, with the tree identical to 4cfd482.

The run is waiting on approval (first contribution from a fork): https://github.com/stratum-mining/sv2-ffi/actions/runs/45972561205. @plebhash could you approve it?

On the coordination note: agreed on all three, same answer as on vincenzopalazzo/sv2.cc#57 (https://github.com/vincenzopalazzo/sv2.cc/pull/57#issuecomment-7198285359). sv2-ffi is the source of truth: sv2.cc re-syncs sri-capi from here once this merges and moves its shim to sv2_ffi_noise_encode / sv2_ffi_noise_try_decode, the review fixes come back with that re-sync, and the certificate API comes here as its own PR in the sv2_ffi dialect once noise_sv2 3.0.0 is on crates.io.

@GitGab19
Copy link
Copy Markdown
Member

The run is waiting on approval (first contribution from a fork): https://github.com/stratum-mining/sv2-ffi/actions/runs/45972561205. @plebhash could you approve it?

Just approved, CI is now running

@vincenzopalazzo
Copy link
Copy Markdown
Contributor Author

Thanks @GitGab19. The C link failed on -lc\x1b[0m: build.sh reads rustc's native-static-libs note from cargo's stderr, and with the workflow's CARGO_TERM_COLOR: always the note ends in a colour reset that stuck to the last flag in sv2_ffi.pc. Nothing forced colour in my local runs, so it never showed there.

Fixed in e2e3ba0 (folded into the feat commit) by running that cargo rustc with --color never. Checked with CARGO_TERM_COLOR=always SANITIZE=1 ./test.sh on Linux (rust 1.85, plus fmt and clippy) and macOS. 6cfdf5e, the fuzz commit, is unchanged. The new run is waiting on approval again: https://github.com/stratum-mining/sv2-ffi/actions/runs/46009420432

A C program has no SRI binding to use today: the C++ bindings of
sv2-uniffi need C++20, and UniFFI has no C target. The first such
program is DATUM Gateway, whose SV2 server is plain C.

This is a hand-written C API with its header generated by cbindgen,
libsv2_ffi.a and include/sv2_ffi.h:

1. codec: one Noise session per connection through codec_sv2. It
   takes a message record to send and hands out the record of each
   message it receives, so a caller reads and writes its own socket
   and never sees a frame header.
2. messages: the 5 common and 21 mining messages as plain C records,
   with parsers_sv2 deciding what a frame holds. The record fields
   carry the names of the mining_sv2 13 structs (max_target, target,
   ntime_start), and the records the names sv2-uniffi uses
   (SetNewPrevHashMining).
3. channels: the server channels of channels_sv2, fed with
   PrebuiltJob, with their share accounting.

The caller owns every buffer it passes, so no Rust lifetime reaches C,
and no panic crosses the boundary: each function returns an error code
instead.

One rule is the binding's own, as a stopgap: a SetupConnection whose
protocol byte common_messages_sv2 has no value for still decodes, so a
server can answer it with unsupported-protocol as the spec requires.
It goes once the crate decodes the byte itself.

It depends on the crates released with stratum v1.13.0, and Cargo.lock
is resolved for Rust 1.75 like the stratum crates.

test.sh runs the crate's tests and tests/capi_test.c, a C program that
links only the library and covers the error paths (SANITIZE=1 for ASan
and UBSan).

Link: stratum-mining/stratum#2131
Signed-off-by: Vincenzo Palazzo <vincenzopalazzodev@gmail.com>
Three targets that call the C functions the way a C caller does:
message_decode (any header and payload, then a re-encode round trip),
noise_transport (any act 1, then streams and frames from a real
initiator read back in pieces) and channel_share (targets,
UpdateChannel, jobs, SetNewPrevHash and shares in any order, on both
channel types, with the share accounting). The initiator of the first
two is codec_sv2's 
10BC8
own, so it can send frames the C API would never
encode.

A panic is a crash there even though the API catches panics:
libfuzzer-sys installs a panic hook that aborts the process before
unwinding reaches catch_unwind. fuzz/Cargo.lock is committed, so a run
builds what the last one did.

Signed-off-by: Vincenzo Palazzo <vincenzopalazzodev@gmail.com>
@vincenzopalazzo
Copy link
Copy Markdown
Contributor Author

I went over the whole PR again with production use in mind: a fresh read of the boundary, the records and the channels against the crates' sources, plus Miri. The fixes are folded into the two commits, c3b6d55 feat and af29207 test. In order of what a C caller would notice:

API

  • sv2_ffi_extended_channel_target() and sv2_ffi_standard_channel_target() bind the crate's get_target(), so there are 40 functions now. _new and _update let the crate derive the channel's target from the hashrate, and C had no way to read it for OpenMiningChannel.Success or for the SetTarget after an UpdateChannel. A caller that trusted _update's doc and skipped _set_target checked shares against a target the miner was never told about.
  • sv2_ffi_noise_try_decode() writes *consumed before it checks the other arguments, so every return sets it. Before, a NULL out returned INVALID with *consumed untouched, which the error table reads as "a frame was used". The table also says now that STATE before the handshake leaves the session as it was.
  • A decoded empty merkle path points at a static byte instead of NULL, so no byte field of a decoded record is NULL: memcpy(dst, NULL, 0) is UB in C, and UBSan flags it.

Memory model
cargo miri test found two Stacked Borrows violations in messages.rs, both in code only Rust reads back (the re-encode in the tests and the fuzzer):

  • The SetupConnection stopgap put the protocol byte back through a pointer that the &mut reborrow passed into parse() had already invalidated.
  • A decoded merkle path's pointer came from the first hash's borrow, which covers 32 bytes, while the view covers all of them.

decode() and parse() now derive every pointer into the payload from one raw pointer. The 14 tests Miri can run now pass under both Stacked and Tree Borrows. The codec tests go through libsecp256k1's C code, which Miri cannot run, and the random-payload test is too slow under it.

Header docs

  • A Threads section: each object is used by one thread at a time and may move between threads between calls, with an allocator and its channels counting as one object. A compile-time check keeps every object Send.
  • Sv2FfiBytes said decoded fields point into "the payload they were given", which was true of the frame API. They point into the session's frame, freed by the next try_decode.
  • *_validate_share: *coinbase_len is the full length even when the coinbase does not fit; the doc said 0, which reads as "nothing to copy" and invites an over-read. A share sent again is a duplicate, so the doc now says to size the buffer from the job (prefix + suffix + 32).
  • *_set_target: a future job activated after the call takes the new target.
  • share_batch_size is at least 1, since with 0 the crate never asks for an acknowledgement. A user_identity that is not UTF-8 is SV2_FFI_ERR_INVALID, and it comes from the miner. An extranonce over 32 bytes is refused before the crate sees the share, so it is not counted. A channel opened with no_version_rolling sends version_rolling_allowed false.
  • *_channel_free: keep a closed channel until the next SetNewPrevHash. With channels_sv2 9, a freed prefix can go to the next channel under the same prev_hash, and accepted shares are remembered per channel, so the same share is accepted twice. That is what channels_sv2: unpredictable extranonce prefixes, not reused under one prev_hash stratum#2515 fixes in channels_sv2 10, and this repository follows it once it is released.
  • The pkg-config Description no longer says prototype.

Tests

  • tests/capi_test.c now calls every exported function. Before, it called none of the standard channel's, nor _update. It covers the target getters, a block with a coinbase buffer too short and one that fits, stale and duplicate shares, the exact rejected count, *consumed on every decode error, and an empty decoded merkle path.
  • The channel_share fuzz target takes the coinbase buffer size from the input, checks that a short one is left untouched, and reads the channel's target.

Checked

  • fmt, and clippy with -D warnings on 1.85.
  • CARGO_TERM_COLOR=always SANITIZE=1 ./test.sh on macOS and in the rust:1.85 image, with cbindgen 0.29.4 checking the header.
  • cargo test on 1.75.
  • 60 s of each fuzz target on nightly-2026-08-07.
  • cargo +nightly miri test --lib under Stacked Borrows and Tree Borrows.
  • The fuzzer caught one more case after the doc changes: the extranonce-size refusal returned before writing *coinbase_len. *_validate_share now clears it first, like *consumed.

Two things left:

  • AGENTS.md on main still says "a decoder reads a caller buffer and points its byte fields into it". With the Noise-only API, decoded fields point into the session's frame. I can send a one-line PR for it, or leave it to you.
  • The retry thread stays open until the stratum issue is filed.

Thanks for approving the last run: with the colour fix, https://github.com/stratum-mining/sv2-ffi/actions/runs/46009420432 went green. The new one is waiting on approval again: https://github.com/stratum-mining/sv2-ffi/actions/runs/46016811194

@plebhash plebhash left a comment
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-reviewed 6cfdf5e against the point-by-point and the inline threads, with the tree checked locally (CARGO_TERM_COLOR=always SANITIZE=1 ./test.sh: 19 tests and the C test under ASan/UBSan pass, header regenerates identical with cbindgen 0.29.4). Everything the replies say is fixed is fixed in the code: the 21 mining records match mining_sv2 13.0.0's list field for field, Sv2FfiShareAccounting is read straight from the crate's ShareAccounting and its should_acknowledge / block semantics match channels_sv2 9.0.0 (the batch resets on the next accepted share, mark_batch_acknowledged() on a block), hash is checked before validate_share() in both channels, the NULL initiator and the frame API are gone, the cert_validity_secs 0 case is forwarded, and the fuzz job is pinned with a committed lock.

On the frame bound: no per-session limit here. What a frame may hold is the crate's decision, and a caller that wants a tighter bound has consumed across NEED_MORE, as the doc says. Adding a cap in the binding would be exactly the kind of rule AGENTS.md keeps out of this repository.

Four small things, none blocking; the first I'd like settled before merge, the rest can ride along in the same commits or a follow-up:

  1. The stratum issue for the unknown-protocol stopgap is not open yet; the PR body says it is on its way. Please file it and link it from the decode() comment and the body, so the stopgap has an exit.
  2. src/codec.rs:15 cites stratum#2437 as "the upstream request"; the README cites #2497 (merged, unreleased). Point both at #2497.
  3. Cargo.lock resolves codec_sv2 to 8.1.0, while the v1.13.0 tag ships 8.0.0; the body says "the crates released with v1.13.0". Either say 8.1.0, or pin =8.0.0 if that is what you mean.
  4. The error codes skip -6 and -8 (the removed ones). Since the header is the API and nothing depends on it yet, this is the last free moment to close the gaps.

Approving.

@plebhash
Copy link
Copy Markdown
Member

The approval above landed on af29207 a few minutes after your push, so for the record it covers that head too. I went over the 6cfdf5e..af29207 diff, ran CARGO_TERM_COLOR=always SANITIZE=1 ./test.sh (green), and cargo +nightly miri test --lib on the same 14 tests under Stacked Borrows (green, 1.99.0-nightly 2026-08-02). The target getters, the *consumed / *coinbase_len ordering, the non-NULL decoded fields and the Send check all do what the comment says.

The four points in the approval still stand as written, since the push predates them. One more from the new text: the _channel_free docs say stratum#2515 is "not released yet"; it is an open PR, not merged, so "open" until it lands.

AGENTS.md is mine to fix; I'll take care of it.

@plebhash
plebhash merged commit f093a5c into stratum-mining:main Nov 27, 2026
3 checks passed
plebhash added a commit to plebhash/sv2-ffi that referenced this pull request Nov 27, 2026
AGENTS.md described the decoder as reading a caller buffer, which was the frame API; with the Noise-only API of stratum-mining#1 a decoded record points into the frame the session keeps.
plebhash added a commit that referenced this pull request Nov 27, 2026
AGENTS.md described the decoder as reading a caller buffer, which was the frame API; with the Noise-only API of #1 a decoded record points into the frame the session keeps.
@plebhash
plebhash commented Nov 27, 2026 •
Copy link
Copy Markdown
Member

Filed as stratum-mining/stratum#2519. The follow-ups from this review are tracked here as #4 to #8; #7 is the stopgap's removal and #8 the certificate port.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants

0