Files
ahash
aho_corasick
ansi_term
anyhow
atty
bech32
bincode
bit_set
bit_vec
bitcoin
bitcoin_hashes
bitflags
cfg_if
clap
convert_case
core2
crunchy
cryptoxide
enum_primitive
fancy_regex
hashbrown
hex
hex_literal
itoa
libc
libloading
memchr
num
num_bigint
num_complex
num_integer
num_iter
num_rational
num_traits
ordered_float
paste
proc_macro2
proc_macro_error
proc_macro_error_attr
qimalloc
quote
regex
regex_syntax
remain
rust_ssvm
ryu
secp256k1
secp256k1_sys
serde
serde_derive
serde_json
serde_value
sewup
sewup_derive
ss_ewasm_api
ssvm_evmc_client
ssvm_evmc_sys
strsim
syn
textwrap
thiserror
thiserror_impl
tiny_keccak
toml
unicode_width
unicode_xid
vec_map
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
#![allow(clippy::cast_ptr_alignment)]

#[cfg(target_arch = "x86")]
use core::arch::x86::*;

#[cfg(target_arch = "x86_64")]
use core::arch::x86_64::*;

use core::convert::TryInto;

#[derive(Clone)]
pub(crate) struct State {
    a: __m128i,
    b: __m128i,
    c: __m128i,
    d: __m128i,
}

#[repr(align(16))]
pub struct Align128([u32; 4]);

impl Align128 {
    pub fn zero() -> Self {
        Self([0u32; 4])
    }

    #[inline]
    fn to_m128i(&self) -> __m128i {
        unsafe { _mm_load_si128(self.0.as_ptr() as *const __m128i) }
    }

    #[inline]
    fn from_m128i(&mut self, v: __m128i) {
        unsafe { _mm_store_si128(self.0.as_mut_ptr() as *mut __m128i, v) }
    }
}

macro_rules! swizzle {
    ($b: expr, $c: expr, $d: expr) => {
        $b = _mm_shuffle_epi32($b, 0b00111001); // <<< 8
        $c = _mm_shuffle_epi32($c, 0b01001110); // <<< 16
        $d = _mm_shuffle_epi32($d, 0b10010011); // <<< 24
    };
}

macro_rules! add_rotate_xor {
    ($a: expr, $b: expr, $c: expr, $d: expr) => {
        // a += b; c ^= a; c <<<= d;
        $a = _mm_add_epi32($a, $b);
        $c = _mm_xor_si128($c, $a);
        $c = _mm_xor_si128(_mm_slli_epi32($c, $d), _mm_srli_epi32($c, 32 - $d));
    };
}

macro_rules! round {
    ($a: expr, $b: expr, $c: expr, $d: expr) => {
        add_rotate_xor!($a, $b, $d, 16);
        add_rotate_xor!($c, $d, $b, 12);
        add_rotate_xor!($a, $b, $d, 8);
        add_rotate_xor!($c, $d, $b, 7);
    };
}

impl State {
    // state initialization constant le-32bit array of b"expand 16-byte k"
    const CST16: [u32; 4] = [0x61707865, 0x3120646e, 0x79622d36, 0x6b206574];

    // state initialization constant le-32bit array of b"expand 32-byte k"
    const CST32: [u32; 4] = [0x61707865, 0x3320646e, 0x79622d32, 0x6b206574];

    // state is initialized to the following 32 bits elements:
    // C1 C2 C3 C4
    // K1 K2 K3 K4
    // K1 K2 K3 K4 (16 bytes key) or K5 K6 K7 K8 (32 bytes keys)
    // N1 N2 N3 N4 (16 bytes nonce) or 0 N1 N2 N3 (12 bytes nonce) or 0 0 N1 N2 (8 bytes nonce)

    #[inline]
    unsafe fn constant32() -> __m128i {
        _mm_loadu_si128(Self::CST32.as_ptr() as *const __m128i)
    }

    #[inline]
    unsafe fn constant16() -> __m128i {
        _mm_loadu_si128(Self::CST16.as_ptr() as *const __m128i)
    }

    #[inline]
    fn key32(key: &[u8]) -> (__m128i, __m128i, __m128i) {
        let k = key.as_ptr();
        unsafe {
            (
                Self::constant32(),
                _mm_loadu_si128(k as *const __m128i),
                _mm_loadu_si128(k.add(16) as *const __m128i),
            )
        }
    }

