symmetric_chacha.rs

benches/crypto/cases/src/symmetric_chacha.rs

symmetric_chacha.rs768 lines← Benchmarks
1//! Candidate fixtures; reusable algorithms contain no IC or benchmark code.2use cdk_rsx_crypto_bench_api::{Case, Operation, Params, Pattern};3use cdk_rsx_crypto_symmetric::{self as s, ChaChaBackend as Backend};4use std::hint::black_box;56#[derive(Clone, Copy)]7enum Kind {8    Xor(Backend, bool),9    HChaCha,10    Poly(bool),11    Verify,12    Aead {13        x: bool,14        backend: Backend,15        open: bool,16        records: bool,17    },18}19enum Prepared {20    ChaCha(s::ChaCha20Key),21    Poly(s::Poly1305WideKey),22    Cipher(s::ChaCha20Poly1305Wide),23    XCipher(s::XChaCha20Poly1305Wide),24}25struct Item {26    key: [u8; 32],27    nonce: [u8; 24],28    aad: [u8; 32],29    plain: Vec<u8>,30    ciphertext: Vec<u8>,31    body: Vec<u8>,32    expected: Vec<u8>,33    tag: [u8; 16],34    output: [u8; 32],35    expected_output: [u8; 32],36    success: bool,37    expected_success: bool,38    prepared: Option<Prepared>,39}40struct Fixture {41    kind: Kind,42    items: Vec<Item>,43    shared: Option<Prepared>,44    ran: bool,45}46fn bytes(seed: u64, n: usize) -> Vec<u8> {47    let mut v = seed;48    (0..n)49        .map(|_| {50            v ^= v << 13;51            v ^= v >> 7;52            v ^= v << 17;53            v as u854        })55        .collect()56}57fn counter(iteration: u64, count: usize, index: usize) -> [u8; 12] {58    let value = iteration as u128 * count as u128 + index as u128;59    value.to_be_bytes()[4..]60        .try_into()61        .expect("bounded 96-bit record counter")62}63fn reference_seal(64    x: bool,65    key: &[u8; 32],66    nonce: &[u8; 24],67    aad: &[u8],68    body: &mut [u8],69) -> [u8; 16] {70    if x {71        s::XChaCha20Poly1305::new(key)72            .seal(nonce, aad, body)73            .expect("fixture length")74    } else {75        s::ChaCha20Poly1305::new(key)76            .seal(nonce[..12].try_into().expect("nonce"), aad, body)77            .expect("fixture length")78    }79}80fn prepare(p: &Params, kind: Kind) -> Result<Box<dyn Operation>, String> {81    if p.batch == 082        || p.batch > 50083        || p.message_len > 1024 * 102484        || p.message_len85            .checked_mul(p.batch)86            .is_none_or(|n| n > 8 * 1024 * 1024)87    {88        return Err("ChaCha candidate fixture exceeds bounded bytes/batch".into());89    }90    // Setup-only probes run the selected backend, including actual Wasm SIMD,91    // at final counters that the upstream stream wrapper cannot represent.92    // They are outside the timed body and remain in setup trace accounting.93    match kind {94        Kind::Xor(backend, _) | Kind::Aead { backend, .. } => counter_probe(backend)?,95        _ => {}96    }97    let records = matches!(kind, Kind::Aead { records: true, .. });98    if records && p.distinct {99        return Err("prepared record cases require distinct=false; input/AAD and nonces still vary per record".into());100    }101    let mut items = Vec::with_capacity(p.batch);102    for i in 0..p.batch {103        let seed = p.seed.wrapping_add(if p.distinct { i as u64 } else { 0 });104        let record_seed = seed.wrapping_add(if records { i as u64 + 1 } else { 0 });105        let key: [u8; 32] = bytes(seed ^ 0x834df3871, 32).try_into().expect("key");106        let mut nonce: [u8; 24] = bytes(record_seed ^ 0xf138daf27, 24)107            .try_into()108            .expect("nonce");109        if records {110            nonce[..12].copy_from_slice(&counter(0, p.batch, i));111        }112        let aad: [u8; 32] = bytes(record_seed ^ 0xc9a781e, 32).try_into().expect("aad");113        let plain = bytes(record_seed, p.message_len);114        let mut ciphertext = plain.clone();115        let mut expected = plain.clone();116        let mut expected_output = [0; 32];117        let valid = match p.pattern {118            Pattern::Valid => true,119            Pattern::Invalid => false,120            Pattern::Mixed => i % 2 == 0,121        };122        let mut expected_success = true;123        match kind {124            Kind::Xor(..) => s::chacha20_xor_reference(125                &key,126                nonce[..12].try_into().expect("nonce"),127                1,128                &mut expected,129            )130            .expect("fixture length"),131            Kind::HChaCha => expected_output132                .copy_from_slice(&s::hchacha20(&key, nonce[..16].try_into().expect("nonce"))),133            Kind::Poly(_) | Kind::Verify => {134                expected_output[..16].copy_from_slice(&s::poly1305_tag(&key, &plain));135                expected_success = !matches!(kind, Kind::Verify) || valid;136            }137            Kind::Aead { x, open, .. } => {138                expected_output[..16].copy_from_slice(&reference_seal(139                    x,140                    &key,141                    &nonce,142                    &aad,143                    &mut ciphertext,144                ));145                if open {146                    expected_success = valid;147                    if !valid {148                        expected.fill(0);149                    }150                } else {151                    expected.copy_from_slice(&ciphertext);152                }153            }154        }155        let mut tag: [u8; 16] = expected_output[..16].try_into().expect("tag");156        if (matches!(kind, Kind::Verify) || matches!(kind, Kind::Aead { open: true, .. })) && !valid157        {158            tag[if i % 2 == 0 { 0 } else { 15 }] ^= 1;159        }160        let prepared = if p.distinct || i == 0 {161            match kind {162                Kind::Xor(_, true) => Some(Prepared::ChaCha(s::ChaCha20Key::new(&key))),163                Kind::Poly(true) | Kind::Verify => {164                    Some(Prepared::Poly(s::Poly1305WideKey::new(&key)))165                }166                Kind::Aead {167                    x: false,168                    backend,169                    records: true,170                    ..171                } => Some(Prepared::Cipher(s::ChaCha20Poly1305Wide::new(172                    &key, backend,173                ))),174                Kind::Aead {175                    x: true,176                    backend,177                    records: true,178                    ..179                } => Some(Prepared::XCipher(s::XChaCha20Poly1305Wide::new(180                    &key, backend,181                ))),182                _ => None,183            }184        } else {185            None186        };187        items.push(Item {188            key,189            nonce,190            aad,191            body: plain.clone(),192            plain,193            ciphertext,194            expected,195            tag,196            output: [0; 32],197            expected_output,198            success: false,199            expected_success,200            prepared,201        });202    }203    let shared = if p.distinct {204        None205    } else {206        items[0].prepared.take()207    };208    Ok(Box::new(Fixture {209        kind,210        items,211        shared,212        ran: false,213    }))214}215216fn counter_probe(backend: Backend) -> Result<(), String> {217    let key = s::ChaCha20Key::new(&[0x37; 32]);218    let nonce = [0x91; 12];219    for (start, lengths) in [220        (u32::MAX, &[1usize, 3, 4, 15, 16, 17, 31, 32, 63, 64][..]),221        (u32::MAX - 3, &[192usize, 193, 255, 256][..]),222    ] {223        for &n in lengths {224            let mut actual = vec![0x73; n];225            let mut expected = actual.clone();226            for (i, part) in expected.chunks_mut(64).enumerate() {227                for (byte, stream) in part.iter_mut().zip(key.block(&nonce, start + i as u32)) {228                    *byte ^= stream;229                }230            }231            apply_xor(backend, &key, &nonce, start, &mut actual)232                .map_err(|e| format!("counter probe: {e:?}"))?;233            if actual != expected {234                return Err(format!(235                    "final-counter output differs for {backend:?}, {start}, {n}"236                ));237            }238        }239        let capacity = (u32::MAX as u64 + 1 - start as u64) as usize * 64;240        let mut over = vec![0x73; capacity + 1];241        if apply_xor(backend, &key, &nonce, start, &mut over) != Err(s::Error::MessageTooLong)242            || over.iter().any(|&b| b != 0x73)243        {244            return Err(format!("counter overflow mutated output for {backend:?}"));245        }246    }247    Ok(())248}249250fn apply_xor(251    backend: Backend,252    key: &s::ChaCha20Key,253    nonce: &[u8; 12],254    counter: u32,255    body: &mut [u8],256) -> Result<(), s::Error> {257    match backend {258        Backend::Words => key.xor_words(nonce, counter, body),259        Backend::Simd => key.xor_simd(nonce, counter, body),260        Backend::Simd4 => key.xor_simd4(nonce, counter, body),261    }262}263fn xor(backend: Backend, key: &s::ChaCha20Key, nonce: &[u8; 12], body: &mut [u8]) {264    apply_xor(backend, key, nonce, 1, body).expect("bounded fixture");265}266impl Operation for Fixture {267    fn operations_per_run(&self) -> usize {268        self.items.len()269    }270    fn run(&mut self, iteration: u64) -> u64 {271        let mut sum = 0u64;272        let count = self.items.len();273        for (i, item) in self.items.iter_mut().enumerate() {274            if matches!(self.kind, Kind::Aead { records: true, .. }) {275                item.nonce[..12].copy_from_slice(&counter(iteration, count, i));276            }277            let retained = self.shared.as_ref().or(item.prepared.as_ref());278            let key = black_box(&item.key);279            let nonce = black_box(&item.nonce);280            let aad = black_box(&item.aad);281            item.success = true;282            match self.kind {283                Kind::Xor(backend, prepared) => {284                    item.body.copy_from_slice(black_box(&item.plain));285                    if prepared {286                        let Some(Prepared::ChaCha(k)) = retained else {287                            unreachable!()288                        };289                        xor(290                            backend,291                            k,292                            nonce[..12].try_into().expect("nonce"),293                            &mut item.body,294                        );295                    } else {296                        xor(297                            backend,298                            &s::ChaCha20Key::new(key),299                            nonce[..12].try_into().expect("nonce"),300                            &mut item.body,301                        );302                    }303                }304                Kind::HChaCha => item.output.copy_from_slice(&s::hchacha20_simd(305                    key,306                    nonce[..16].try_into().expect("nonce"),307                )),308                Kind::Poly(prepared) => {309                    let tag = if prepared {310                        let Some(Prepared::Poly(k)) = retained else {311                            unreachable!()312                        };313                        k.tag(black_box(&item.plain))314                    } else {315                        s::Poly1305WideKey::new(key).tag(black_box(&item.plain))316                    };317                    item.output[..16].copy_from_slice(&tag);318                }319                Kind::Verify => {320                    let Some(Prepared::Poly(k)) = retained else {321                        unreachable!()322                    };323                    item.success = k.verify(black_box(&item.plain), black_box(&item.tag));324                }325                Kind::Aead {326                    x,327                    backend,328                    open,329                    records,330                } => {331                    item.body.copy_from_slice(black_box(if open {332                        &item.ciphertext333                    } else {334                        &item.plain335                    }));336                    macro_rules! perform {337                        ($cipher:expr, $nonce:expr) => {{338                            if open {339                                item.success = $cipher340                                    .open($nonce, aad, &mut item.body, black_box(&item.tag))341                                    .is_ok();342                            } else {343                                item.output[..16].copy_from_slice(344                                    &$cipher345                                        .seal($nonce, aad, &mut item.body)346                                        .expect("fixture length"),347                                );348                            }349                        }};350                    }351                    if records {352                        match retained {353                            Some(Prepared::Cipher(c)) => {354                                perform!(c, nonce[..12].try_into().expect("nonce"))355                            }356                            Some(Prepared::XCipher(c)) => perform!(c, nonce),357                            _ => unreachable!(),358                        }359                    } else if x {360                        perform!(s::XChaCha20Poly1305Wide::new(key, backend), nonce);361                    } else {362                        perform!(363                            s::ChaCha20Poly1305Wide::new(key, backend),364                            nonce[..12].try_into().expect("nonce")365                        );366                    }367                }368            }369            black_box(item.body.as_slice());370            black_box(item.output);371            black_box(item.success);372            sum = sum.rotate_left(7)373                ^ u64::from_le_bytes(item.output[..8].try_into().expect("sum"))374                ^ item.success as u64;375            if let Some(byte) = item.body.first() {376                sum ^= *byte as u64;377            }378        }379        self.ran = true;380        sum381    }382    fn check(&mut self) -> Result<(), String> {383        if !self.ran {384            return Err("candidate operation has not run".into());385        }386        for (i, item) in self.items.iter_mut().enumerate() {387            if let Kind::Aead {388                x, records: true, ..389            } = self.kind390            {391                item.expected.copy_from_slice(&item.plain);392                item.expected_output[..16].copy_from_slice(&reference_seal(393                    x,394                    &item.key,395                    &item.nonce,396                    &item.aad,397                    &mut item.expected,398                ));399            }400            let correct = match self.kind {401                Kind::Xor(..) => item.body == item.expected,402                Kind::HChaCha | Kind::Poly(_) => item.output == item.expected_output,403                Kind::Verify => item.success == item.expected_success,404                Kind::Aead { open: true, .. } => {405                    item.body == item.expected && item.success == item.expected_success406                }407                Kind::Aead { open: false, .. } => {408                    item.body == item.expected && item.output == item.expected_output409                }410            };411            if !correct {412                return Err(format!("complete ChaCha candidate output mismatch at {i}"));413            }414        }415        Ok(())416    }417}418pub(crate) fn cases() -> Vec<Case> {419    vec![420        Case {421            id: "chacha20-words-fresh",422            description: "Scalar word XOR candidate with fresh key words and restore",423            prepare: |p| prepare(p, Kind::Xor(Backend::Words, false)),424        },425        Case {426            id: "chacha20-words-prepared",427            description: "Scalar word XOR candidate with retained key words and restore",428            prepare: |p| prepare(p, Kind::Xor(Backend::Words, true)),429        },430        Case {431            id: "chacha20-simd-fresh",432            description: "One-block SIMD candidate with fresh key words and restore",433            prepare: |p| prepare(p, Kind::Xor(Backend::Simd, false)),434        },435        Case {436            id: "chacha20-simd-prepared",437            description: "One-block SIMD candidate with retained key words and restore",438            prepare: |p| prepare(p, Kind::Xor(Backend::Simd, true)),439        },440        Case {441            id: "chacha20-simd4-fresh",442            description: "Four-block SIMD candidate with fresh key words and restore",443            prepare: |p| prepare(p, Kind::Xor(Backend::Simd4, false)),444        },445        Case {446            id: "chacha20-simd4-prepared",447            description: "Four-block SIMD candidate with retained key words and restore",448            prepare: |p| prepare(p, Kind::Xor(Backend::Simd4, true)),449        },450        Case {451            id: "hchacha20-simd",452            description: "One-block SIMD HChaCha20 candidate including fresh key words",453            prepare: |p| prepare(p, Kind::HChaCha),454        },455        Case {456            id: "poly1305-wide-fresh",457            description: "Widened 26-bit limbs candidate including fresh one-time key setup",458            prepare: |p| prepare(p, Kind::Poly(false)),459        },460        Case {461            id: "poly1305-wide-prepared",462            description: "Widened limbs with retained public one-time test key only",463            prepare: |p| prepare(p, Kind::Poly(true)),464        },465        Case {466            id: "poly1305-wide-verify",467            description: "Widened limbs with constant-time complete tag comparison",468            prepare: |p| prepare(p, Kind::Verify),469        },470        Case {471            id: "chachapoly-wide-words-seal-fresh",472            description: "chachapoly widened Poly1305/words seal, fresh key setup and restore",473            prepare: |p| {474                prepare(475                    p,476                    Kind::Aead {477                        x: false,478                        backend: Backend::Words,479                        open: false,480                        records: false,481                    },482                )483            },484        },485        Case {486            id: "chachapoly-wide-words-open-fresh",487            description: "chachapoly widened Poly1305/words open with complete failure wipe, fresh key setup and restore",488            prepare: |p| {489                prepare(490                    p,491                    Kind::Aead {492                        x: false,493                        backend: Backend::Words,494                        open: true,495                        records: false,496                    },497                )498            },499        },500        Case {501            id: "chachapoly-wide-words-seal-records",502            description: "chachapoly widened Poly1305/words, one retained key, distinct records and advancing nonces",503            prepare: |p| {504                prepare(505                    p,506                    Kind::Aead {507                        x: false,508                        backend: Backend::Words,509                        open: false,510                        records: true,511                    },512                )513            },514        },515        Case {516            id: "xchachapoly-wide-words-seal-fresh",517            description: "xchachapoly widened Poly1305/words seal, fresh key setup and restore",518            prepare: |p| {519                prepare(520                    p,521                    Kind::Aead {522                        x: true,523                        backend: Backend::Words,524                        open: false,525                        records: false,526                    },527                )528            },529        },530        Case {531            id: "xchachapoly-wide-words-open-fresh",532            description: "xchachapoly widened Poly1305/words open with complete failure wipe, fresh key setup and restore",533            prepare: |p| {534                prepare(535                    p,536                    Kind::Aead {537                        x: true,538                        backend: Backend::Words,539                        open: true,540                        records: false,541                    },542                )543            },544        },545        Case {546            id: "xchachapoly-wide-words-seal-records",547            description: "xchachapoly widened Poly1305/words, one retained key, distinct records and advancing nonces",548            prepare: |p| {549                prepare(550                    p,551                    Kind::Aead {552                        x: true,553                        backend: Backend::Words,554                        open: false,555                        records: true,556                    },557                )558            },559        },560        Case {561            id: "chachapoly-wide-simd-seal-fresh",562            description: "chachapoly widened Poly1305/simd seal, fresh key setup and restore",563            prepare: |p| {564                prepare(565                    p,566                    Kind::Aead {567                        x: false,568                        backend: Backend::Simd,569                        open: false,570                        records: false,571                    },572                )573            },574        },575        Case {576            id: "chachapoly-wide-simd-open-fresh",577            description: "chachapoly widened Poly1305/simd open with complete failure wipe, fresh key setup and restore",578            prepare: |p| {579                prepare(580                    p,581                    Kind::Aead {582                        x: false,583                        backend: Backend::Simd,584                        open: true,585                        records: false,586                    },587                )588            },589        },590        Case {591            id: "chachapoly-wide-simd-seal-records",592            description: "chachapoly widened Poly1305/simd, one retained key, distinct records and advancing nonces",593            prepare: |p| {594                prepare(595                    p,596                    Kind::Aead {597                        x: false,598                        backend: Backend::Simd,599                        open: false,600                        records: true,601                    },602                )603            },604        },605        Case {606            id: "xchachapoly-wide-simd-seal-fresh",607            description: "xchachapoly widened Poly1305/simd seal, fresh key setup and restore",608            prepare: |p| {609                prepare(610                    p,611                    Kind::Aead {612                        x: true,613                        backend: Backend::Simd,614                        open: false,615                        records: false,616                    },617                )618            },619        },620        Case {621            id: "xchachapoly-wide-simd-open-fresh",622            description: "xchachapoly widened Poly1305/simd open with complete failure wipe, fresh key setup and restore",623            prepare: |p| {624                prepare(625                    p,626                    Kind::Aead {627                        x: true,628                        backend: Backend::Simd,629                        open: true,630                        records: false,631                    },632                )633            },634        },635        Case {636            id: "xchachapoly-wide-simd-seal-records",637            description: "xchachapoly widened Poly1305/simd, one retained key, distinct records and advancing nonces",638            prepare: |p| {639                prepare(640                    p,641                    Kind::Aead {642                        x: true,643                        backend: Backend::Simd,644                        open: false,645                        records: true,646                    },647                )648            },649        },650        Case {651            id: "chachapoly-wide-simd4-seal-fresh",652            description: "chachapoly widened Poly1305/simd4 seal, fresh key setup and restore",653            prepare: |p| {654                prepare(655                    p,656                    Kind::Aead {657                        x: false,658                        backend: Backend::Simd4,659                        open: false,660                        records: false,661                    },662                )663            },664        },665        Case {666            id: "chachapoly-wide-simd4-open-fresh",667            description: "chachapoly widened Poly1305/simd4 open with complete failure wipe, fresh key setup and restore",668            prepare: |p| {669                prepare(670                    p,671                    Kind::Aead {672                        x: false,673                        backend: Backend::Simd4,674                        open: true,675                        records: false,676                    },677                )678            },679        },680        Case {681            id: "chachapoly-wide-simd4-seal-records",682            description: "chachapoly widened Poly1305/simd4, one retained key, distinct records and advancing nonces",683            prepare: |p| {684                prepare(685                    p,686                    Kind::Aead {687                        x: false,688                        backend: Backend::Simd4,689                        open: false,690                        records: true,691                    },692                )693            },694        },695        Case {696            id: "xchachapoly-wide-simd4-seal-fresh",697            description: "xchachapoly widened Poly1305/simd4 seal, fresh key setup and restore",698            prepare: |p| {699                prepare(700                    p,701                    Kind::Aead {702                        x: true,703                        backend: Backend::Simd4,704                        open: false,705                        records: false,706                    },707                )708            },709        },710        Case {711            id: "xchachapoly-wide-simd4-open-fresh",712            description: "xchachapoly widened Poly1305/simd4 open with complete failure wipe, fresh key setup and restore",713            prepare: |p| {714                prepare(715                    p,716                    Kind::Aead {717                        x: true,718                        backend: Backend::Simd4,719                        open: true,720                        records: false,721                    },722                )723            },724        },725        Case {726            id: "xchachapoly-wide-simd4-seal-records",727            description: "xchachapoly widened Poly1305/simd4, one retained key, distinct records and advancing nonces",728            prepare: |p| {729                prepare(730                    p,731                    Kind::Aead {732                        x: true,733                        backend: Backend::Simd4,734                        open: false,735                        records: true,736                    },737                )738            },739        },740    ]741}742743#[cfg(test)]744mod tests {745    use super::*;746    #[test]747    fn all_candidates_execute_exact_100_and_check_all_outputs() {748        for case in cases() {749            for n in [32, 128, 512, 2048] {750                for pattern in [Pattern::Valid, Pattern::Invalid, Pattern::Mixed] {751                    let p = Params {752                        batch: 100,753                        message_len: n,754                        pattern,755                        distinct: !case.id.ends_with("-records"),756                        seed: 73,757                    };758                    let mut operation = (case.prepare)(&p).unwrap();759                    assert_eq!(operation.operations_per_run(), 100);760                    for iteration in [0, 1, 17, u64::MAX] {761                        black_box(operation.run(iteration));762                        operation.check().unwrap();763                    }764                }765            }766        }767    }768}