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
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
//! Argon2 - Argon2 is a Key Derivation Function algorithm, winner of the Password Hashing Competition
//!
//! This is defined in [RFC9106](https://www.rfc-editor.org/rfc/rfc9106.txt) ([HTML](https://www.rfc-editor.org/rfc/rfc9106.html))
//!
//! The algorithm is defined by the following inputs and output:
//!
//! ```text
//! Function Argon2
//!    Inputs:
//!       password (P):       Bytes (0..2^32-1)    Password (or message) to be hashed
//!       salt (S):           Bytes (8..2^32-1)    Salt (16 bytes recommended for password hashing)
//!       parallelism (p):    Number (1..2^24-1)   Degree of parallelism (i.e. number of threads)
//!       tagLength (T):      Number (4..2^32-1)   Desired number of returned bytes
//!       memorySizeKB (m):   Number (8p..2^32-1)  Amount of memory (in kilo bytes) to use
//!       iterations (t):     Number (1..2^32-1)   Number of iterations to perform
//!       version (v):        Number (0x13)        The current version is 0x13 (19 decimal)
//!       key (K):            Bytes (0..2^32-1)    Optional key (Errata: PDF says 0..32 bytes, RFC says 0..232 bytes)
//!       associatedData (X): Bytes (0..2^32-1)    Optional arbitrary extra data
//!       hashType (y):       Number (0=Argon2d, 1=Argon2i, 2=Argon2id)
//!   Output:
//!       tag:                Bytes (tagLength)   The resulting generated bytes, tagLength bytes long
//! ```
//!
//! ## Usage
//!
//! ```
//! use cryptoxide::kdf::argon2;
//!
//! let output: [u8; 40] = argon2::argon2::<40>(&argon2::Params::argon2d(), b"my-password", b"saltsaltsaltsalt", b"", b"");
//! ```
//!
//! ## Notes
//!
//! The size of the salt is not verified, so this implementation can use invalid
//! salt that are out of the realm of expected value for this parameter. this
//! is left to the user, but the recommendation is to follow the expectation of salt length.
//!
//! The memory-kb parameter is automatically enforced to be at minimum, 8 times the level
//! of the parameter, so if a user chose an invalid memory-kb, the implementation
//! will automatically and silently override the parameter value.
//!
//! When comparing the ARGON2 tag, always use a constant time equality function.
//! Using non constant time equality could expose your software to timing
//! attack.
//!
//! This implementation doesn't provide support for the ARGON2 serialized string.
//! This is left to the user since the URL-like textual format might not be
//! appropriate in some settings and depending on context the user might want a
//! different format for the parameters (e.g. database text columns, etc).
//!

use crate::cryptoutil::xor_array64_mut;
use crate::hashing::blake2b;
use alloc::borrow::ToOwned;
use alloc::boxed::Box;
use alloc::vec;
use core::num::NonZeroU32;
use core::ops::{BitXorAssign, Index, IndexMut};

/// Parameters for argon2
///
/// use `Params::argon2d`, `Params::argon2i` or `Params::argon2id` to initialize
/// the structure for each possible variant of argon2, then use a builder type
/// setter to set the other parameters, typically:
///
/// ```
/// use cryptoxide::kdf::argon2;
///
/// let params = argon2::Params::argon2d()
///     .memory_kb(32)
///     .unwrap()
///     .iterations(3)
///     .unwrap()
///     .parallelism(4)
///     .unwrap();
/// ```
pub struct Params {
    parallelism: NonZeroU32,
    iterations: NonZeroU32,
    memory_kb: u32,
    version: u32,
    hash_type: Type,

    // -----------
    // calculated from parallelism and memory_kb
    // -----------
    memory_blocks: u32,
    segment_length: u32,
    lane_length: u32,
}

/// Possible type of parameters errors when setting values to the various parameters
#[derive(Clone, Copy, Debug)]
pub enum InvalidParam {
    /// At least 1 level of parallelism should be used
    ParallelismZero,
    /// Not more than 2^24-1 level of parallelism should be used
    ParallelismTooHigh,
    /// At least 1 iterations should be used
    IterationsZero,
    /// Unknown version, only supported version are `0x13` and `0x10`
    UnknownVersion,
    /// Memory requirement too high
    MemoryTooHigh,
}