    #[inline]
    fn key16(key: &[u8]) -> (__m128i, __m128i, __m128i) {
        let k = unsafe { _mm_loadu_si128(key.as_ptr() as *const __m128i) };
        (unsafe { Self::constant16() }, k, k)
    }

    #[inline]
    fn nonce(nonce: &[u8]) -> __m128i {
        if nonce.len() == 16 {
            unsafe { _mm_loadu_si128(nonce.as_ptr() as *const __m128i) }
        } else {
            let mut n = Align128::zero();
            if nonce.len() == 12 {
                n.0[1] = u32::from_le_bytes(nonce[0..4].try_into().unwrap());
                n.0[2] = u32::from_le_bytes(nonce[4..8].try_into().unwrap());
                n.0[3] = u32::from_le_bytes(nonce[8..12].try_into().unwrap());
                n.to_m128i()
            } else if nonce.len() == 8 {
                n.0[2] = u32::from_le_bytes(nonce[0..4].try_into().unwrap());
                n.0[3] = u32::from_le_bytes(nonce[4..8].try_into().unwrap());
                n.to_m128i()
            } else {
                unreachable!()
            }
        }
    }

    /// Initialize the state with key and nonce
    pub(crate) fn init(key: &[u8], nonce: &[u8]) -> Self {
        let (a, b, c) = match key.len() {
            32 => Self::key32(key),
            16 => Self::key16(key),
            _ => unreachable!(),
        };
        let d = Self::nonce(nonce);
        Self { a, b, c, d }
    }

    #[inline]
    pub(crate) fn round20(&mut self) {
        unsafe {
            for _ in 0..10 {
                round!(self.a, self.b, self.c, self.d);
                swizzle!(self.b, self.c, self.d);
                round!(self.a, self.b, self.c, self.d);
                swizzle!(self.d, self.c, self.b);
            }
        }
    }

    #[inline]
    pub(crate) fn increment(&mut self) {
        let mut align = Align128::zero();
        align.from_m128i(self.d);
        let (a, overflowed) = align.0[0].overflowing_add(1);
        if overflowed {
            align.0[1] = align.0[1].wrapping_add(1);
        }
        align.0[0] = a;
        self.d = align.to_m128i();
    }

    #[inline]
    /// Add back the initial state
    pub(crate) fn add_back(&mut self, initial: &Self) {
        unsafe {
            self.a = _mm_add_epi32(self.a, initial.a);
            self.b = _mm_add_epi32(self.b, initial.b);
            self.c = _mm_add_epi32(self.c, initial.c);
            self.d = _mm_add_epi32(self.d, initial.d);
        }
    }

    #[inline]
    pub(crate) fn output_bytes(&self, output: &mut [u8]) {
        #[allow(clippy::cast_ptr_alignment)]
        let o = output.as_mut_ptr() as *mut __m128i;
        unsafe {
            _mm_storeu_si128(o, self.a);
            _mm_storeu_si128(o.add(1), self.b);
            _mm_storeu_si128(o.add(2), self.c);
            _mm_storeu_si128(o.add(3), self.d);
        }
    }

    #[inline]
    pub(crate) fn output_ad_bytes(&self, output: &mut [u8; 32]) {
        #[allow(clippy::cast_ptr_alignment)]
        let o = output.as_mut_ptr() as *mut __m128i;
        unsafe {
            _mm_storeu_si128(o, self.a);
            _mm_storeu_si128(o.add(1), self.d);
        }
    }
}

mod test {
    /*
    use super::super::reference;
    use super::*;

    fn assert_state_equivalent(doing: &'static str, refere: &reference::State, sse: &State) {
        let mut output1 = [0u8; 64];
        let mut output2 = [0u8; 64];
        sse.output_bytes(&mut output1);
        refere.output_bytes(&mut output2);

        assert_eq!(&output1[0..], &output2[0..], "doing: {}", doing);
    }

    #[test]
    pub fn test_same_ref() {
        let key = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15];
        let nonce = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15];

        let st_initial = State::init(&key, &nonce);
        let r_initial = reference::State::init(&key, &nonce);

        let mut st = st_initial.clone();
        let mut r = r_initial.clone();

        assert_state_equivalent("init", &r, &st);

        st.round20();
        r.round20();

        assert_state_equivalent("round", &r, &st);

        st.add_back(&st_initial);
        r.add_back(&r_initial);

        assert_state_equivalent("add_back", &r, &st);

        st.increment();
        r.increment();

        assert_state_equivalent("increment", &r, &st);
    }
    */
}