snops 0.1.0

The snarkops control plane responsible for managing environments and agents
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
use std::{fs, io::Write, os::unix::fs::PermissionsExt, path::PathBuf};

use futures_util::StreamExt;
use indexmap::IndexMap;
use rand::seq::IteratorRandom;
use sha2::{Digest, Sha256};
use snops_checkpoint::CheckpointManager;
use snops_common::{
    api::{CheckpointMeta, StorageInfo},
    binaries::{BinaryEntry, BinarySource},
    key_source::KeySource,
    state::{InternedId, KeyState, NetworkId, StorageId},
};
use tracing::{info, trace};

use super::{DEFAULT_AOT_BINARY, STORAGE_DIR};
use crate::{cli::Cli, schema::error::StorageError, state::GlobalState};

// IndexMap<addr, private_key>
pub type AleoAddrMap = IndexMap<String, String>;

#[derive(Debug, Clone)]
pub struct LoadedStorage {
    /// Storage ID
    pub id: StorageId,
    /// Network ID
    pub network: NetworkId,
    /// Version counter for this storage - incrementing will invalidate old
    /// saved ledgers
    pub version: u16,
    /// committee lookup
    pub committee: AleoAddrMap,
    /// other accounts files lookup
    pub accounts: IndexMap<InternedId, AleoAddrMap>,
    /// storage of checkpoints
    pub checkpoints: Option<CheckpointManager>,
    /// whether agents using this storage should persist it
    pub persist: bool,
    /// whether to use the network's native genesis block
    pub native_genesis: bool,
    /// binaries available for this storage
    pub binaries: IndexMap<InternedId, BinaryEntry>,
}

impl LoadedStorage {
    pub fn lookup_keysource_pk(&self, key: &KeySource) -> KeyState {
        match key {
            KeySource::Local => KeyState::Local,
            KeySource::PrivateKeyLiteral(pk) => KeyState::Literal(pk.clone()),
            KeySource::PublicKeyLiteral(_) => KeyState::None,
            KeySource::ProgramLiteral(_) => KeyState::None,
            KeySource::Committee(Some(i)) => self
                .committee
                .get_index(*i)
                .map(|(_, pk)| pk.clone())
                .into(),
            KeySource::Committee(None) => KeyState::None,
            KeySource::Named(name, Some(i)) => self
                .accounts
                .get(name)
                .and_then(|a| a.get_index(*i).map(|(_, pk)| pk.clone()))
                .into(),
            KeySource::Named(_name, None) => KeyState::None,
        }
    }

    pub fn lookup_keysource_addr(&self, key: &KeySource) -> KeyState {
        match key {
            KeySource::Local => KeyState::Local,
            KeySource::PrivateKeyLiteral(_) => KeyState::None,
            KeySource::PublicKeyLiteral(addr) => KeyState::Literal(addr.clone()),
            KeySource::ProgramLiteral(addr) => KeyState::Literal(addr.clone()),
            KeySource::Committee(Some(i)) => self
                .committee
                .get_index(*i)
                .map(|(addr, _)| addr.clone())
                .into(),
            KeySource::Committee(None) => KeyState::None,
            KeySource::Named(name, Some(i)) => self
                .accounts
                .get(name)
                .and_then(|a| a.get_index(*i).map(|(addr, _)| addr.clone()))
                .into(),
            KeySource::Named(_name, None) => KeyState::None,
        }
    }

    pub fn sample_keysource_pk(&self, key: &KeySource) -> KeyState {
        match key {
            KeySource::Local => KeyState::Local,
            KeySource::PrivateKeyLiteral(pk) => KeyState::Literal(pk.clone()),
            KeySource::PublicKeyLiteral(_) => KeyState::None,
            KeySource::ProgramLiteral(_) => KeyState::None,
            KeySource::Committee(Some(i)) => self
                .committee
                .get_index(*i)
                .map(|(_, pk)| pk.clone())
                .into(),
            KeySource::Committee(None) => self
                .committee
                .values()
                .choose(&mut rand::thread_rng())
                .cloned()
                .into(),
            KeySource::Named(name, Some(i)) => self
                .accounts
                .get(name)
                .and_then(|a| a.get_index(*i).map(|(_, pk)| pk.clone()))
                .into(),
            KeySource::Named(name, None) => self
                .accounts
                .get(name)
                .and_then(|a| a.values().choose(&mut rand::thread_rng()).cloned())
                .into(),
        }
    }

