Repository navigation
crypto: SHA-256 auto-detect + self-test on every node; one scrypt per LTC/DGB submit - #2353
Merged
Merged
Conversation
…very node binary btclibs compiles Bitcoin Core's x86 SHA-256 implementations (SSE4, SSE4.1 4-way, AVX2 8-way, SHA-NI) into non-MSVC x86 builds, but SHA256AutoDetect() ran only in c2pool-dash and c2pool-utxo: c2pool-ltc, -btc, -dgb, -bch, -bip110 and c2pool-v37-btc-dash hashed with the scalar Transform. Its only check, assert(SelfTest()), compiles out under NDEBUG. core::init_sha256() (src/core/sha256_init.hpp) is now the first statement of main() in c2pool-ltc, -btc, -dgb, -bch, -bip110, c2pool-v37-btc-dash and c2pool-utxo, and replaces the direct call in c2pool-dash: - C2POOL_SHA256=standard forces the scalar implementation; unset, empty or "auto" auto-detects; any other value is logged and auto-detects; - SHA256SelfTest() runs after the detection in every build. If the selected implementation fails it, an error is logged and the scalar implementation is put back; the node is not aborted; - one line on stderr: "[init] sha256: using <implementation>" (c2pool-dash keeps its startup block on stdout). --version stdout is unchanged. btclibs: SHA256AutoDetect takes Bitcoin Core's sha256_implementation mask (default USE_ALL), starts from the scalar implementation on every call (STANDARD puts it back), and no longer asserts; SHA256SelfTest() runs the known-answer test on the installed implementation. c2pool-v37 and c2pool-v37-btc link only Threads and do not hash with btclibs; c2pool-v37-xmr does not use btclibs SHA-256. MSVC and arm64 stay on the scalar implementation. KATs (core_test, sha256_dispatch_test.cpp): every implementation the CPU offers passes SHA256SelfTest and the standard vectors (FIPS 180-2 "", "abc", 448/896-bit, one million 'a'; sha256d of 64 zero bytes; BTC and LTC genesis header hashes); SHA-256, sha256d and SHA256D64 (1..64 blocks) are byte-equal to the scalar implementation over random inputs of 0..4096 bytes written in random pieces; the kill-switch, also through the real environment; a failing self-test falls back to standard and returns.
…t paths A pool share submitted over stratum had its 80-byte header hashed with scrypt by the vardiff gate and again in mining_submit: on LTC once for the merged-mining check and once for the block check, on DGB once for the classification. The bytes are the same in every case. - IWorkSource::compute_share_difficulty_pow: compute_share_difficulty that also hands back the header it hashed and the digest (SharePow). Default: compute_share_difficulty, no digest. LTC (MiningInterface) and DGB (DGBWorkSource) implement it; BTC, BCH, BIP110 and DASH keep the default. - The stratum session calls it and passes the result to mining_submit in JobSnapshot::gate_pow. - mining_submit uses the digest only for a header byte-equal to the one the gate hashed (SharePow::digest_for), else hashes as before. LTC hashes the header once for both the merged-mining check and the block check. Same difficulty, same acceptance, same blocks. Not changed: the share creation's own PoW check (impl/ltc/share_check.hpp create_local_share and the DGB mint), the job-less statistics difficulty in LTC mining_submit (calculate_share_difficulty(job_id, ...) hashes the live template's header, not the submission's), and the best-share card's hash (record-beating pseudoshares only). Counting seams: MiningInterface::header_scrypt_count(), DGBWorkSource::header_scrypt_count(). KATs: core_test submit_scrypt_once_test.cpp (gate digest is the header's scrypt; gate + mining_submit = one scrypt of the header with a merged-mining manager attached and the block found; one without the gate digest; a gate digest of other header bytes is not used; the same blocks submitted over 32 nonces with, without and with a wrong gate digest). dgb_work_source_test: mining_submit uses the gate digest of its header (no second scrypt, block dispatched, minted header equal), hashes for other bytes, and classifies 24 submissions the same with, without and with a wrong gate digest.
…very header field core_test (submit_scrypt_once_test.cpp): - AuxBlocksThroughMiningSubmitMatchAScryptOracle: a DOGE chain with an easy aux target (0x207fffff) committed in the stratum coinbase; over 24 nonces the aux blocks MiningInterface::mining_submit hands to the DOGE daemon, their AuxPoW parent hash and parent header, equal a scrypt oracle computed in the test; a parent hash above the aux target submits nothing. Run with the gate pow, without one, and with the gate pow of other bytes: same aux blocks and same parent (LTC) blocks; scrypt count 1 + the live template's statistics hash (2 + it for other bytes). - SnapshotDigestIsUsedForItsOwnBytes: for the same 80 bytes the snapshot's digest decides the merged and the block checks (a digest above every target: no aux block, no block; the gate's own digest: both found). - StratumSessionFillsTheSnapshotDigestFromItsOneGateCall: source pin of stratum_server.cpp: gate_pow is declared once, written only as the out parameter of the one compute_share_difficulty_pow call, then copied into the snapshot. - GatePowOfAnyOtherHeaderFieldIsHashedAgain: a gate pow whose header differs in extranonce2, ntime, prevhash, a rolled version bit, or a job version 0 (the header takes the default version): exactly one more scrypt per submission and the same blocks as without a gate pow. - OneScryptPerSubmitWithTheGatePow renamed ...NoLiveTemplate: the count is 1 because the rig has no live template, so the job-less statistics hash does not run. dgb_work_source_test: a gate pow of another extranonce2 or a rolled version bit: exactly one more scrypt, the same results and the same won blocks (block target 0x207fffff).
master's ref_hash_fn_t gained a trailing const std::optional<double>& (#2354); the AuxRig lambda in submit_scrypt_once_test.cpp takes it too.
The ASan+UBSan leg (GCC 13.4, Release -O3, -fsanitize=address,undefined -fno-omit-frame-pointer) aborts Sha256Dispatch.EveryImplementationPasses- SelfTestAndStandardVectors and .DetectedImplementationsAreByteIdentical- ToScalar: "SEGV on unknown address 0x00003587278b", a READ, in sha256_sse4::Transform called from SelfTest (sha256.cpp:531). Cause: the inline asm of sha256_sse4::Transform takes 14 general-purpose register operands. ASan moves its "+m" operands inp_end, inp and xfer into the instrumented frame; with rbp kept as the frame pointer no register is left for that frame's base, and GCC gives it %rax, which is also the "=r" operand y0 (%10): Transform+0x0d9 mov %rsi,0x20(%rax) inp_end Transform+0x16e mov %esi,%eax y0 = e, overwrites the base Transform+0x1b3 add 0x60(%rax),%r15d first xfer read, faults At the fault rax = Sigma1(e) = 0x3587272b with e = 0x510e527f (the SHA-256 IV), so the address is 0x3587272b + 0x60 = 0x3587278b for every message: the first round of the first block. rbp stays the frame pointer (bp 0x7fffffffd510 at the fault); no input or state byte is read out of bounds. The Release object addresses the three operands off %rsp. Per mask, one mask per process (ASan build of 5776552; SHA256SelfTest, "", "abc", one 64-byte block, SHA256D64 over 8 blocks): - vm905, Xeon E5-2690 v4 (no SHA-NI): masks 1, 3, 5 and 7 select sse4(1way) and fault at 0x3587278b on all but SHA256D64 (sse41 4-way, avx2 8-way); mask 0 clean. - oplex26, i7-14700T (SHA-NI): masks 1 and 3 fault the same way; masks 0, 5 and 7 (shani(1way,2way)) clean. On oplex26 "nested bug in the same thread" with no stack is the ASan symbolizer failing; with ASAN_OPTIONS=symbolize=0 the same frames print. Fix: Bitcoin Core fedeff7f201d (bitcoin/bitcoin#34953, for bitcoin/bitcoin#34881, GCC + ASan SEGV in sha256_sse4::Transform during SHA256AutoDetect's self-test): no_sanitize("address") on sha256_sse4::Transform under __SANITIZE_ADDRESS__, or on Clang under __has_feature(address_sanitizer), the same guard and position as Core. Without ASan neither is defined: the Release object of sha256_sse4.cpp has the same .text before and after (sha256 7a246c21...1623b146). Under ASan the operands are now off %rbp and Transform makes no ASan call. KAT 5 (sha256_dispatch_test.cpp, Linux, mmap/mprotect): NoImplementationTouchesBytesOutsideItsBuffers. Every mask (0, 1, 3, 5, 7): - message at lo() + o after a PROT_NONE page, o = 0..63, 0..256 bytes and 1 MiB; - message ending at a PROT_NONE page, 0..256 bytes and 1 MiB + k, k = 0..63 (every start offset mod 64), 0..256 also in two pieces cut at 0..63; - CSHA256 Write/Finalize at all of those, Hash() at all for 0..256 and for 1 MiB at o = 0 and k = 0; - SHA256D64 over 1..8 blocks, input and output each ending at a PROT_NONE page and at lo() + o, o = 0..63; output exactly 32 bytes per block. Every digest equals the scalar one; 242460 checks. Results (fix applied): - vm905 Release: Sha256Dispatch.* 6/6; guard pages 242460 checks, 0 mismatches (standard; sse4,sse41; sse4,sse41,avx2). - oplex26 Release: 6/6; 242460 checks, 0 mismatches (masks 5 and 7 shani(1way,2way)). - valgrind 3.22 memcheck, Release core_test --gtest_filter=Sha256Dispatch.* on vm905: 6/6, 0 errors (standard, sse4, sse41, avx2). valgrind does not run SHA-NI: under it CPUID shows no SHA (masks 5 and 7 select sse4 on oplex26) and sha256rnds2 (0f 38 cb) is an unrecognised instruction (SIGILL); SHA-NI is covered by the guard pages and ASan on oplex26. - ASan+UBSan, CI flags, vm905: Sha256Dispatch.* 6/6; core_test 885 of 886 passed, 1 skipped (UtxoSnapshotLive.DashMainnet2564044, live data), no ASan or UBSan report. - ASan+UBSan, the vm905 binary on oplex26: Sha256Dispatch.* 6/6, 242460 checks, 0 mismatches; masks 0, 1, 3, 5, 7 one per process clean.
frstrtr
added a commit
that referenced
this pull request
Nov 28, 2026
) The Windows "Verify binary" step in build.yml runs `c2pool.exe --help 2>&1` under the shell's default `$ErrorActionPreference = 'Stop'`. Since #2353 the binary logs `[init] sha256: using <impl>` on stderr at startup; PowerShell turns that stderr line into a terminating NativeCommandError and the step exits 1 (master run 46159848860, Windows x86_64). The step now sets `$ErrorActionPreference = 'Continue'` before the call, as release.yml's Windows smoke steps already do. The pass rule is unchanged: the captured output must not be empty. ## Tests - This PR's own Windows x86_64 job runs the changed step. - build.yml parses (yaml.safe_load).
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Two commits.
crypto: SHA-256 implementation chosen and self-tested at startup on every node binary (5207f8a)
core::init_sha256()(src/core/sha256_init.hpp) is the first statement ofmain()in c2pool-ltc, -btc, -dgb, -bch, -bip110, -dash, c2pool-v37-btc-dash and c2pool-utxo. Before this, only c2pool-dash calledSHA256AutoDetect(); the other binaries ran the scalar SHA-256.SHA256AutoDetect(sha256_implementation::UseImplementation)takes Bitcoin Core's implementation mask (defaultUSE_ALL). Each call starts from the scalar implementation.SHA256SelfTest()runs after detection in every build. On failure it logs[init] ERROR sha256: ...and puts the scalar implementation back. The node does not abort.assert(SelfTest())is removed fromSHA256AutoDetect; under NDEBUG it never ran.C2POOL_SHA256=standardforces the scalar implementation. Unset, empty orautoauto-detects; any other value is logged and auto-detects.[init] sha256: using <implementation>.--versionstdout is unchanged.src/core/test/sha256_dispatch_test.cpp(core_test).stratum: one scrypt of a submission's header on the LTC and DGB submit paths (3f9ba4b)
IWorkSource::compute_share_difficulty_powreturns the header the vardiff gate hashed and its digest (SharePow). The default callscompute_share_difficultyand returns none, so BTC, BCH, BIP110 and DASH are unchanged.mining_submitinJobSnapshot::gate_pow.MiningInterface) and DGB (DGBWorkSource) use that digest only when the header is byte-equal to the gate's header (SharePow::digest_for); otherwise they hash as before.src/core/test/submit_scrypt_once_test.cpp: gate + submit = exactly 1 scrypt of the header, with a merged-mining manager attached and a block found; submitted blocks identical across 32 nonces.src/impl/dgb/test/work_source_test.cpp: 3 cases (reused digest, other header bytes, same outcome across 24 submissions).create_local_share, the DGB mint) andrecord_best_pseudosharestill hash for themselves.Tests (vm905, all binaries built 506/506)
core_test 878, share_test 844, btc_share_test 316, dgb_share_test 88, dgb_template_builder_test 8, dgb_work_source_test 39, dgb_submit_classify_test 7, test_template_builder 35, test_dash_sml_simd_sha256 1, test_stratum_interim_hardening 44: all PASSED. test_settings_cli_scan ALL PASS. The BCH G1/G2/tx-refs/coinbase KATs and the BIP110 share-detail/mint/verify/workshape/serving KATs pass.
ASan: sha256_sse4::Transform (69909fe)
Cause: under ASan the SSE4 inline asm's
"+m"operands move into ASan's instrumented frame. With rbp kept as the frame pointer, GCC bases that frame on%rax, which is also the"=r"operand y0. Outputs are not early-clobber, so this is allowed. The first xfer read after y0 is written then faults at Σ1(IV e) + 0x60 = 0x3587278b on every input. The input buffer is never read out of bounds. The Release object addresses these operands off %rsp.Fix: a port of Bitcoin Core fedeff7f201d (crypto: disable ASan instrumentation of SSE4 SHA256 for GCC (matching Clang) bitcoin/bitcoin#34953, fixing #34881):
no_sanitize("address")onsha256_sse4::Transformwhen ASan is on. The Releasesha256_sse4.o.textis byte-identical before and after.New KAT
Sha256Dispatch.NoImplementationTouchesBytesOutsideItsBuffers(Linux, mmap/mprotect). It covers every mask (standard, sse4, sse4+avx2, sse4+shani, all). Messages start right after or end exactly at a PROT_NONE page: lengths 0..256 and 1 MiB(+0..63), offsets 0..63, split writes. Paths: CSHA256, Hash(), and SHA256D64 over 1..8 blocks with guarded output. 242,460 digests are compared to the scalar one.Evidence: