Repository navigation
feat: add a C API over the stratum crates - #1
Conversation
Proposed upstream as stratum-mining/sv2-ffi#1; this repository is archived. Signed-off-by: Vincenzo Palazzo <vincenzopalazzodev@gmail.com>
| 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), | ||
| }; |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
|
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 Names. Rename to 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:
Also missing, fine as follow-ups if listed: the template-driven job path ( Record shapes. The names are right. Two shape points:
The 6 byte frame header (your question from the sv2-uniffi PR). In sv2-uniffi the transport hands out whole messages: The responder's certificate. stratum#2497 merged on Two utilities. |
a8afa57 to
4cfd482
Compare
|
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. Scope.
Record shapes. 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.
The responder's certificate. Agreed, its own PR after noise_sv2 3.0.0 is out. The NULL initiator is gone ( Two utilities. 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, |
|
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
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 |
Workflow from #1, landed on main first so it is registered and runs on that PR.
|
CI is now registered on Nothing has triggered on this PR yet, since checks only fire on a push. Rebase onto |
4cfd482 to
79b340d
Compare
|
Rebased onto 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 |
Just approved, CI is now running |
79b340d to
6cfdf5e
Compare
|
Thanks @GitGab19. The C link failed on Fixed in e2e3ba0 (folded into the feat commit) by running that |
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>
6cfdf5e to
af29207
Compare
|
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
Memory model
Header docs
Tests
Checked
Two things left:
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 |
There was a problem hiding this comment.
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:
- 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. src/codec.rs:15cites stratum#2437 as "the upstream request"; the README cites #2497 (merged, unreleased). Point both at #2497.Cargo.lockresolvescodec_sv2to 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.0if that is what you mean.- 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.
|
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 The four points in the approval still stand as written, since the push predates them. One more from the new text: the AGENTS.md is mine to fix; I'll take care of it. |
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.
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.
|
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. |
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.aandinclude/sv2_ffi.h, 40 functions, C11.codec: the Noise handshake, as responder and as initiator, and the encrypted transport, throughcodec_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_sv2decides 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 ofchannels_sv2and 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_sv213 andcommon_messages_sv210 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_startishas_ntime_start+ntime_start(NewMiningJob, NewExtendedMiningJob);Seq0255<U256>ismerkle_path_count+Seq064K<u32>ischannel_ids_count+channel_ids, the little endian values (SetGroupChannel).Not in this PR
SV2_FFI_ERR_UNSUPPORTEDand the session goes on.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.prev_hash: withchannels_sv29 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 inchannels_sv210; 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
stratumcrates come from crates.io (the v1.13.0 releases), no git revision.Cargo.lockis resolved for Rust 1.75.build.shfails when the committed header differs from the sources._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 undercatch_unwindand reports a panic asSV2_FFI_ERR_INTERNAL(NULL from a constructor).tests/capi_test.ccalls every function and covers the error paths from C under ASan and UBSan.Send.handlers_sv2,buffer_sv2orframing_sv2in the API: the frame header stays betweencodec_sv2andparsers_sv2.common_messages_sv2has no value for still decodes, so a server can answerunsupported-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.Testing
cargo fmt --checkandcargo clippy --release --all-targets --locked -- -D warningson Rust 1.85.CARGO_TERM_COLOR=always SANITIZE=1 ./test.sh, with the workflow's environment, on macOS (arm64) and in therust:1.85image (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 --lockedon Rust 1.75.cargo +nightly miri test --libunder 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.message_decodeandnoise_transportand 180 ofchannel_shareonnightly-2026-08-07, the toolchain CI pins, no crash.The workflow is on
mainsince #2 (the sameci.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.