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
use std::collections::HashMap;

use crate::SignatureError;
use poseidon::POSEIDON;
use signature::Verifier;
use sui_sdk_types::types::Claim;
use sui_sdk_types::types::Jwk;
use sui_sdk_types::types::JwkId;
use sui_sdk_types::types::UserSignature;
use sui_sdk_types::types::ZkLoginAuthenticator;
use sui_sdk_types::types::ZkLoginInputs;

mod poseidon;
mod verify;

#[cfg(test)]
mod tests;

pub struct ZkloginVerifier {
    proof_verifying_key: verify::VerifyingKey,
    jwks: HashMap<JwkId, Jwk>,
}

impl ZkloginVerifier {
    fn new(proof_verifying_key: verify::VerifyingKey) -> Self {
        Self {
            proof_verifying_key,
            jwks: Default::default(),
        }
    }

    pub fn new_mainnet() -> Self {
        Self::new(verify::VerifyingKey::new_mainnet())
    }

    pub fn new_dev() -> Self {
        Self::new(verify::VerifyingKey::new_dev())
    }

    pub fn jwks(&self) -> &HashMap<JwkId, Jwk> {
        &self.jwks
    }

    pub fn jwks_mut(&mut self) -> &mut HashMap<JwkId, Jwk> {
        &mut self.jwks
    }
}

impl Verifier<ZkLoginAuthenticator> for ZkloginVerifier {
    fn verify(
        &self,
        message: &[u8],
        signature: &ZkLoginAuthenticator,
    ) -> Result<(), SignatureError> {
        // 1. check that we have a valid corrisponding Jwk
        let jwt_details = JwtDetails::from_zklogin_inputs(&signature.inputs)?;
        let jwk = self.jwks.get(&jwt_details.id).ok_or_else(|| {
            SignatureError::from_source(format!(
                "unable to find corrisponding jwk with id '{:?}' for provided authenticator",
                jwt_details.id
            ))
        })?;

        // 2. verify that the provided SimpleSignature is valid
        crate::simple::SimpleVerifier.verify(message, &signature.signature)?;

        // 3. verify groth16 proof
        self.proof_verifying_key.verify_zklogin(
            jwk,
            &signature.inputs,
            &signature.signature,
            signature.max_epoch,
        )
    }
}

impl Verifier<UserSignature> for ZkloginVerifier {
    fn verify(&self, message: &[u8], signature: &UserSignature) -> Result<(), SignatureError> {
        let UserSignature::ZkLogin(zklogin_authenticator) = signature else {
            return Err(SignatureError::from_source("not a zklogin signature"));
        };

        self.verify(message, zklogin_authenticator.as_ref())
    }
}

/// A structed of parsed JWT details, consists of kid, header, iss.
#[derive(Debug, Clone, PartialEq, Eq)]
struct JwtDetails {
    header: JwtHeader,
    id: JwkId,
}

impl JwtDetails {
    fn from_zklogin_inputs(inputs: &ZkLoginInputs) -> Result<Self, SignatureError> {
        const ISS: &str = "iss";

        let header = JwtHeader::from_base64(&inputs.header_base64)?;
        let id = JwkId {
            iss: verify_extended_claim(&inputs.iss_base64_details, ISS)?,
            kid: header.kid.clone(),
        };
        Ok(JwtDetails { header, id })
    }
}

/// Struct that represents a standard JWT header according to
/// https://openid.net/specs/openid-connect-core-1_0.html
#[derive(Debug, Clone, PartialEq, Eq)]
struct JwtHeader {
    alg: String,
    kid: String,
    typ: Option<String>,
}

impl JwtHeader {
    fn from_base64(s: &str) -> Result<Self, SignatureError> {
        use base64ct::Base64UrlUnpadded;
        use base64ct::Encoding;

        #[derive(serde_derive::Serialize, serde_derive::Deserialize)]
        struct Header {
            alg: String,
            kid: String,
            #[serde(skip_serializing_if = "Option::is_none")]
            typ: Option<String>,
        }

        let header_bytes = Base64UrlUnpadded::decode_vec(s)
            .map_err(|e| SignatureError::from_source(e.to_string()))?;
        let Header { alg, kid, typ } =
            serde_json::from_slice(&header_bytes).map_err(SignatureError::from_source)?;
        if alg != "RS256" {
            return Err(SignatureError::from_source("jwt alg must be RS256"));
        }
        Ok(Self { alg, kid, typ })
    }
}