impl Params {
    fn def(hash_type: Type) -> Self {
        Self {
            parallelism: NonZeroU32::new(1).unwrap(),
            iterations: NonZeroU32::new(1).unwrap(),
            memory_kb: 32,
            version: 0x13, // by default version = 19
            hash_type,
            memory_blocks: 32,
            segment_length: 8,
            lane_length: 32,
        }
    }

    /// Create a new ARGON2D parameters structure
    ///
    /// Other parameters are set to:
    /// * memory_kb=32kb
    /// * version=19
    /// * parallelism=1
    /// * iteration=1
    pub fn argon2d() -> Self {
        Params::def(Type::Argon2d)
    }

    /// Create a new ARGON2ID parameters structure
    ///
    /// Other parameters are set to:
    /// * memory_kb=32kb
    /// * version=19
    /// * parallelism=1
    /// * iteration=1
    pub fn argon2id() -> Self {
        Params::def(Type::Argon2id)
    }

    /// Create a new ARGON2I parameters structure
    ///
    /// Other parameters are set to:
    /// * memory_kb=32kb
    /// * version=19
    /// * parallelism=1
    /// * iteration=1
    pub fn argon2i() -> Self {
        Params::def(Type::Argon2i)
    }

    /// Set the memory_kb value to the value
    pub fn memory_kb(mut self, memory_kb: u32) -> Result<Self, InvalidParam> {
        self.memory_kb = memory_kb;
        self.parallelism_override_memory();
        Ok(self)
    }

    /// Set the parallelism value to the chosen value
    ///
    /// If the chosen value is not supported by argon2, then a failure is raised here
    pub fn parallelism(mut self, parallelism: u32) -> Result<Self, InvalidParam> {
        if parallelism >= 0x1000000 {
            return Err(InvalidParam::ParallelismTooHigh);
        }
        self.parallelism = NonZeroU32::new(parallelism).ok_or(InvalidParam::ParallelismZero)?;
        self.parallelism_override_memory();
        Ok(self)
    }

    /// Set the iterations value to the chosen value
    ///
    /// If the chosen value is not supported by argon2, then a failure is raised here
    pub fn iterations(mut self, iterations: u32) -> Result<Self, InvalidParam> {
        self.iterations = NonZeroU32::new(iterations).ok_or(InvalidParam::IterationsZero)?;
        Ok(self)
    }

    /// Set the version value to the chosen value
    ///
    /// Only version 19 (0x13) and 16 (0x10) are supported here, any other value
    /// will raise a failure.
    pub fn version(mut self, version: u32) -> Result<Self, InvalidParam> {
        if !(version == 0x13 || version == 0x10) {
            return Err(InvalidParam::UnknownVersion);
        }
        self.version = version;
        Ok(self)
    }

    // memory need to be at 8*parallelism minimum
    fn parallelism_override_memory(&mut self) {
        let mut memory_blocks = self.memory_kb;
        if memory_blocks < 8 * self.parallelism.get() {
            memory_blocks = 8 * self.parallelism.get();
            self.memory_kb = memory_blocks;
        }

        // memory_block is memory_kb rounded up to the parallelism level * 4
        self.segment_length = memory_blocks / (self.parallelism.get() * SYNC_POINTS);
        self.memory_blocks = self.segment_length * (self.parallelism.get() * SYNC_POINTS);
        self.lane_length = self.segment_length * SYNC_POINTS;
    }
}

const SYNC_POINTS: u32 = 4; // sync points per lanes

const BLOCK_SIZE_U64: usize = 128; // 1024 bytes in u64's
const BLOCK_SIZE: usize = BLOCK_SIZE_U64 * 8;

#[derive(Clone)]
struct Block([u64; BLOCK_SIZE_U64]);

impl Block {
    pub fn new() -> Block {
        Block([0u64; BLOCK_SIZE_U64])
    }

    pub fn as_u8(&self) -> &[u8] {
        let bytes: &[u8; BLOCK_SIZE] =
            unsafe { &*(&self.0 as *const [u64; BLOCK_SIZE_U64] as *const [u8; BLOCK_SIZE]) };
        bytes
    }

