C bindings to the Stratum V2 Reference Implementation (SRI).
A C API over the SRI crates, written by hand as a raw FFI with its header generated by cbindgen, for programs that speak Stratum V2 with SRI's code deciding what the protocol allows. It is meant to cover the Noise transport (codec_sv2), the subprotocol messages (common_messages_sv2, mining_sv2, job_declaration_sv2, template_distribution_sv2) and the mining channels (channels_sv2); what it covers today is below.
Bindings for languages that UniFFI supports (Python, C++) live in sv2-uniffi.
A static library and a header, libsv2_ffi.a and include/sv2_ffi.h, for the pool side of a Stratum V2 server:
- the Noise handshake, as responder and as initiator, and the encrypted transport, which takes and hands out whole messages;
- the 5 common and 21 mining messages as plain C records;
- the server-side extended and standard channels of
channels_sv2, fed with prebuilt jobs, with their extranonce allocator and their share accounting.
Not there yet:
- records for template distribution, job declaration and the extensions: a well-formed frame of one of those decodes to
SV2_FFI_ERR_UNSUPPORTED; - 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 built from a static key and a certificate issued ahead of time, which comes with
noise_sv23.0.0 (stratum#2497, not released yet).
| Module | What it is | SRI code underneath |
|---|---|---|
src/codec.rs |
One Noise session per connection: the handshake as responder (and as initiator, for tests and clients) and the encrypted transport, from message record to wire bytes and back | codec_sv2 (Handshake, NoiseEncoder, NoiseDecoder) over noise_sv2 |
src/messages.rs |
The common and mining messages as plain C records, and their conversions to and from the crates' structs | parsers_sv2 decides what a frame holds; the structs of common_messages_sv2 and mining_sv2, which assign each message its type and channel_msg bit |
src/keys.rs |
The authority key and its base58check text form | secp256k1, key-utils |
src/channels/ |
Server channels: an extranonce allocator, extended and standard channels that take each job as the bytes the server sends, validate the shares and keep the share accounting | channels_sv2 (ExtranonceAllocator, ExtendedChannel, StandardChannel, PrebuiltJob, ShareAccounting) |
include/sv2_ffi.h |
The header, generated by cbindgen and committed |
The record field names are those of the crates' message structs (max_target, target, ntime_start, ...), and the record names those of sv2-uniffi (Sv2FfiSetNewPrevHashMining, as the mining protocol's SetNewPrevHash is to tell it from template distribution's), so the header reads like the crates and the specification. Two field shapes differ from the structs, since C has no sequence type: a Seq0255<U256> is a count and the hashes back to back (merkle_path_count, merkle_path), and a Seq064K<u32> a count and the little endian values (channel_ids_count, channel_ids); an optional ntime_start comes with has_ntime_start.
The SRI crates are the ones released on crates.io with stratum v1.13.0 (channels_sv2 9, mining_sv2 13, common_messages_sv2 10, parsers_sv2 0.7, codec_sv2 8, binary_sv2 8, framing_sv2 9, noise_sv2 2.1).
Needs a Rust toolchain, 1.75 or newer like the SRI crates, and, the first time, network access to crates.io. The committed Cargo.lock is resolved for 1.75 and CI tests it there; .cargo/config.toml keeps cargo update on versions that build with it when cargo is 1.84 or newer.
./build.sh [prefix] # default: build/
installs lib/libsv2_ffi.a, include/sv2_ffi.h and lib/pkgconfig/sv2_ffi.pc (with the system libraries the archive needs), so a C build only needs:
cc ... $(PKG_CONFIG_PATH=<prefix>/lib/pkgconfig pkg-config --cflags --libs sv2_ffi)
When cbindgen is installed, build.sh fails if the committed header does not match the sources. Regenerate it with the version CI uses (CBINDGEN_VERSION in .github/workflows/ci.yml):
cbindgen --config cbindgen.toml --crate sv2_ffi --output include/sv2_ffi.h .
On x86_64, build for the CPU it will run on (RUSTFLAGS="-C target-cpu=native" or x86-64-v3): the ChaCha20-Poly1305 of the crates costs three to four times as much per short message on baseline x86-64.
40 functions. The rules that hold for every one of them:
- Buffers belong to the caller. An encoder writes into a buffer of a given capacity. A decoded message's byte fields (
Sv2FfiBytes, a pointer and a length) point into the frame the Noise session decoded it from, which the session keeps until its next decode or its free, and are never NULL, even when empty. Nothing keeps a pointer the caller passed in after returning, so no Rust lifetime reaches C. - Objects. The only Rust allocations a caller holds are the objects of the
_new()functions, each released by its_free(): a Noise session per connection, an extranonce allocator, and a channel object per channel, which keeps the jobs it is given. - Threads. Each object is used by one thread at a time and may move to another thread between calls; an allocator and the channels opened from it share state, so they count as one object. A Noise session's encode and decode count too: an error in either ends the whole session.
- Return values.
SV2_FFI_OK(0), a byte count where documented,SV2_FFI_NEED_MOREfromsv2_ffi_noise_try_decode(), or a negativeSV2_FFI_ERR_*code. The header is the only definition of the values. The channel codes (SV2_FFI_ERR_CH_*,SV2_FFI_ERR_SHARE_*) each name a crate error, andsv2_ffi_channel_error_code()gives the spec's error-code string for it, the one to put inOpenMiningChannel.Error,UpdateChannel.ErrororSubmitShares.Error. - No panic reaches C. Every function runs under
catch_unwindand reports a panic asSV2_FFI_ERR_INTERNAL(NULL from a constructor). The object the call was made on must then be freed, not used again; anything else the caller holds is fine. A server drops one connection instead of stopping with all of them. - No frame headers. The session encodes a record with the message type and channel_msg bit its subprotocol crate assigns, and decodes what
parsers_sv2finds in a frame. A well-formed frame of a message or extension this API has no record for isSV2_FFI_ERR_UNSUPPORTED, and the session goes on with the next one. Bytes in a frame after its message are left toparsers_sv2, which reads them as TLV fields of negotiated extensions; none are negotiated here, so they are ignored.
| Group | Functions |
|---|---|
| Authority key | sv2_ffi_authority_keypair_generate, sv2_ffi_authority_pubkey, sv2_ffi_authority_pubkey_to_base58, sv2_ffi_authority_pubkey_from_base58 |
| Handshake | sv2_ffi_noise_responder_new, sv2_ffi_noise_initiator_new, sv2_ffi_noise_free, sv2_ffi_noise_initiator_step0, sv2_ffi_noise_responder_step1, sv2_ffi_noise_initiator_step2, sv2_ffi_noise_is_transport |
| Messages | sv2_ffi_noise_encode, sv2_ffi_noise_encoded_size, sv2_ffi_noise_try_decode, and the Sv2FfiMessage record: a message type and a union of the records of SetupConnection, .Success, .Error, ChannelEndpointChanged, Reconnect, Open{Standard,Extended}MiningChannel and .Success, OpenMiningChannel.Error, UpdateChannel, .Error, CloseChannel, SetExtranoncePrefix, SetTarget, SetGroupChannel, NewMiningJob, NewExtendedMiningJob, SetNewPrevHash (mining), SetCustomMiningJob, .Success, .Error, SubmitShares{Standard,Extended}, .Success, .Error |
| Channels | sv2_ffi_extranonce_allocator_new/free/rollable_size; for each of extended_channel and standard_channel: _new, _free, _extranonce_prefix, _target, _set_target, _update, _prebuilt_job, _job_target, _activate_job, _validate_share, _share_accounting; sv2_ffi_channel_error_code |
Each function is documented in sv2_ffi.h. tests/capi_test.c is a short example of all of them from C: a handshake, messages each way, and an extended and a standard channel that take jobs, check shares, hand back a block's coinbase and keep their accounting, with the error paths.
./test.sh [prefix] # build.sh, cargo test, then tests/capi_test.c
SANITIZE=1 ./test.sh # the C test under ASan and UBSan
cargo +nightly fuzz run message_decode -- -max_total_time=600
cargo test: the records round trip through the encoder and the decoder, messages through the transport across chunk boundaries, the channel rules with a hand-built coinbase, and random and mutated frames that must never panic.tests/capi_test.c: a C program that links only the library, and runs the API the way a server and a miner do, with the error paths: handshake steps out of order, a certificate checked past its validity, NULL arguments, short buffers (a block's coinbase among them), records the encoder refuses, a session ended by a tampered frame, duplicate and stale shares.fuzz/: cargo-fuzz targets on the C API, with acodec_sv2initiator as the miner where a target needs a peer that sends frames the API would never encode.message_decode(any header and payload, then a re-encode round trip),noise_transport(any act 1; any stream, or frames chosen by the input, read back in pieces chosen by the input) andchannel_share(targets, UpdateChannel, jobs, SetNewPrevHash and shares in any order, on both channel types, with the share accounting). A panic is a crash there: libfuzzer-sys installs a panic hook that aborts the process before unwinding reachescatch_unwind. CI pins the nightly and cargo-fuzz, andfuzz/Cargo.lockis committed.
Licensed under Apache 2.0 or MIT, at your option, like the other SRI repositories. See LICENSE.md.