Coverage Report

Created: 2025-10-08 19:34

/work/toxcore/crypto_core_test_util.hh
Line
Count
Source (jump to first uncovered line)
1
#ifndef C_TOXCORE_TOXCORE_CRYPTO_CORE_TEST_UTIL_H
2
#define C_TOXCORE_TOXCORE_CRYPTO_CORE_TEST_UTIL_H
3
4
#include <algorithm>
5
#include <array>
6
#include <iosfwd>
7
#include <random>
8
9
#include "crypto_core.h"
10
#include "test_util.hh"
11
#include "tox_random_impl.h"
12
13
struct Random_Class {
14
    static Tox_Random_Funcs const vtable;
15
    Tox_Random const self;
16
17
    operator Tox_Random const *() const { return &self; }
18
19
    Random_Class(Random_Class const &) = default;
20
    Random_Class()
21
        : self{&vtable, this}
22
    {
23
    }
24
25
    virtual ~Random_Class();
26
    virtual tox_random_bytes_cb random_bytes = 0;
27
    virtual tox_random_uniform_cb random_uniform = 0;
28
};
29
30
/**
31
 * A very simple, fast, and deterministic PRNG just for testing.
32
 *
33
 * We generally don't want to use system_random(), since it's a
34
 * cryptographically secure PRNG and we don't need that in unit tests.
35
 */
36
class Test_Random : public Random_Class {
37
    std::minstd_rand lcg;
38
39
    void random_bytes(void *obj, uint8_t *bytes, uint32_t length) override;
40
    uint32_t random_uniform(void *obj, uint32_t upper_bound) override;
41
};
42
43
struct PublicKey : private std::array<uint8_t, CRYPTO_PUBLIC_KEY_SIZE> {
44
    using Base = std::array<uint8_t, CRYPTO_PUBLIC_KEY_SIZE>;
45
46
    using Base::begin;
47
    using Base::data;
48
    using Base::end;
49
    using Base::size;
50
    using Base::operator[];
51
52
    PublicKey() = default;
53
    explicit PublicKey(uint8_t const (&arr)[CRYPTO_PUBLIC_KEY_SIZE])
54
        : PublicKey(to_array(arr))
55
0
    {
56
0
    }
57
    explicit PublicKey(std::array<uint8_t, CRYPTO_PUBLIC_KEY_SIZE> const &arr)
58
2
    {
59
2
        std::copy(arr.begin(), arr.end(), begin());
60
2
    }
61
62
    PublicKey(std::initializer_list<uint8_t> const &arr)
63
    {
64
        std::copy(arr.begin(), arr.end(), begin());
65
    }
66
67
    Base const &base() const { return *this; }
68
};
69
70
inline bool operator!=(PublicKey const &pk1, PublicKey const &pk2)
71
{
72
    return pk1.base() != pk2.base();
73
}
74
75
inline bool operator==(PublicKey const &pk1, PublicKey const &pk2)
76
{
77
    return pk1.base() == pk2.base();
78
}
79
80
inline bool operator==(PublicKey::Base const &pk1, PublicKey const &pk2)
81
{
82
    return pk1 == pk2.base();
83
}
84
85
std::ostream &operator<<(std::ostream &out, PublicKey const &pk);
86
87
PublicKey random_pk(const Tox_Random *rng);
88
89
#endif  // C_TOXCORE_TOXCORE_CRYPTO_CORE_TEST_UTIL_H