8000 perf(noise_sv2): use rust-bitcoin's chacha20-poly1305 for the AEAD by rustaceanrob · Pull Request #2506 · stratum-mining/stratum · GitHub
[go: up one dir, main page]

Skip to content

perf(noise_sv2): use rust-bitcoin's chacha20-poly1305 for the AEAD - #2506

Open
rustaceanrob wants to merge 1 commit into
stratum-mining:mainfrom
rustaceanrob:nov-15-chacha
Open

rustaceanrob wants to merge 1 commit into
stratum-mining:mainfrom
rustaceanrob:nov-15-chacha

Conversation

@rustaceanrob
Copy link
Copy Markdown

Our chacha20-poly1305 implementation in rust-bitcoin has recently added multi-block SIMD support for both ChaCha20 and Poly1305. Performance is now better for all the roundtrip benchmarks due to a setup cost somewhere within RustCrypto's implementation (I am not as familiar with their implementation and cannot allude to why).

This adds a wrapper class for ChaCha20Poly1305 that uses the existing zeroize crate to clear memory on drop. Some additional message parsing is done when decrypting to extract the tag. Otherwise it is a simple replacement. A sanity check test that the wrapper is working is added as well.

The aead crate is preserved to avoid a breaking change, but this can also be removed in a 3.0.0 with a simple new type. Considering Stratum already depends on rust-bitcoin, this allows for a consolidation of organizations Stratum depends on for maintenance.

The tag check is done in constant time, same behavior as RustCrypto.

Ryzen 7 7700, median of 3 runs:

Benchmark RustCrypto rust-bitcoin Change
transport/roundtrip/64B 4.70 us 781 ns -83%
transport/roundtrip/256B 4.83 us 1.17 us -76%
transport/roundtrip/1024B 6.12 us 2.07 us -66%
transport/roundtrip/4096B 11.89 us 7.03 us -41%
noise/encode_only 1.79 us 407 ns -77%
encoder/noise/transport 1.80 us 396 ns -78%
handshake/handshake 215.9 us 211.9 us -2%

Constant time equality check: https://github.com/rust-bitcoin/rust-bitcoin/blob/master/chacha20_poly1305/src/lib.rs#L147

Our `chacha20-poly1305` implementation in `rust-bitcoin` has recently
added multi-block SIMD support for both ChaCha20 and Poly1305.
Performance is now better for all the roundtrip benchmarks due to a
setup cost somewhere within RustCrypto's implementation (I am not as
familiar with their implementation and cannot allude to why).

This adds a wrapper class for `ChaCha20Poly1305` that uses the existing
zeroize crate to clear memory on drop. Some additional message parsing
is done when decrypting to extract the tag. Otherwise it is a simple
replacement. A sanity check test that the wrapper is working is added as
well.

The `aead` crate is preserved to avoid a breaking change, but this can
also be removed in a `3.0.0` with a simple new type. Considering Stratum
already depends on `rust-bitcoin`, this allows for a consolidation of
organizations Stratum depends on for maintenance.

The tag check is done in constant time, same behavior as RustCrypto.

Ryzen 7 7700, median of 3 runs:

| Benchmark                         | RustCrypto | rust-bitcoin | Change |
|-----------------------------------|------------|--------------|--------|
| transport/roundtrip/64B           |    4.70 us |       781 ns |   -83% |
| transport/roundtrip/256B          |    4.83 us |      1.17 us |   -76% |
| transport/roundtrip/1024B         |    6.12 us |      2.07 us |   -66% |
| transport/roundtrip/4096B         |   11.89 us |      7.03 us |   -41% |
| noise/encode_only                 |    1.79 us |       407 ns |   -77% |
| encoder/noise/transport           |    1.80 us |       396 ns |   -78% |
| handshake/handshake               |   215.9 us |     211.9 us |    -2% |

Constant time equality check: https://github.com/rust-bitcoin/rust-bitcoin/blob/master/chacha20_poly1305/src/lib.rs#L147
@GitGab19
Copy link
Copy Markdown
Member

cc @bit-aloo

@bit-aloo
Copy link
Copy Markdown
Member

Damn!! rust-bitcoin's implementation is faster than rustcrypto 😆 I will have a look at this PR soon!

@bit-aloo
bit-aloo self-requested a review November 16, 2026 17:29
@rustaceanrob
Copy link
Copy Markdown
Author

I was curious how performance would be for more realistic message flows, and I had claude write some more benchmarks for those