/// Parse the extended claim json value to its claim value, using the expected claim key.
fn verify_extended_claim(claim: &Claim, expected_key: &str) -> Result<String, SignatureError> {
    /// Map a base64 string to a bit array by taking each char's index and convert it to binary form with one bit per u8
    /// element in the output. Returns SignatureError if one of the characters is not in the base64 charset.
    fn base64_to_bitarray(input: &str) -> Result<Vec<u8>, SignatureError> {
        use itertools::Itertools;

        const BASE64_URL_CHARSET: &str =
            "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";

        input
            .chars()
            .map(|c| {
                BASE64_URL_CHARSET
                    .find(c)
                    .map(|index| index as u8)
                    .map(|index| (0..6).rev().map(move |i| index >> i & 1))
                    .ok_or_else(|| SignatureError::from_source("base64_to_bitarry invalid input"))
            })
            .flatten_ok()
            .collect()
    }

    /// Convert a bitarray (each bit is represented by a u8) to a byte array by taking each 8 bits as a
    /// byte in big-endian format.
    fn bitarray_to_bytearray(bits: &[u8]) -> Result<Vec<u8>, SignatureError> {
        if bits.len() % 8 != 0 {
            return Err(SignatureError::from_source(
                "bitarray_to_bytearray invalid input",
            ));
        }
        Ok(bits
            .chunks(8)
            .map(|chunk| {
                let mut byte = 0u8;
                for (i, bit) in chunk.iter().rev().enumerate() {
                    byte |= bit << i;
                }
                byte
            })
            .collect())
    }

    /// Parse the base64 string, add paddings based on offset, and convert to a bytearray.
    fn decode_base64_url(s: &str, index_mod_4: &u8) -> Result<String, SignatureError> {
        if s.len() < 2 {
            return Err(SignatureError::from_source("Base64 string smaller than 2"));
        }
        let mut bits = base64_to_bitarray(s)?;
        match index_mod_4 {
            0 => {}
            1 => {
                bits.drain(..2);
            }
            2 => {
                bits.drain(..4);
            }
            _ => {
                return Err(SignatureError::from_source("Invalid first_char_offset"));
            }
        }

        let last_char_offset = (index_mod_4 + s.len() as u8 - 1) % 4;
        match last_char_offset {
            3 => {}
            2 => {
                bits.drain(bits.len() - 2..);
            }
            1 => {
                bits.drain(bits.len() - 4..);
            }
            _ => {
                return Err(SignatureError::from_source("Invalid last_char_offset"));
            }
        }

        if bits.len() % 8 != 0 {
            return Err(SignatureError::from_source("Invalid bits length"));
        }

        Ok(std::str::from_utf8(&bitarray_to_bytearray(&bits)?)
            .map_err(|_| SignatureError::from_source("Invalid UTF8 string"))?
            .to_owned())
    }

    let extended_claim = decode_base64_url(&claim.value, &claim.index_mod_4)?;

    // Last character of each extracted_claim must be '}' or ','
    if !(extended_claim.ends_with('}') || extended_claim.ends_with(',')) {
        return Err(SignatureError::from_source("Invalid extended claim"));
    }

    let json_str = format!("{{{}}}", &extended_claim[..extended_claim.len() - 1]);

    serde_json::from_str::<serde_json::Value>(&json_str)
        .map_err(SignatureError::from_source)?
        .as_object_mut()
        .and_then(|o| o.get_mut(expected_key))
        .map(serde_json::Value::take)
        .and_then(|v| match v {
            serde_json::Value::String(s) => Some(s),
            _ => None,
        })
        .ok_or_else(|| SignatureError::from_source("invalid extended claim"))
}

pub(crate) fn zklogin_identifier_from_inputs(
    inputs: &ZkLoginInputs,
) -> Result<sui_sdk_types::types::ZkLoginPublicIdentifier, SignatureError> {
    const ISS: &str = "iss";

    let iss = verify_extended_claim(&inputs.iss_base64_details, ISS)?;
    sui_sdk_types::types::ZkLoginPublicIdentifier::new(iss, inputs.address_seed.clone())
        .ok_or_else(|| SignatureError::from_source("invalid iss"))
}