    pub fn as_u8_mut(&mut self) -> &mut [u8; BLOCK_SIZE] {
        let bytes: &mut [u8; BLOCK_SIZE] =
            unsafe { &mut *(&mut self.0 as *mut [u64; BLOCK_SIZE_U64] as *mut [u8; BLOCK_SIZE]) };
        bytes
    }
}

impl<'a> BitXorAssign<&'a Block> for Block {
    fn bitxor_assign(&mut self, rhs: &Block) {
        xor_array64_mut(&mut self.0, &rhs.0)
    }
}

impl Index<usize> for Block {
    type Output = u64;
    fn index(&self, index: usize) -> &u64 {
        &self.0[index]
    }
}

impl IndexMut<usize> for Block {
    fn index_mut(&mut self, index: usize) -> &mut u64 {
        &mut self.0[index]
    }
}

/// Structure representing the memory matrix.
struct Memory {
    lane_length: u32,
    blocks: Box<[Block]>,
}

impl Memory {
    /// number of elements per row (length of a lane)
    fn stride(&self) -> u32 {
        self.lane_length
    }

    fn new(params: &Params) -> Memory {
        let nb_blocks = params.parallelism.get() as usize * params.lane_length as usize;
        let blocks = vec![Block::new(); nb_blocks].into_boxed_slice();
        Memory {
            lane_length: params.lane_length,
            blocks,
        }
    }

    fn block_index(&self, index: u32) -> &Block {
        &self.blocks[index as usize]
    }

    fn block_index64(&self, index64: u64) -> &Block {
        &self.blocks[index64 as usize]
    }

    fn mut_block_index(&mut self, index: u32) -> &mut Block {
        &mut self.blocks[index as usize]
    }

    fn mut_block_at(&mut self, row: u32, col: u32) -> &mut Block {
        let pos = ((row as usize) * (self.lane_length as usize)) + (col as usize);
        &mut self.blocks[pos]
    }
}

// Position of the block currently being operated on.
#[derive(Clone, Debug)]
struct BlockPos {
    pass: u32,
    lane: u32,
    slice: u32,
    index: u32,
}

fn process(params: &Params, h0: &H0, memory: &mut Memory, out: &mut [u8]) {
    // Initializes the first 2 blocks (col=0, col=1) of memory for each rows (lane)
    for lane in 0..params.parallelism.get() {
        hprime_block_init(memory.mut_block_at(lane, 0).as_u8_mut(), &h0.0, 0, lane);
        hprime_block_init(memory.mut_block_at(lane, 1).as_u8_mut(), &h0.0, 1, lane);
    }
    // Fill all the blocks
    for pass in 0..params.iterations.get() {
        for slice in 0..SYNC_POINTS {
            for lane in 0..params.parallelism.get() {
                let position = BlockPos {
                    pass,
                    lane,
                    slice,
                    index: 0,
                };
                fill_segment(params, &position, memory);
            }
        }
    }

    // Calculates the final hash and return it.
    let mut blockhash = memory.block_index(memory.stride() - 1).clone();
    for l in 1..params.parallelism.get() {
        let last_block_in_lane = l * memory.stride() + (memory.stride() - 1);
        blockhash ^= memory.block_index(last_block_in_lane);
    }
    hprime(out, blockhash.as_u8());
}

