chacha20.cpp raw
1 // Copyright (c) 2019-present The Bitcoin Core developers
2 // Distributed under the MIT software license, see the accompanying
3 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
4
5 #include <bench/bench.h>
6 #include <crypto/chacha20.h>
7 #include <crypto/chacha20poly1305.h>
8 // IWYU incorrectly suggests removing this header.
9 // See https://github.com/include-what-you-use/include-what-you-use/issues/2014.
10 #include <util/byte_units.h> // IWYU pragma: keep
11
12 #include <cstddef>
13 #include <cstdint>
14 #include <span>
15 #include <vector>
16
17 /* Number of bytes to process per iteration */
18 static const uint64_t BUFFER_SIZE_TINY = 64;
19 static const uint64_t BUFFER_SIZE_SMALL = 256;
20 static const uint64_t BUFFER_SIZE_LARGE{1_MiB};
21
22 static void CHACHA20(benchmark::Bench& bench, size_t buffersize)
23 {
24 std::vector<std::byte> key(32, {});
25 ChaCha20 ctx(key);
26 ctx.Seek({0, 0}, 0);
27 std::vector<std::byte> in(buffersize, {});
28 std::vector<std::byte> out(buffersize, {});
29 bench.batch(in.size()).unit("byte").run([&] {
30 ctx.Crypt(in, out);
31 });
32 }
33
34 static void FSCHACHA20POLY1305(benchmark::Bench& bench, size_t buffersize)
35 {
36 std::vector<std::byte> key(32);
37 FSChaCha20Poly1305 ctx(key, 224);
38 std::vector<std::byte> in(buffersize);
39 std::vector<std::byte> aad;
40 std::vector<std::byte> out(buffersize + FSChaCha20Poly1305::EXPANSION);
41 bench.batch(in.size()).unit("byte").run([&] {
42 ctx.Encrypt(in, aad, out);
43 });
44 }
45
46 static void CHACHA20_64BYTES(benchmark::Bench& bench)
47 {
48 CHACHA20(bench, BUFFER_SIZE_TINY);
49 }
50
51 static void CHACHA20_256BYTES(benchmark::Bench& bench)
52 {
53 CHACHA20(bench, BUFFER_SIZE_SMALL);
54 }
55
56 static void CHACHA20_1MB(benchmark::Bench& bench)
57 {
58 CHACHA20(bench, BUFFER_SIZE_LARGE);
59 }
60
61 static void FSCHACHA20POLY1305_64BYTES(benchmark::Bench& bench)
62 {
63 FSCHACHA20POLY1305(bench, BUFFER_SIZE_TINY);
64 }
65
66 static void FSCHACHA20POLY1305_256BYTES(benchmark::Bench& bench)
67 {
68 FSCHACHA20POLY1305(bench, BUFFER_SIZE_SMALL);
69 }
70
71 static void FSCHACHA20POLY1305_1MB(benchmark::Bench& bench)
72 {
73 FSCHACHA20POLY1305(bench, BUFFER_SIZE_LARGE);
74 }
75
76 BENCHMARK(CHACHA20_64BYTES);
77 BENCHMARK(CHACHA20_256BYTES);
78 BENCHMARK(CHACHA20_1MB);
79 BENCHMARK(FSCHACHA20POLY1305_64BYTES);
80 BENCHMARK(FSCHACHA20POLY1305_256BYTES);
81 BENCHMARK(FSCHACHA20POLY1305_1MB);
82