Repository navigation
perf(noise_sv2): use rust-bitcoin's chacha20-poly1305 for the AEAD - #2506
rustaceanrob wants to merge 1 commit into
Conversation
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
|
cc @bit-aloo |
|
Damn!! rust-bitcoin's implementation is faster than rustcrypto 😆 I will have a look at this PR soon! |
|
I was curious how performance would be for more realistic message flows, and I had claude write some more benchmarks for those
Benchmark diffdiff --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");
+} |
|
@rustaceanrob a small question about key hygiene here. |
|
I don't actually know why we implement |
|
Will be cool, if we can clear key material before stack frame pops |
Our
chacha20-poly1305implementation inrust-bitcoinhas 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
ChaCha20Poly1305that 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
aeadcrate is preserved to avoid a breaking change, but this can also be removed in a3.0.0with a simple new type. Considering Stratum already depends onrust-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:
Constant time equality check: https://github.com/rust-bitcoin/rust-bitcoin/blob/master/chacha20_poly1305/src/lib.rs#L147