    pub fn sample_keysource_addr(&self, key: &KeySource) -> KeyState {
        match key {
            KeySource::Local => KeyState::Local,
            KeySource::PrivateKeyLiteral(_) => KeyState::None,
            KeySource::PublicKeyLiteral(addr) => KeyState::Literal(addr.clone()),
            KeySource::ProgramLiteral(addr) => KeyState::Literal(addr.clone()),
            KeySource::Committee(Some(i)) => self
                .committee
                .get_index(*i)
                .map(|(addr, _)| addr.clone())
                .into(),
            KeySource::Committee(None) => self
                .committee
                .keys()
                .choose(&mut rand::thread_rng())
                .cloned()
                .into(),
            KeySource::Named(name, Some(i)) => self
                .accounts
                .get(name)
                .and_then(|a| a.get_index(*i).map(|(addr, _)| addr.clone()))
                .into(),
            KeySource::Named(name, None) => self
                .accounts
                .get(name)
                .and_then(|a| a.keys().choose(&mut rand::thread_rng()).cloned())
                .into(),
        }
    }

    pub fn info(&self) -> StorageInfo {
        let checkpoints = self
            .checkpoints
            .as_ref()
            .map(|c| {
                c.checkpoints()
                    .filter_map(|(c, path)| {
                        path.file_name()
                            .and_then(|s| s.to_str())
                            .map(|filename| CheckpointMeta {
                                filename: filename.to_string(),
                                height: c.block_height,
                                timestamp: c.timestamp,
                            })
                    })
                    .collect()
            })
            .unwrap_or_default();
        let mut binaries: IndexMap<_, _> = self
            .binaries
            .iter()
            .map(|(k, v)| (*k, v.with_api_path(self.network, self.id, *k)))
            .collect();

        // insert the default binary source information (so agents have a way to compare
        // shasums and file size)
        binaries
            .entry(InternedId::default())
            .or_insert(DEFAULT_AOT_BINARY.with_api_path(
                self.network,
                self.id,
                InternedId::default(),
            ));

        StorageInfo {
            id: self.id,
            version: self.version,
            retention_policy: self.checkpoints.as_ref().map(|c| c.policy().clone()),
            checkpoints,
            persist: self.persist,
            native_genesis: self.native_genesis,
            binaries,
        }
    }

    pub fn path(&self, state: &GlobalState) -> PathBuf {
        self.path_cli(&state.cli)
    }

    pub fn path_cli(&self, cli: &Cli) -> PathBuf {
        let mut path = cli.path.join(STORAGE_DIR);
        path.push(self.network.to_string());
        path.push(self.id.to_string());
        path
    }

    /// Resolve the default binary for this storage
    pub async fn resolve_default_binary(
        &self,
        state: &GlobalState,
    ) -> Result<PathBuf, StorageError> {
        self.resolve_binary(state, InternedId::default()).await
    }

    /// Resolve the compute binary for this storage
    pub async fn resolve_compute_binary(
        &self,
        state: &GlobalState,
    ) -> Result<PathBuf, StorageError> {
        self.resolve_binary(state, InternedId::compute_id()).await
    }

    /// Resolve (find and download) a binary for this storage by id
    pub async fn resolve_binary(
        &self,
        state: &GlobalState,
        id: InternedId,
    ) -> Result<PathBuf, StorageError> {
        Self::resolve_binary_from_map(self.id, self.network, &self.binaries, state, id).await
    }

    /// Resolve a binary entry for this storage by id
    pub fn resolve_binary_entry(
        &self,
        id: InternedId,
    ) -> Result<(InternedId, &BinaryEntry), StorageError> {
        Self::resolve_binary_entry_from_map(self.id, &self.binaries, id)
    }

    pub fn resolve_binary_entry_from_map(
        storage_id: InternedId,
        binaries: &IndexMap<InternedId, BinaryEntry>,
        mut id: InternedId,
    ) -> Result<(InternedId, &BinaryEntry), StorageError> {
        let compute_id = InternedId::compute_id();

        // if the binary id is "compute" and there is no "compute" binary override in
        // the map, then we should use the default binary
        if id == compute_id && !binaries.contains_key(&compute_id) {
            id = InternedId::default();
        }

        // if the binary id is the default binary id and there is no default binary
        // override in the map,
        if id == InternedId::default() && !binaries.contains_key(&InternedId::default()) {
            // then we should use the default AOT binary
            return Ok((id, &DEFAULT_AOT_BINARY));
        }

        let bin = binaries
            .get(&id)
            .ok_or(StorageError::BinaryDoesNotExist(id, storage_id))?;

        Ok((id, bin))
    }