fn fill_block(prev_block: &Block, ref_block: &Block, next_block: &mut Block, with_xor: bool) {
    let mut block_r = ref_block.clone();
    block_r ^= prev_block;
    let mut block_tmp = block_r.clone();

    if with_xor {
        block_tmp ^= next_block;
    }

    // Apply permutation row-wise
    for i in 0..8 {
        let mut v0 = block_r[16 * i];
        let mut v1 = block_r[16 * i + 1];
        let mut v2 = block_r[16 * i + 2];
        let mut v3 = block_r[16 * i + 3];
        let mut v4 = block_r[16 * i + 4];
        let mut v5 = block_r[16 * i + 5];
        let mut v6 = block_r[16 * i + 6];
        let mut v7 = block_r[16 * i + 7];
        let mut v8 = block_r[16 * i + 8];
        let mut v9 = block_r[16 * i + 9];
        let mut v10 = block_r[16 * i + 10];
        let mut v11 = block_r[16 * i + 11];
        let mut v12 = block_r[16 * i + 12];
        let mut v13 = block_r[16 * i + 13];
        let mut v14 = block_r[16 * i + 14];
        let mut v15 = block_r[16 * i + 15];

        p(
            &mut v0, &mut v1, &mut v2, &mut v3, &mut v4, &mut v5, &mut v6, &mut v7, &mut v8,
            &mut v9, &mut v10, &mut v11, &mut v12, &mut v13, &mut v14, &mut v15,
        );

        block_r[16 * i] = v0;
        block_r[16 * i + 1] = v1;
        block_r[16 * i + 2] = v2;
        block_r[16 * i + 3] = v3;
        block_r[16 * i + 4] = v4;
        block_r[16 * i + 5] = v5;
        block_r[16 * i + 6] = v6;
        block_r[16 * i + 7] = v7;
        block_r[16 * i + 8] = v8;
        block_r[16 * i + 9] = v9;
        block_r[16 * i + 10] = v10;
        block_r[16 * i + 11] = v11;
        block_r[16 * i + 12] = v12;
        block_r[16 * i + 13] = v13;
        block_r[16 * i + 14] = v14;
        block_r[16 * i + 15] = v15;
    }

    // Apply permutations column-wise
    for i in 0..8 {
        let mut v0 = block_r[2 * i];
        let mut v1 = block_r[2 * i + 1];
        let mut v2 = block_r[2 * i + 16];
        let mut v3 = block_r[2 * i + 17];
        let mut v4 = block_r[2 * i + 32];
        let mut v5 = block_r[2 * i + 33];
        let mut v6 = block_r[2 * i + 48];
        let mut v7 = block_r[2 * i + 49];
        let mut v8 = block_r[2 * i + 64];
        let mut v9 = block_r[2 * i + 65];
        let mut v10 = block_r[2 * i + 80];
        let mut v11 = block_r[2 * i + 81];
        let mut v12 = block_r[2 * i + 96];
        let mut v13 = block_r[2 * i + 97];
        let mut v14 = block_r[2 * i + 112];
        let mut v15 = block_r[2 * i + 113];

        p(
            &mut v0, &mut v1, &mut v2, &mut v3, &mut v4, &mut v5, &mut v6, &mut v7, &mut v8,
            &mut v9, &mut v10, &mut v11, &mut v12, &mut v13, &mut v14, &mut v15,
        );

        block_r[2 * i] = v0;
        block_r[2 * i + 1] = v1;
        block_r[2 * i + 16] = v2;
        block_r[2 * i + 17] = v3;
        block_r[2 * i + 32] = v4;
        block_r[2 * i + 33] = v5;
        block_r[2 * i + 48] = v6;
        block_r[2 * i + 49] = v7;
        block_r[2 * i + 64] = v8;
        block_r[2 * i + 65] = v9;
        block_r[2 * i + 80] = v10;
        block_r[2 * i + 81] = v11;
        block_r[2 * i + 96] = v12;
        block_r[2 * i + 97] = v13;
        block_r[2 * i + 112] = v14;
        block_r[2 * i + 113] = v15;
    }

    block_tmp.clone_into(next_block);
    *next_block ^= &block_r;
}

