tor_hscrypto/pow/v1/
challenge.rs1use crate::pow::v1::{
8 err::SolutionErrorV1, types::Effort, types::Instance, types::NONCE_LEN, types::Nonce,
9 types::SEED_LEN, types::Seed,
10};
11use arrayvec::{ArrayVec, CapacityError};
12use blake2::{Blake2b, Digest, digest::consts::U4};
13
14const P_STRING: &[u8] = b"Tor hs intro v1\0";
20
21const P_STRING_LEN: usize = 16;
23
24const ID_LEN: usize = 32;
26
27const SEED_OFFSET: usize = P_STRING_LEN + ID_LEN;
29
30const NONCE_OFFSET: usize = SEED_OFFSET + SEED_LEN;
32
33const EFFORT_OFFSET: usize = NONCE_OFFSET + NONCE_LEN;
35
36const EFFORT_LEN: usize = 4;
38
39const CHALLENGE_LEN: usize = EFFORT_OFFSET + EFFORT_LEN;
41
42#[derive(derive_more::AsRef, Debug, Clone, Eq, PartialEq)]
47pub(super) struct Challenge([u8; CHALLENGE_LEN]);
48
49impl Challenge {
50 pub(super) fn new(instance: &Instance, effort: Effort, nonce: &Nonce) -> Self {
55 let mut result = ArrayVec::<u8, CHALLENGE_LEN>::new();
56 (|| -> Result<(), CapacityError> {
57 result.try_extend_from_slice(P_STRING)?;
58 result.try_extend_from_slice(instance.service().as_ref())?;
59 assert_eq!(result.len(), SEED_OFFSET);
60 result.try_extend_from_slice(instance.seed().as_ref())?;
61 assert_eq!(result.len(), NONCE_OFFSET);
62 result.try_extend_from_slice(nonce.as_ref())?;
63 assert_eq!(result.len(), EFFORT_OFFSET);
64 result.try_extend_from_slice(&effort.as_ref().to_be_bytes())
65 })()
66 .expect("CHALLENGE_LEN holds a full challenge string");
67 Self(
68 result
69 .into_inner()
70 .expect("challenge buffer is fully written"),
71 )
72 }
73
74 pub(super) fn seed(&self) -> Seed {
76 let array: [u8; SEED_LEN] = self.0[SEED_OFFSET..(SEED_OFFSET + SEED_LEN)]
77 .try_into()
78 .expect("slice length correct");
79 array.into()
80 }
81
82 pub(super) fn nonce(&self) -> Nonce {
84 let array: [u8; NONCE_LEN] = self.0[NONCE_OFFSET..(NONCE_OFFSET + NONCE_LEN)]
85 .try_into()
86 .expect("slice length correct");
87 array.into()
88 }
89
90 pub(super) fn effort(&self) -> Effort {
92 u32::from_be_bytes(
93 self.0[EFFORT_OFFSET..(EFFORT_OFFSET + EFFORT_LEN)]
94 .try_into()
95 .expect("slice length correct"),
96 )
97 .into()
98 }
99
100 pub(super) fn increment_nonce(&mut self) {
107 fn inc_le_bytes(slice: &mut [u8]) {
109 for byte in slice {
110 let (value, overflow) = (*byte).overflowing_add(1);
111 *byte = value;
112 if !overflow {
113 break;
114 }
115 }
116 }
117 inc_le_bytes(&mut self.0[NONCE_OFFSET..(NONCE_OFFSET + NONCE_LEN)]);
118 }
119
120 pub(super) fn check_effort(
128 &self,
129 proof: &equix::SolutionByteArray,
130 ) -> Result<(), SolutionErrorV1> {
131 let mut hasher = Blake2b::<U4>::new();
132 hasher.update(self.as_ref());
133 hasher.update(proof.as_ref());
134 let value = u32::from_be_bytes(hasher.finalize().into());
135 match value.checked_mul(*self.effort().as_ref()) {
136 Some(_) => Ok(()),
137 None => Err(SolutionErrorV1::Effort),
138 }
139 }
140}