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
// Copyright (C) 2019-2021 Aleo Systems Inc.
// This file is part of the Leo library.

// The Leo library is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.

// The Leo library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.

// You should have received a copy of the GNU General Public License
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.

//! The program package zip file.

use crate::{
    errors::ZipFileError,
    imports::IMPORTS_DIRECTORY_NAME,
    inputs::{INPUTS_DIRECTORY_NAME, INPUT_FILE_EXTENSION},
    outputs::{
        CHECKSUM_FILE_EXTENSION,
        CIRCUIT_FILE_EXTENSION,
        OUTPUTS_DIRECTORY_NAME,
        PROOF_FILE_EXTENSION,
        PROVING_KEY_FILE_EXTENSION,
        VERIFICATION_KEY_FILE_EXTENSION,
    },
    root::{MANIFEST_FILENAME, README_FILENAME},
    source::{SOURCE_DIRECTORY_NAME, SOURCE_FILE_EXTENSION},
};

use serde::Deserialize;
use std::{
    borrow::Cow,
    fs::{self, File},
    io::{Read, Write},
    path::Path,
};
use walkdir::WalkDir;
use zip::write::{FileOptions, ZipWriter};

pub static ZIP_FILE_EXTENSION: &str = ".zip";

#[derive(Deserialize)]
pub struct ZipFile {
    pub package_name: String,
}

impl ZipFile {
    pub fn new(package_name: &str) -> Self {
        Self {
            package_name: package_name.to_string(),
        }
    }

    pub fn exists_at(&self, path: &Path) -> bool {
        let path = self.setup_file_path(path);
        path.exists()
    }

    pub fn get_file_path<'a>(&self, current_dir: &'a Path) -> Cow<'a, Path> {
        self.setup_file_path(current_dir)
    }

    // /// Reads the program bytes from the given file path if it exists.
    // pub fn read_from(&self, path: &Path) -> Result<Vec<u8>, ZipFileError> {
    //     let path = self.setup_file_path(path);
    //
    //     Ok(fs::read(&path).map_err(|_| ZipFileError::FileReadError(path.clone()))?)
    // }

    /// Writes the current package contents to a zip file.
    pub fn write(&self, src_dir: &Path) -> Result<(), ZipFileError> {
        // Build walkdir iterator from current package
        let walkdir = WalkDir::new(src_dir);

        // Create zip file
        let path = self.setup_file_path(src_dir);

        let file = &mut File::create(&path)?;
        let mut zip = ZipWriter::new(file);
        let options = FileOptions::default()
            .compression_method(zip::CompressionMethod::Stored)
            .unix_permissions(0o755);

        // Walk through files in directory and write desired ones to the zip file
        let mut buffer = Vec::new();
        for entry in walkdir.into_iter().filter_map(|e| e.ok()) {
            let path = entry.path();
            let name = path.strip_prefix(src_dir).unwrap();

            // Add file/directory exclusion

            let included = is_included(name);
            tracing::debug!("Checking if {:?} is included - {}", name, included);
            if !included {
                continue;
            }

            // Write file or directory
            if path.is_file() {
                tracing::info!("Adding file {:?} as {:?}", path, name);
                zip.start_file(name.to_string_lossy(), options)?;
                let mut f = File::open(path)?;

                f.read_to_end(&mut buffer)?;
                zip.write_all(&*buffer)?;
                buffer.clear();
            } else if !name.as_os_str().is_empty() {
                // Only if not root Avoids path spec / warning
                // and mapname conversion failed error on unzip
                tracing::info!("Adding directory {:?} as {:?}", path, name);
                zip.add_directory(name.to_string_lossy(), options)?;
            }
        }

        zip.finish()?;

        tracing::info!("Package zip file created successfully {:?}", path);

        Ok(())
    }

    /// Removes the zip file at the given path if it exists. Returns `true` on success,
    /// `false` if the file doesn't exist, and `Error` if the file system fails during operation.
    pub fn remove(&self, path: &Path) -> Result<bool, ZipFileError> {
        let path = self.setup_file_path(path);
        if !path.exists() {
            return Ok(false);
        }

        fs::remove_file(&path).map_err(|_| ZipFileError::FileRemovalError(path.into_owned()))?;
        Ok(true)
    }

    fn setup_file_path<'a>(&self, path: &'a Path) -> Cow<'a, Path> {
        let mut path = Cow::from(path);
        if path.is_dir() {
            if !path.ends_with(OUTPUTS_DIRECTORY_NAME) {
                path.to_mut().push(OUTPUTS_DIRECTORY_NAME);
            }
            path.to_mut()
                .push(format!("{}{}", self.package_name, ZIP_FILE_EXTENSION));
        }
        path
    }
}

/// Check if the file path should be included in the package zip file.
fn is_included(path: &Path) -> bool {
    // excluded directories: `input`, `output`, `imports`
    if path.ends_with(INPUTS_DIRECTORY_NAME.trim_end_matches('/'))
        | path.ends_with(OUTPUTS_DIRECTORY_NAME.trim_end_matches('/'))
        | path.ends_with(IMPORTS_DIRECTORY_NAME.trim_end_matches('/'))
    {
        return false;
    }

    // excluded extensions: `.in`, `.bytes`, `lpk`, `lvk`, `.proof`, `.sum`, `.zip`, `.bytes`
    if let Some(true) = path.extension().map(|ext| {
        ext.eq(INPUT_FILE_EXTENSION.trim_start_matches('.'))
            | ext.eq(ZIP_FILE_EXTENSION.trim_start_matches('.'))
            | ext.eq(PROVING_KEY_FILE_EXTENSION.trim_start_matches('.'))
            | ext.eq(VERIFICATION_KEY_FILE_EXTENSION.trim_start_matches('.'))
            | ext.eq(PROOF_FILE_EXTENSION.trim_start_matches('.'))
            | ext.eq(CHECKSUM_FILE_EXTENSION.trim_start_matches('.'))
            | ext.eq(ZIP_FILE_EXTENSION.trim_start_matches('.'))
            | ext.eq(CIRCUIT_FILE_EXTENSION.trim_start_matches('.'))
    }) {
        return false;
    }

    // Allow the README.md and Leo.toml files in the root directory
    if (path.ends_with(README_FILENAME) | path.ends_with(MANIFEST_FILENAME)) & (path.parent() == Some(Path::new(""))) {
        return true;
    }

    // Only allow additional files in the `src/` directory
    if !path.starts_with(SOURCE_DIRECTORY_NAME.trim_end_matches('/')) {
        return false;
    }

    // Allow the `.leo` files in the `src/` directory
    path.extension()
        .map(|ext| ext.eq(SOURCE_FILE_EXTENSION.trim_start_matches('.')))
        .unwrap_or(false)
}