Message (payload) Op RustCrypto r1/r2/r3 rust-bitcoin r1/r2/r3 Median change
submit_shares_standard (24B) encrypt 1.86 µs / 1.86 µs / 1.87 µs 473 ns / 506 ns / 468 ns -74.6%
submit_shares_standard (24B) decrypt 1.88 µs / 1.88 µs / 1.88 µs 491 ns / 482 ns / 483 ns -74.2%
submit_shares_extended (33B) encrypt 2.19 µs / 2.20 µs / 2.18 µs 517 ns / 523 ns / 522 ns -76.2%
submit_shares_extended (33B) decrypt 2.17 µs / 2.17 µs / 2.17 µs 504 ns / 494 ns / 498 ns -77.1%
new_mining_job (45B) encrypt 2.19 µs / 2.19 µs / 2.21 µs 531 ns / 548 ns / 527 ns -75.8%
new_mining_job (45B) decrypt 2.18 µs / 2.18 µs / 2.18 µs 500 ns / 499 ns / 500 ns -77.1%
set_new_prev_hash (48B) encrypt 2.17 µs / 2.17 µs / 2.18 µs 499 ns / 499 ns / 498 ns -77.0%
set_new_prev_hash (48B) decrypt 2.18 µs / 2.18 µs / 2.17 µs 501 ns / 494 ns / 498 ns -77.1%
new_template (476B) encrypt 2.92 µs / 2.92 µs / 2.94 µs 1.34 µs / 1.35 µs / 1.35 µs -53.9%
new_template (476B) decrypt 2.51 µs / 2.51 µs / 2.54 µs 894 ns / 898 ns / 893 ns -64.4%
new_extended_mining_job (542B) encrypt 2.78 µs / 2.79 µs / 2.80 µs 1.14 µs / 1.14 µs / 1.14 µs -59.2%
new_extended_mining_job (542B) decrypt 2.41 µs / 2.41 µs / 2.42 µs 725 ns / 724 ns / 726 ns -69.9%
declare_mining_job (112188B) encrypt 131.55 µs / 131.02 µs / 130.68 µs 123.62 µs / 125.11 µs / 124.64 µs -4.9%
declare_mining_job (112188B) decrypt 55.38 µs / 55.57 µs / 55.38 µs 48.34 µs / 48.52 µs / 48.36 µs -12.7%
Benchmark diff
diff --git a/Cargo.lock b/Cargo.lock
index 58a34da8..b4c7d52f 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -291,12 +291,15 @@ dependencies = [
  "buffer_sv2",
  "criterion",
  "framing_sv2",
+ "job_declaration_sv2",
  "
8000
key-utils",
+ "mining_sv2",
  "noise_sv2",
  "quickcheck",
  "quickcheck_macros",
  "rand",
  "rayon-core",
+ "template_distribution_sv2",
 ]

 [[[package](https://github.com/stratum-mining/stratum/pull/package)]]
diff --git a/sv2/codec-sv2/Cargo.toml b/sv2/codec-sv2/Cargo.toml
index 872077d7..e78beb81 100644
--- a/sv2/codec-sv2/Cargo.toml
+++ b/sv2/codec-sv2/Cargo.toml
@@ -24,6 +24,9 @@ criterion = { workspace = true }
 rayon-core = { workspace = true }
 quickcheck = { workspace = true }
 quickcheck_macros = { workspace = true }
+mining_sv2 = { path = "../subprotocols/mining" }
+template_distribution_sv2 = { path = "../subprotocols/template-distribution" }
+job_declaration_sv2 = { path = "../subprotocols/job-declaration" }

 [features]
 default = ["std"]
@@ -46,6 +49,10 @@ harness = false
 name = "noise_roundtrip"
 harness = false

+[[[bench](https://github.com/stratum-mining/stratum/pull/bench)]]
+name = "noise_realistic"
+harness = false
+
 [[[bench](https://github.com/stratum-mining/stratum/pull/bench)]]
 name = "serialization"
 harness = false
diff --git a/sv2/codec-sv2/benches/noise_realistic.rs b/sv2/codec-sv2/benches/noise_realistic.rs
new file mode 100644
index 00000000..42ecad93
--- /dev/null
+++ b/sv2/codec-sv2/benches/noise_realistic.rs
@@ -0,0 +1,289 @@
+// Encrypts and decrypts real Sv2 messages, at the sizes they have on the wire, over an
+// established Noise session.
+//
+// Each benchmark name carries the message's payload size. A frame costs one AEAD operation for
+// its 6-byte header plus one per payload chunk of up to 65519 bytes, so small messages measure
+// the per-operation overhead and `DeclareMiningJob` measures bulk throughput.
+//
+// The messages are sized after a mainnet block of 3500 transactions: a 12-hash merkle path, and
+// the coinbase prefix and suffix from the `channels_sv2` job fixtures.
+
+extern crate alloc;
+
+#[cfg(feature = "noise_sv2")]
+mod common;
+
+#[cfg(feature = "noise_sv2")]
+mod realistic {
+    use binary_sv2::{
+        B0255Owned, B032Owned, B064KOwned, Seq0255Owned, Seq064KOwned, Serialize, Sv2OptionOwned,
+        U256Owned,
+    };
+    use codec_sv2::{Decrypted, NoiseDecoder, NoiseEncoder};
+    use criterion::{black_box, BatchSize, Criterion};
+    use framing_sv2::framing::{EncodableFrame, MessageFrame};
+    use job_declaration_sv2::{
+        DeclareMiningJobOwned, CHANNEL_BIT_DECLARE_MINING_JOB, MESSAGE_TYPE_DECLARE_MINING_JOB,
+    };
+    use mining_sv2::{
+        NewExtendedMiningJobOwned, NewMiningJobOwned, SetNewPrevHashOwned,
+        SubmitSharesExtendedOwned, SubmitSharesStandard, CHANNEL_BIT_MINING_SET_NEW_PREV_HASH,
+        CHANNEL_BIT_NEW_EXTENDED_MINING_JOB, CHANNEL_BIT_NEW_MINING_JOB,
+        CHANNEL_BIT_SUBMIT_SHARES_EXTENDED, CHANNEL_BIT_SUBMIT_SHARES_STANDARD,
+        MESSAGE_TYPE_MINING_SET_NEW_PREV_HASH, MESSAGE_TYPE_NEW_EXTENDED_MINING_JOB,
+        MESSAGE_TYPE_NEW_MINING_JOB, MESSAGE_TYPE_SUBMIT_SHARES_EXTENDED,
+        MESSAGE_TYPE_SUBMIT_SHARES_STANDARD,
+    };
+    use template_distribution_sv2::{
+        NewTemplateOwned, CHANNEL_BIT_NEW_TEMPLATE, MESSAGE_TYPE_NEW_TEMPLATE,
+    };
+
+    use crate::common::make_transport_state_pair;
+
+    // Merkle path depth for a block of 3500 transactions (ceil(log2(3501))).
+    const MERKLE_PATH_DEPTH: usize = 12;
+    const BLOCK_TRANSACTIONS: usize = 3500;
+
+    // Coinbase split around the extranonce, as in the `channels_sv2` job fixtures.
+    const COINBASE_TX_PREFIX: [u8; 52] = [
+        2, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+        0, 0, 0, 0, 0, 0, 0, 255, 255, 255, 255, 42, 82, 0, 6, 83, 118, 50, 47, 47, 47, 32,
+    ];
+    const COINBASE_TX_SUFFIX: [u8; 87] = [
+        255, 255, 255, 255, 2, 0, 242, 5, 42, 1, 0, 0, 0, 22, 0, 20, 235, 225, 183, 220, 194, 147,
+        204, 170, 14, 231, 67, 168, 111, 137, 223, 130, 88, 194, 8, 252, 0, 0, 0, 0, 0, 0, 0, 0,
+        38, 106, 36, 170, 33, 169, 237, 226, 246, 28, 63, 113, 209, 222, 253, 63, 169, 153, 223,
+        163, 105, 83, 117, 92, 105, 6, 137, 121, 153, 98, 180, 139, 235, 216, 54, 151, 78, 140,
+        249, 0, 0, 0, 0,
+    ];
+
+    fn hash(byte: u8) -> U256Owned {
+        [byte; 32].into()
+    }
+
+    fn merkle_path() -> Seq0255Owned<U256Owned> {
+        Seq0255Owned::try_from((0..MERKLE_PATH_DEPTH as u8).map(hash).collect::<Vec<_>>()).unwrap()
+    }
+
+    fn submit_shares_standard() -> SubmitSharesStandard {
+        SubmitSharesStandard {
+            channel_id: 1,
+            sequence_number: 42,
+            job_id: 7,
+            nonce: 0xdead_beef,
+            ntime: 1_700_000_000,
+            version: 0x2000_0000,
+        }
+    }
+
+    fn submit_shares_extended() -> SubmitSharesExtendedOwned {
+        SubmitSharesExtendedOwned {
+            channel_id: 1,
+            sequence_number: 42,
+            job_id: 7,
+            nonce: 0xdead_beef,
+            ntime: 1_700_000_000,
+            version: 0x2000_0000,
+            extranonce: B032Owned::try_from(vec![0xab; 8]).unwrap(),
+        }
+    }
+
+    fn new_mining_job() -> NewMiningJobOwned {
+        NewMiningJobOwned {
+            channel_id: 1,
+            job_id: 7,
+            ntime_start: Sv2OptionOwned::new(None),
+            version: 0x2000_0000,
+            merkle_root: hash(0x11),
+        }
+    }
+
+    fn set_new_prev_hash() -> SetNewPrevHashOwned {
+        SetNewPrevHashOwned {
+            channel_id: 1,
+            job_id: 7,
+            prev_hash: hash(0x22),
+            ntime_start: 1_700_000_000,
+            nbits: 0x1703_4219,
+        }
+    }
+
+    fn new_extended_mining_job() -> NewExtendedMiningJobOwned {
+        NewExtendedMiningJobOwned {
+            channel_id: 1,
+            job_id: 7,
+            ntime_start: Sv2OptionOwned::new(None),
+            version: 0x2000_0000,
+            version_rolling_allowed: true,
+            merkle_path: merkle_path(),
+            coinbase_tx_prefix: B064KOwned::try_from(COINBASE_TX_PREFIX.to_vec()).unwrap(),
+            coinbase_tx_suffix: B064KOwned::try_from(COINBASE_TX_SUFFIX.to_vec()).unwrap(),
+        }
+    }
+
+    fn new_template() -> NewTemplateOwned {
+        NewTemplateOwned {
+            template_id: 9,
+            future_template: false,
+            version: 0x2000_0000,
+            coinbase_tx_version: 2,
+            coinbase_prefix: B0255Owned::try_from(vec![0x03, 0x52, 0x0d, 0x0e]).unwrap(),
+            coinbase_tx_input_sequence: 0xffff_ffff,
+            coinbase_tx_value_remaining: 312_500_000,
+            coinbase_tx_outputs_count: 1,
+            // The witness commitment output from the coinbase suffix.
+            coinbase_tx_outputs: B064KOwned::try_from(COINBASE_TX_SUFFIX[36..83].to_vec()).unwrap(),
+            coinbase_tx_locktime: 0,
+            merkle_path: merkle_path(),
+        }
+    }
+
+    fn declare_mining_job() -> DeclareMiningJobOwned {
+        DeclareMiningJobOwned {
+            request_id: 3,
+            mining_job_token: B0255Owned::try_from(vec![0xcd; 32]).unwrap(),
+            version: 0x2000_0000,
+            coinbase_tx_prefix: B064KOwned::try_from(COINBASE_TX_PREFIX.to_vec()).unwrap(),
+            coinbase_tx_suffix: B064KOwned::try_from(COINBASE_TX_SUFFIX.to_vec()).unwrap(),
+            wtxid_list: Seq064KOwned::try_from(
+                (0..BLOCK_TRANSACTIONS)
+                    .map(|i| hash(i as u8))
+                    .collect::<Vec<_>>(),
+            )
+            .unwrap(),
+            excess_data: B064KOwned::try_from(Vec::new()).unwrap(),
+        }
+    }
+
+    // Benchmarks encrypting and decrypting one message type through the Noise codec.
+    //
+    // `encrypt` serializes and encrypts a frame into a reused buffer, as a writer that keeps one
+    // buffer per connection does. `decrypt` feeds an encrypted frame to the decoder and decrypts it
+    // back to a serialized frame; the frames are encrypted outside the measurement, in order, so the
+    // decryptor's nonce always matches.
+    fn bench_message<M, F>(c: &mut Criterion, name: &str, make: F, message_type: u8, channel: bool)
+    where
+        M: Serialize + binary_sv2::GetSize,
+        F: Fn() -> M,
+        MessageFrame<M>: EncodableFrame,
+    {
+        let frame = || MessageFrame::from_message(make(), message_type, 0, channel).unwrap();
+        let payload_len = frame().encoded_length() - framing_sv2::header::Header::SIZE;
+        let mut group = c.benchmark_group(format!("realistic/{name}/{payload_len}B"));
+
+        group.bench_function("encrypt", |b| {
+            let (mut enc_state, _) = make_transport_state_pair();
+            let mut enc = NoiseEncoder::new();
+            let mut out = Vec::new();
+            b.iter_batched(
+                frame,
+                |frame| {
+                    out.clear();
+                    enc.encode_transport_into(black_box(frame), &mut enc_state, &mut out)
+                        .unwrap();
+                    black_box(&out);
+                },
+                BatchSize::SmallInput,
+            );
+        });
+
+        group.bench_function("decrypt", |b| {
+            let (mut enc_state, dec_state) = make_transport_state_pair();
+            let mut enc = NoiseEncoder::new();
+            let mut dec = NoiseDecoder::new();
+            let mut dec_state = Some(dec_state);
+            b.iter_batched(
+                || {
+                    let mut encrypted = Vec::new();
+                    enc.encode_transport_into(frame(), &mut enc_state, &mut encrypted)
+                        .unwrap();
+                    encrypted
+                },
+                |encrypted| {
+                    let mut offset = 0;
+                    loop {
+                        let w = dec.read_buf();
+                        let n = w.len();
+                        w.copy_from_slice(&encrypted[offset..offset + n]);
+                        dec.advance(n).unwrap();
+                        offset += n;
+                        match dec.next_transport_frame(dec_state.take().unwrap()).unwrap() {
+                            Decrypted::Frame(decoded, state) => {
+                                dec_state = Some(state);
+                                black_box(decoded);
+                                break;
+                            }
+                            Decrypted::Incomplete(state) => dec_state = Some(state),
+                        }
+                    }
+                    assert_eq!(offset, encrypted.len());
+                },
+                BatchSize::SmallInput,
+            );
+        });
+
+        group.finish();
+    }
+
+    pub fn benches(c: &mut Criterion) {
+        bench_message(
+            c,
+            "submit_shares_standard",
+            submit_shares_standard,
+            MESSAGE_TYPE_SUBMIT_SHARES_STANDARD,
+            CHANNEL_BIT_SUBMIT_SHARES_STANDARD,
+        );
+        bench_message(
+            c,
+            "submit_shares_extended",
+            submit_shares_extended,
+            MESSAGE_TYPE_SUBMIT_SHARES_EXTENDED,
+            CHANNEL_BIT_SUBMIT_SHARES_EXTENDED,
+        );
+        bench_message(
+            c,
+            "new_mining_job",
+            new_mining_job,
+            MESSAGE_TYPE_NEW_MINING_JOB,
+            CHANNEL_BIT_NEW_MINING_JOB,
+        );
+        bench_message(
+            c,
+            "set_new_prev_hash",
+            set_new_prev_hash,
+            MESSAGE_TYPE_MINING_SET_NEW_PREV_HASH,
+            CHANNEL_BIT_MINING_SET_NEW_PREV_HASH,
+        );
+        bench_message(
+            c,
+            "new_template",
+            new_template,
+            MESSAGE_TYPE_NEW_TEMPLATE,
+            CHANNEL_BIT_NEW_TEMPLATE,
+        );
+        bench_message(
+            c,
+            "new_extended_mining_job",
+            new_extended_mining_job,
+            MESSAGE_TYPE_NEW_EXTENDED_MINING_JOB,
+            CHANNEL_BIT_NEW_EXTENDED_MINING_JOB,
+        );
+        bench_message(
+            c,
+            "declare_mining_job",
+            declare_mining_job,
+            MESSAGE_TYPE_DECLARE_MINING_JOB,
+            CHANNEL_BIT_DECLARE_MINING_JOB,
+        );
+    }
+}
+
+#[cfg(feature = "noise_sv2")]
+criterion::criterion_group!(noise_realistic, realistic::benches);
+#[cfg(feature = "noise_sv2")]
+criterion::criterion_main!(noise_realistic);
+
+#[cfg(not(feature = "noise_sv2"))]
+fn main() {
+    eprintln!("Noise benchmarks require the 'noise_sv2' feature");
+}

@bit-aloo
Copy link
Copy Markdown
Member

@rustaceanrob a small question about key hygiene here. Key, ChaCha20 and Poly1305 are all Copy and don't seem to be zeroized on drop. So we might end up leaving copies of key material in memory, even though we zeroize the key in our wrapper. RustCrypto did some zeroization here. I am curious if there's a reason for not doing it in this crate?

@rustaceanrob
Copy link
Copy Markdown
Author

I don't actually know why we implement Copy on those, I worked on the architecture specific SIMD. Maybe @nyonson has an idea. I'm not familiar with how zeroize does it but it seems like we can implement a custom Drop to zero memory. Understandable if that is a blocker, can work on a fix.

@bit-aloo
Copy link
Copy Markdown
Member

Will be cool, if we can clear key material before stack frame pops

@rustaceanrob
Copy link
Copy Markdown
Author

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