rusk-profile 1.6.0

Utility crate to handle Rusk profile directories
Documentation
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
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
//
// Copyright (c) DUSK NETWORK. All rights reserved.

use std::fs::{self, File, read};
use std::io::prelude::*;
use std::io::{self, ErrorKind};
use std::path::PathBuf;

use blake3::Hasher;
use serde::{Deserialize, Serialize};
use tracing::info;
use version_check::Version;

use crate::{
    Theme, extension, file_name, file_stem, get_rusk_circuits_dir,
    get_rusk_keys_dir,
};

#[derive(Debug, Clone, PartialEq)]
pub struct Circuit {
    id: [u8; 32],
    id_str: String,
    circuit: Vec<u8>,
    metadata: Metadata,
}

#[derive(Default, Debug, Clone, PartialEq, Deserialize, Serialize)]
struct Metadata {
    plonk_version: Option<String>,
    name: Option<String>,
}

impl Circuit {
    /// Create a new [`Circuit`]
    pub fn new(
        circuit: Vec<u8>,
        plonk_version: String,
        name: Option<String>,
    ) -> io::Result<Self> {
        let id = compute_id(&circuit, &plonk_version)?;
        Ok(Self {
            id,
            id_str: hex::encode(id),
            circuit,
            metadata: Metadata {
                plonk_version: Some(plonk_version),
                name,
            },
        })
    }

    /// Attempt to create a new [`Circuit`] from local storage
    pub fn from_stored(id: [u8; 32]) -> io::Result<Self> {
        let mut file = get_rusk_circuits_dir()?;
        let id_str = hex::encode(id);
        file.push(&id_str);
        file.set_extension("cd");

        let circuit = match &file.exists() {
            true => read(file),
            false => {
                Err(io::Error::new(ErrorKind::NotFound, "Circuit not found"))
            }
        }?;

        let circuit = Self {
            id,
            id_str,
            circuit,
            metadata: Metadata::from_stored(&id)?,
        };

        if let Some(result) = circuit.check_id() {
            if !result {
                return Err(io::Error::new(
                    ErrorKind::InvalidData,
                    "The stored circuit id is incorrect",
                ));
            }
        }

        Ok(circuit)
    }

    /// Attempts to create a new [`Circuit`] from local storage by searching
    /// for the circuit name in the local toml files
    pub fn from_name(name: impl AsRef<str>) -> io::Result<Self> {
        let id = search_id(name.as_ref())?;
        Circuit::from_stored(id)
    }

    /// Checks whether [`Circuit::id`] is correct.
    ///
    /// Note: The check can only be performed when the plonk-version is stored
    /// as metadata in the [`Circuit`]
    pub fn check_id(&self) -> Option<bool> {
        match self.plonk_version() {
            None => None,
            Some(version) => {
                let computed_id = compute_id(self.circuit(), version)
                    .expect("plonk-version of a stored circuit to be valid");
                Some(computed_id == *self.id())
            }
        }
    }

    /// Stores the circuit description and circuit metadata (if there is
    /// metadata) or updates it if it exists but is different from the
    /// description in the struct
    pub fn store(&self) -> io::Result<()> {
        // store matadata
        self.metadata.update_or_store(&self.id)?;

        // store circuit
        let mut file = get_rusk_circuits_dir()?;
        file.push(self.id_str());
        let cd_file = file.with_extension("cd");
        File::create(&cd_file)?.write_all(&self.circuit)?;
        info!(
            "{}   {}",
            Theme::default().info("Cached"),
            file_name(&cd_file)
                .expect("At this point we know that the file is valid")
        );

        Ok(())
    }

    /// Returns the compressed circuit
    pub fn circuit(&self) -> &[u8] {
        &self.circuit
    }

    /// Returns the circuit id
    pub fn id(&self) -> &[u8; 32] {
        &self.id
    }

    /// Returns the circuit id in a hexadecimal string
    pub fn id_str(&self) -> &str {
        &self.id_str
    }