    pub async fn resolve_binary_from_map(
        storage_id: InternedId,
        network: NetworkId,
        binaries: &IndexMap<InternedId, BinaryEntry>,
        state: &GlobalState,
        id: InternedId,
    ) -> Result<PathBuf, StorageError> {
        let (id, bin) = Self::resolve_binary_entry_from_map(storage_id, binaries, id)?;

        let id_str: &str = id.as_ref();

        let remote_url = match bin.source.clone() {
            // if the binary is a relative path, then we should use the path as is
            // rather than downloading it
            BinarySource::Path(path) => return Ok(path.clone()),
            BinarySource::Url(url) => url,
        };

        // derive the path to the binary
        let mut download_path = state.cli.path.join(STORAGE_DIR);
        download_path.push(network.to_string());
        download_path.push(storage_id.to_string());
        download_path.push("binaries");
        download_path.push(id_str);

        // if the file already exists, ensure that it is the correct size and sha256
        if download_path.exists() {
            let perms = download_path
                .metadata()
                .map_err(|e| StorageError::PermissionError(download_path.clone(), e))?
                .permissions();
            if perms.mode() != 0o755 {
                std::fs::set_permissions(&download_path, std::fs::Permissions::from_mode(0o755))
                    .map_err(|e| StorageError::PermissionError(download_path.clone(), e))?;
            }

            match bin.check_file_sha256(&download_path) {
                Ok(None) => {}
                Ok(Some(sha256)) => {
                    return Err(StorageError::BinarySha256Mismatch(
                        storage_id,
                        download_path,
                        bin.sha256.clone().unwrap_or_default(),
                        sha256,
                    ));
                }
                Err(e) => {
                    return Err(StorageError::BinaryCheckFailed(
                        storage_id,
                        download_path,
                        e.to_string(),
                    ));
                }
            }

            match bin.check_file_size(&download_path) {
                // file is okay :)
                Ok(None) => {}
                Ok(Some(size)) => {
                    return Err(StorageError::BinarySizeMismatch(
                        storage_id,
                        download_path,
                        bin.size.unwrap_or_default(),
                        size,
                    ));
                }
                Err(e) => {
                    return Err(StorageError::BinaryCheckFailed(
                        storage_id,
                        download_path,
                        e.to_string(),
                    ));
                }
            }

            return Ok(download_path);
        }

        let resp = reqwest::get(remote_url.clone())
            .await
            .map_err(|e| StorageError::FailedToFetchBinary(id, remote_url.clone(), e))?;

        if resp.status() != reqwest::StatusCode::OK {
            return Err(StorageError::FailedToFetchBinaryWithStatus(
                id,
                remote_url,
                resp.status(),
            ));
        }

        if let Some(parent) = download_path.parent() {
            fs::create_dir_all(parent)
                .map_err(|e| StorageError::FailedToCreateBinaryFile(id, e))?;
        }

        let mut file = std::fs::OpenOptions::new()
            .write(true)
            .create(true)
            .truncate(true)
            .open(&download_path)
            .map_err(|e| StorageError::FailedToCreateBinaryFile(id, e))?;

        let mut digest = Sha256::new();
        let mut stream = resp.bytes_stream();
        let mut size = 0u64;

        while let Some(chunk) = stream.next().await {
            match chunk {
                Ok(chunk) => {
                    size += chunk.len() as u64;
                    file.write_all(&chunk)
                        .map_err(|e| StorageError::FailedToWriteBinaryFile(id, e))?;
                    digest.update(&chunk);
                }
                Err(e) => {
                    return Err(StorageError::FailedToFetchBinary(id, remote_url, e));
                }
            }
        }

        // check if the binary sha256 matches the expected sha256
        let sha256 = format!("{:x}", digest.finalize());
        if let Some(bin_sha256) = bin.sha256.as_ref() {
            if bin_sha256.to_lowercase() != sha256 {
                return Err(StorageError::BinarySha256Mismatch(
                    id,
                    download_path,
                    bin_sha256.clone(),
                    sha256,
                ));
            }
        }

        // check if the binary size matches the expected size
        if let Some(bin_size) = bin.size {
            if bin_size != size {
                return Err(StorageError::BinarySizeMismatch(
                    id,
                    download_path,
                    bin_size,
                    size,
                ));
            }
        }

        info!(
            "downloaded binary {storage_id}.{id_str} to {} ({size} bytes)",
            download_path.display()
        );
        trace!("binary {storage_id}.{id_str} has sha256 {sha256}");

        let perms = download_path
            .metadata()
            .map_err(|e| StorageError::PermissionError(download_path.clone(), e))?
            .permissions();
        if perms.mode() != 0o755 {
            std::fs::set_permissions(&download_path, std::fs::Permissions::from_mode(0o755))
                .map_err(|e| StorageError::PermissionError(download_path.clone(), e))?;
        }

        Ok(download_path)
    }
}