fn fill_segment(params: &Params, position: &BlockPos, memory: &mut Memory) {
    let mut position = position.clone();
    let data_independent_addressing = (params.hash_type == Type::Argon2i)
        || (params.hash_type == Type::Argon2id && position.pass == 0)
            && (position.slice < (SYNC_POINTS / 2));
    let zero_block = Block::new();
    let mut input_block = Block::new();
    let mut address_block = Block::new();

    if data_independent_addressing {
        input_block[0] = position.pass as u64;
        input_block[1] = position.lane as u64;
        input_block[2] = position.slice as u64;
        input_block[3] = params.memory_blocks as u64;
        input_block[4] = params.iterations.get() as u64;
        input_block[5] = params.hash_type as u64;
    }

    let mut starting_index = 0u32;

    if position.pass == 0 && position.slice == 0 {
        starting_index = 2;
        if data_independent_addressing {
            next_addresses(&mut address_block, &mut input_block, &zero_block);
        }
    }

    let mut curr_offset = (position.lane * memory.stride())
        + (position.slice * params.segment_length)
        + starting_index;

    // Last block in this lane
    let mut prev_offset = if curr_offset % memory.stride() == 0 {
        curr_offset + memory.stride() - 1
    } else {
        curr_offset - 1
    };

    let mut pseudo_rand;
    for i in starting_index..params.segment_length {
        // 1.1 Rotating prev_offset if needed
        if curr_offset % memory.stride() == 1 {
            prev_offset = curr_offset - 1;
        }

        // 1.2 Computing the index of the reference block
        // 1.2.1 Taking pseudo-random value from the previous block
        if data_independent_addressing {
            if i % 128 == 0 {
                next_addresses(&mut address_block, &mut input_block, &zero_block);
            }
            pseudo_rand = address_block[(i % 128) as usize];
        } else {
            pseudo_rand = memory.block_index(prev_offset)[0];
        }

        // 1.2.2 Computing the lane of the reference block
        // If (position.pass == 0) && (position.slice == 0): can not reference other lanes yet
        let ref_lane = if (position.pass == 0) && (position.slice == 0) {
            position.lane as u64
        } else {
            (pseudo_rand >> 32) % params.parallelism.get() as u64
        };

        // 1.2.3 Computing the number of possible reference block within the lane.
        position.index = i;
        let pseudo_rand_u32 = (pseudo_rand & 0xffff_ffff) as u32;
        let same_lane = ref_lane == (position.lane as u64);
        let ref_index = index_alpha(params, &position, pseudo_rand_u32, same_lane);

        // 2 Creating a new block
        let index = params.lane_length as u64 * ref_lane + ref_index as u64;
        let mut curr_block = memory.block_index(curr_offset).clone();

        let prev_block = memory.block_index(prev_offset);
        let ref_block = memory.block_index64(index);
        let with_xor = !(params.version == 0x10 || position.pass == 0);
        fill_block(prev_block, ref_block, &mut curr_block, with_xor);

        *memory.mut_block_index(curr_offset) = curr_block;
        curr_offset += 1;
        prev_offset += 1;
    }
}

/// compute the output hash for a variable length output hash.
///
/// if the output expected is more than 64 bytes, then it is just a simple BLAKE2 hash,
/// but when we need to produce more than 64 bytes, it is computed at most 64 bytes at a time and
/// by hashing repeatdly the current context
///
/// initial hash : V0 = H(LE32(OUTPUT_LEN) | input);
fn hprime(output: &mut [u8], input: &[u8]) {
    if output.len() <= 64 {
        blake2b::ContextDyn::new(output.len())
            .update(&(output.len() as u32).to_le_bytes())
            .update(&input)
            .finalize_at(output);
        return;
    }

    let output_len = output.len();

    let v0 = blake2b::Context::<512>::new()
        .update(&(output_len as u32).to_le_bytes())
        .update(input)
        .finalize();
    output[0..32].copy_from_slice(&v0[0..32]);
    let mut bytes = output_len - 32;
    let mut pos = 32;

    let mut vi_prev = v0;
    while bytes > 64 {
        blake2b::Context::<512>::new()
            .update(&vi_prev)
            .finalize_at(&mut vi_prev);
        output[pos..pos + 32].copy_from_slice(&vi_prev[0..32]);

        bytes -= 32;
        pos += 32;
    }

    blake2b::ContextDyn::new(bytes)
        .update(&vi_prev)
        .finalize_at(&mut output[pos..pos + bytes]);
}

/// Variant of hprime specialized for 1024 bytes block initialization from h0 || U32LE(col) || U32LE(lane)
fn hprime_block_init(output: &mut [u8; 1024], h0: &[u8; 64], col: u32, lane: u32) {
    let v0 = blake2b::Context::<512>::new()
        .update(&1024u32.to_le_bytes())
        .update(h0)
        .update(&u32::to_le_bytes(col))
        .update(&u32::to_le_bytes(lane))
        .finalize();
    output[0..32].copy_from_slice(&v0[0..32]);
    let mut pos = 32;

    let mut vi_prev = v0;
    // 28 partial 32-bytes generation
    for _ in 0..29 {
        blake2b::Context::<512>::new()
            .update(&vi_prev)
            .finalize_at(&mut vi_prev);
        output[pos..pos + 32].copy_from_slice(&vi_prev[0..32]);
        pos += 32;
    }

    blake2b::Context::<512>::new()
        .update(&vi_prev)
        .finalize_at(&mut output[pos..pos + 64]);
}