    /// Returns the circuit name if it exists, defaulting to the id string if
    /// not.
    pub fn name(&self) -> &str {
        self.metadata.name().unwrap_or(self.id_str())
    }

    /// Returns the plonk version of the metadata
    pub fn plonk_version(&self) -> Option<&str> {
        self.metadata.plonk_version.as_deref()
    }

    /// Returns the compressed circuit
    pub fn get_compressed(&self) -> &[u8] {
        &self.circuit
    }

    /// Fetches the prover key if stored in the keys directory
    pub fn get_prover(&self) -> io::Result<Vec<u8>> {
        let mut file = get_rusk_keys_dir()?;
        file.push(self.id_str());
        file.set_extension("pk");

        let pk = match &file.exists() {
            true => read(file),
            false => {
                Err(io::Error::new(ErrorKind::NotFound, "ProverKey not found"))
            }
        }?;

        Ok(pk)
    }

    /// Fetches the verifier data if stored in the keys directory
    pub fn get_verifier(&self) -> io::Result<Vec<u8>> {
        let mut file = get_rusk_keys_dir()?;
        file.push(self.id_str());
        file.set_extension("vd");

        let vd = match &file.exists() {
            true => read(file),
            false => Err(io::Error::new(
                ErrorKind::NotFound,
                "VerifierData not found",
            )),
        }?;

        Ok(vd)
    }

    /// Feches the prover key and verifier data if stored in the keys directory
    pub fn get_keys(&self) -> io::Result<(Vec<u8>, Vec<u8>)> {
        Ok((self.get_prover()?, self.get_verifier()?))
    }

    /// Stores the given prover key and verifier data
    pub fn add_keys(&self, pk: Vec<u8>, vd: Vec<u8>) -> io::Result<()> {
        let mut file = get_rusk_keys_dir()?;
        file.push(self.id_str());

        let pk_file = file.with_extension("pk");
        let vd_file = file.with_extension("vd");

        File::create(pk_file)?.write_all(&pk)?;
        File::create(vd_file)?.write_all(&vd)?;

        Ok(())
    }

    /// Cleans all stored files associated with the [`Circuit`]
    pub fn clean(&self) -> io::Result<()> {
        // collect all files with the circuit id as the file stem in circuits
        // directory
        let circuit_files: Vec<PathBuf> =
            fs::read_dir(get_rusk_circuits_dir()?)?
                .flatten()
                .map(|entry| entry.path())
                .filter(|file| file_stem(file) == Some(self.id_str()))
                .collect();

        for file in circuit_files {
            info!(
                "{}   /circuits/{}",
                Theme::default().warn("Removing"),
                file_name(&file).expect("file should be valid")
            );
            fs::remove_file(file)?;
        }

        // collect all files with the circuit id as the file stem in keys
        // directory
        let keys_files: Vec<PathBuf> = fs::read_dir(get_rusk_keys_dir()?)?
            .flatten()
            .map(|entry| entry.path())
            .filter(|file| file_stem(file) == Some(self.id_str()))
            .collect();

        for file in keys_files {
            info!(
                "{}   /keys/{}",
                Theme::default().warn("Removing"),
                file_name(&file).expect("file should be valid")
            );
            fs::remove_file(file)?;
        }
        Ok(())
    }
}

impl Metadata {
    /// Create new [`Metadata`]
    fn new(plonk_version: Option<String>, name: Option<String>) -> Self {
        Self {
            plonk_version,
            name,
        }
    }

    /// Attempt to create [`Metadata`] from local storage
    fn from_stored(id: &[u8; 32]) -> io::Result<Self> {
        let mut file = get_rusk_circuits_dir()?;
        file.push(hex::encode(id));
        file.set_extension("toml");

        Metadata::from_file(&file)
    }