fn index_alpha(params: &Params, position: &BlockPos, pseudo_rand: u32, same_lane: bool) -> u32 {
    let reference_area_size = if position.pass == 0 {
        if position.slice == 0 {
            position.index - 1
        } else if same_lane {
            position.slice * params.segment_length + position.index - 1
        } else if position.index == 0 {
            position.slice * params.segment_length - 1
        } else {
            position.slice * params.segment_length
        }
    } else {
        // other passes
        if same_lane {
            params.lane_length - params.segment_length + position.index - 1
        } else if position.index == 0 {
            params.lane_length - params.segment_length - 1
        } else {
            params.lane_length - params.segment_length
        }
    };
    let reference_area_size = reference_area_size as u64;
    let mut relative_position = pseudo_rand as u64;
    relative_position = (relative_position * relative_position) >> 32;
    relative_position = reference_area_size - 1 - ((reference_area_size * relative_position) >> 32);

    // 1.2.5 Computing starting position
    let start_position = if position.pass != 0 {
        if position.slice == SYNC_POINTS - 1 {
            0u32
        } else {
            (position.slice + 1) * params.segment_length
        }
    } else {
        0u32
    };

    // 1.2.6. Computing absolute position
    ((start_position as u64 + relative_position) % params.lane_length as u64) as u32
}

fn next_addresses(address_block: &mut Block, input_block: &mut Block, zero_block: &Block) {
    input_block[6] += 1;
    fill_block(zero_block, input_block, address_block, false);
    fill_block(zero_block, &address_block.clone(), address_block, false);
}

/// permutation P
fn p(
    v0: &mut u64,
    v1: &mut u64,
    v2: &mut u64,
    v3: &mut u64,
    v4: &mut u64,
    v5: &mut u64,
    v6: &mut u64,
    v7: &mut u64,
    v8: &mut u64,
    v9: &mut u64,
    v10: &mut u64,
    v11: &mut u64,
    v12: &mut u64,
    v13: &mut u64,
    v14: &mut u64,
    v15: &mut u64,
) {
    // The modular additions in GB are combined with 64-bit multiplications. Multiplications are the
    // only difference from the original BLAKE2b design. This choice is done to increase the circuit
    // depth and thus the running time of ASIC implementations, while having roughly the same
    // running time on CPUs thanks to parallelism and pipelining.
    #[inline]
    fn add_and_mul(x: u64, y: u64) -> u64 {
        let xy = (x & 0xffff_ffff) * (y & 0xffff_ffff);
        x.wrapping_add(y.wrapping_add(xy << 1))
    }

    fn gb(a: &mut u64, b: &mut u64, c: &mut u64, d: &mut u64) {
        *a = add_and_mul(*a, *b);
        *d = (*d ^ *a).rotate_right(32);
        *c = add_and_mul(*c, *d);
        *b = (*b ^ *c).rotate_right(24);
        *a = add_and_mul(*a, *b);
        *d = (*d ^ *a).rotate_right(16);
        *c = add_and_mul(*c, *d);
        *b = (*b ^ *c).rotate_right(63);
    }

    gb(v0, v4, v8, v12);
    gb(v1, v5, v9, v13);
    gb(v2, v6, v10, v14);
    gb(v3, v7, v11, v15);
    gb(v0, v5, v10, v15);
    gb(v1, v6, v11, v12);
    gb(v2, v7, v8, v13);
    gb(v3, v4, v9, v14);
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u32)]
enum Type {
    Argon2d = 0,
    Argon2i = 1,
    Argon2id = 2,
}

/// Initial H value for Argon2
///
/// It's recommended to use only the `argon2` function directly, but
/// this allow to disassociate the chosen arguments (password, salt, aad),
/// from the computationally and memory intensive tasks that argon2 go
/// through to derive the final result.
#[derive(Clone)]
pub struct H0([u8; 64]);