    /// Attempt to create [`Metadata`] from a given file path
    fn from_file(file: &PathBuf) -> io::Result<Self> {
        let mut metadata = Metadata::new(None, None);
        if file.exists() {
            let content = read(file)?;
            let content =
                std::str::from_utf8(content.as_slice()).map_err(|e| {
                    io::Error::new(
                        ErrorKind::InvalidData,
                        format!(
                            "Couldn't read metadata for {:?}: {}",
                            file.file_name().expect("file exists"),
                            e
                        ),
                    )
                })?;
            metadata = toml::from_str(content).map_err(|e| {
                io::Error::new(
                    ErrorKind::InvalidData,
                    format!(
                        "Couldn't parse metadata for {:?}: {}",
                        file.file_name().expect("file exists"),
                        e
                    ),
                )
            })?;
        }
        Ok(metadata)
    }

    /// Return name
    fn name(&self) -> Option<&str> {
        self.name.as_deref()
    }

    /// Store the circuit metadata or updates it if it is different from the
    /// stored version
    fn update_or_store(&self, id: &[u8; 32]) -> io::Result<()> {
        let stored = Metadata::from_stored(id)?;

        if self != &stored {
            return self.add(id);
        }

        Ok(())
    }

    /// Stores the [`Metadata`] without perfoming any checks
    fn add(&self, id: &[u8; 32]) -> io::Result<()> {
        let mut file = get_rusk_circuits_dir()?;
        file.push(hex::encode(id));
        file.set_extension("toml");

        let toml = toml::to_string(self).map_err(|e| {
            io::Error::new(
                ErrorKind::InvalidData,
                format!("Couldn't create string from metadata: {e}"),
            )
        })?;
        File::create(&file)?.write_all(toml.as_bytes())?;

        Ok(())
    }
}

fn compute_id(circuit: &[u8], plonk_version: &str) -> io::Result<[u8; 32]> {
    // parse plonk version
    let (major, mut minor, _) = match Version::parse(plonk_version) {
        Some(v) => v.to_mmp(),
        None => {
            return Err(io::Error::new(
                ErrorKind::InvalidInput,
                format!("couldn't parse plonk version: {plonk_version}"),
            ));
        }
    };

    // ignore minor when major > 0
    if major > 0 {
        minor = 0;
    }

    // hash circuit description and plonk version to compute id
    let mut hasher = Hasher::new();
    hasher.update(circuit);
    hasher.update(&major.to_be_bytes());
    hasher.update(&minor.to_be_bytes());
    Ok(hasher.finalize().into())
}

fn search_id(name: &str) -> io::Result<[u8; 32]> {
    // gather all toml files with the correct metadata format that specify the
    // name we are looking for
    let circuits_dir = get_rusk_circuits_dir()?;
    let toml_files: Vec<PathBuf> = fs::read_dir(circuits_dir)?
        .flatten()
        .map(|entry| entry.path())
        // filter on "toml" extension
        .filter(|file| extension(file) == Some("toml"))
        // filter on correct name and fileformat
        .filter(|file| {
            let metadata = Metadata::from_file(file);
            match metadata {
                Err(_) => false,
                Ok(data) => match data.name {
                    Some(stored_name) => stored_name == name,
                    None => false,
                },
            }
        })
        .collect();

    // we are only continuing when we found exactly one file
    if toml_files.len() == 1 {
        let id_str = file_stem(&toml_files[0]).expect("file exists");
        let id = hex::decode(id_str).map_err(|e| {
            io::Error::new(
                ErrorKind::InvalidData,
                format!("Couldn't parse id from {id_str}: {e}"),
            )
        })?;

        // we are only continuing when the id is exactly 32 bytes long
        if id.len() == 32 {
            let mut buf = [0u8; 32];
            buf.copy_from_slice(&id[0..32]);
            return Ok(buf);
        }
    }

    Err(io::Error::new(
        ErrorKind::NotFound,
        format!("Couldn't find circuit id for {name}"),
    ))
}