impl H0 {
    pub fn new(
        params: &Params,
        password: &[u8],
        salt: &[u8],
        key: &[u8],
        aad: &[u8],
        tag_length: u32,
    ) -> Self {
        let h0 = blake2b::Context::<512>::new()
            .update(&params.parallelism.get().to_le_bytes())
            .update(&tag_length.to_le_bytes())
            .update(&params.memory_kb.to_le_bytes())
            .update(&params.iterations.get().to_le_bytes())
            .update(&params.version.to_le_bytes())
            .update(&(params.hash_type as u32).to_le_bytes())
            .update(&u32::to_le_bytes(password.len() as u32))
            .update(password)
            .update(&u32::to_le_bytes(salt.len() as u32))
            .update(salt)
            .update(&u32::to_le_bytes(key.len() as u32))
            .update(key)
            .update(&u32::to_le_bytes(aad.len() as u32))
            .update(aad)
            .finalize();
        Self(h0)
    }
}

/// Generate the ARGON2 output into a mutable output slice, from the parameters, password, salt, key and AAD
pub fn argon2_at(
    params: &Params,
    password: &[u8],
    salt: &[u8],
    key: &[u8],
    aad: &[u8],
    tag: &mut [u8],
) {
    let h0 = H0::new(&params, password, salt, key, aad, tag.len() as u32);
    let mut memory = Memory::new(params);
    process(&params, &h0, &mut memory, tag);
}

/// Generate the ARGON2 output from the parameters, password, salt, key and AAD
pub fn argon2<const T: usize>(
    params: &Params,
    password: &[u8],
    salt: &[u8],
    key: &[u8],
    aad: &[u8],
) -> [u8; T] {
    let mut tag = [0u8; T];
    let h0 = H0::new(&params, password, salt, key, aad, T as u32);
    let mut memory = Memory::new(params);
    process(&params, &h0, &mut memory, &mut tag);
    tag
}

#[cfg(test)]
mod tests {
    use super::*;

    // test vectors from
    // https://www.rfc-editor.org/rfc/rfc9106.html

    fn rfc9106_params(params: Params) -> Params {
        params
            .memory_kb(32)
            .unwrap()
            .iterations(3)
            .unwrap()
            .parallelism(4)
            .unwrap()
    }

    fn run_std(params: Params, expected: &[u8; 32]) {
        let params = rfc9106_params(params);
        let tag = argon2(&params, &[0x01; 32], &[0x02; 16], &[0x03; 8], &[0x04; 12]);

        assert_eq!(*expected, tag, "expected tag failed")
    }

    #[test]
    fn argon2d_rfc9106() {
        const EXPECTED: [u8; 32] = [
            0x51, 0x2b, 0x39, 0x1b, 0x6f, 0x11, 0x62, 0x97, 0x53, 0x71, 0xd3, 0x09, 0x19, 0x73,
            0x42, 0x94, 0xf8, 0x68, 0xe3, 0xbe, 0x39, 0x84, 0xf3, 0xc1, 0xa1, 0x3a, 0x4d, 0xb9,
            0xfa, 0xbe, 0x4a, 0xcb,
        ];
        run_std(Params::argon2d(), &EXPECTED)
    }

    #[test]
    fn argon2i_rfc9106() {
        const EXPECTED: [u8; 32] = [
            0xc8, 0x14, 0xd9, 0xd1, 0xdc, 0x7f, 0x37, 0xaa, 0x13, 0xf0, 0xd7, 0x7f, 0x24, 0x94,
            0xbd, 0xa1, 0xc8, 0xde, 0x6b, 0x01, 0x6d, 0xd3, 0x88, 0xd2, 0x99, 0x52, 0xa4, 0xc4,
            0x67, 0x2b, 0x6c, 0xe8,
        ];
        run_std(Params::argon2i(), &EXPECTED)
    }

    #[test]
    fn argon2id_rfc9106() {
        const EXPECTED: [u8; 32] = [
            0x0d, 0x64, 0x0d, 0xf5, 0x8d, 0x78, 0x76, 0x6c, 0x08, 0xc0, 0x37, 0xa3, 0x4a, 0x8b,
            0x53, 0xc9, 0xd0, 0x1e, 0xf0, 0x45, 0x2d, 0x75, 0xb6, 0x5e, 0xb5, 0x25, 0x20, 0xe9,
            0x6b, 0x01, 0xe6, 0x59,
        ];
        run_std(Params::argon2id(), &EXPECTED);
    }
}