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
// Module used by validators to approve storage mining proofs in parallel using the GPU

use solana_chacha::chacha::{CHACHA_BLOCK_SIZE, CHACHA_KEY_SIZE};
use solana_ledger::blockstore::Blockstore;
use solana_perf::perf_libs;
use solana_sdk::hash::Hash;
use std::io;
use std::mem::size_of;
use std::sync::Arc;

// Encrypt a file with multiple starting IV states, determined by ivecs.len()
//
// Then sample each block at the offsets provided by samples argument with sha256
// and return the vec of sha states
pub fn chacha_cbc_encrypt_file_many_keys(
    blockstore: &Arc<Blockstore>,
    segment: u64,
    slots_per_segment: u64,
    ivecs: &mut [u8],
    samples: &[u64],
) -> io::Result<Vec<Hash>> {
    let api = perf_libs::api().expect("no perf libs");
    if ivecs.len() % CHACHA_BLOCK_SIZE != 0 {
        return Err(io::Error::new(
            io::ErrorKind::Other,
            format!(
                "bad IV length({}) not divisible by {} ",
                ivecs.len(),
                CHACHA_BLOCK_SIZE,
            ),
        ));
    }

    const BUFFER_SIZE: usize = 8 * 1024;
    let mut buffer = [0; BUFFER_SIZE];
    let num_keys = ivecs.len() / CHACHA_BLOCK_SIZE;
    let mut sha_states = vec![0; num_keys * size_of::<Hash>()];
    let mut int_sha_states = vec![0; num_keys * 112];
    let keys: Vec<u8> = vec![0; num_keys * CHACHA_KEY_SIZE]; // keys not used ATM, uniqueness comes from IV
    let mut current_slot = segment * slots_per_segment;
    let mut start_index = 0;
    let start_slot = current_slot;
    let mut total_size = 0;
    let mut time: f32 = 0.0;
    unsafe {
        (api.chacha_init_sha_state)(int_sha_states.as_mut_ptr(), num_keys as u32);
    }
    loop {
        match blockstore.get_data_shreds(current_slot, start_index, std::u64::MAX, &mut buffer) {
            Ok((last_index, mut size)) => {
                debug!(
                    "chacha_cuda: encrypting segment: {} num_shreds: {} data_len: {}",
                    segment,
                    last_index.saturating_sub(start_index),
                    size
                );

                if size == 0 {
                    if current_slot.saturating_sub(start_slot) < slots_per_segment {
                        current_slot += 1;
                        start_index = 0;
                        continue;
                    } else {
                        break;
                    }
                }

                if size < BUFFER_SIZE {
                    // round to the nearest key_size boundary
                    size = (size + CHACHA_KEY_SIZE - 1) & !(CHACHA_KEY_SIZE - 1);
                }

                unsafe {
                    (api.chacha_cbc_encrypt_many_sample)(
                        buffer[..size].as_ptr(),
                        int_sha_states.as_mut_ptr(),
                        size,
                        keys.as_ptr(),
                        ivecs.as_mut_ptr(),
                        num_keys as u32,
                        samples.as_ptr(),
                        samples.len() as u32,
                        total_size,
                        &mut time,
                    );
                }

                total_size += size as u64;
                start_index = last_index + 1;
            }
            Err(e) => {
                info!("Error encrypting file: {:?}", e);
                break;
            }
        }
    }
    unsafe {
        (api.chacha_end_sha_state)(
            int_sha_states.as_ptr(),
            sha_states.as_mut_ptr(),
            num_keys as u32,
        );
    }
    let mut res = Vec::new();
    for x in 0..num_keys {
        let start = x * size_of::<Hash>();
        let end = start + size_of::<Hash>();
        res.push(Hash::new(&sha_states[start..end]));
    }
    Ok(res)
}

#[cfg(test)]
mod tests {
    use super::*;
    use solana_archiver_utils::sample_file;
    use solana_chacha::chacha::chacha_cbc_encrypt_ledger;
    use solana_ledger::entry::create_ticks;
    use solana_ledger::get_tmp_ledger_path;
    use solana_sdk::clock::DEFAULT_SLOTS_PER_SEGMENT;
    use solana_sdk::signature::Keypair;
    use std::fs::{remove_dir_all, remove_file};
    use std::path::Path;

    #[test]
    fn test_encrypt_file_many_keys_single() {
        solana_logger::setup();
        if perf_libs::api().is_none() {
            info!("perf-libs unavailable, skipped");
            return;
        }

        let slots_per_segment = 32;
        let entries = create_ticks(slots_per_segment, 0, Hash::default());
        let ledger_path = get_tmp_ledger_path!();
        let ticks_per_slot = 16;
        let blockstore = Arc::new(Blockstore::open(&ledger_path).unwrap());

        blockstore
            .write_entries(
                0,
                0,
                0,
                ticks_per_slot,
                Some(0),
                true,
                &Arc::new(Keypair::new()),
                entries,
                0,
            )
            .unwrap();

        let out_path = Path::new("test_chacha_encrypt_file_many_keys_single_output.txt.enc");

        let samples = [0];
        let mut ivecs = hex!(
            "abcd1234abcd1234abcd1234abcd1234 abcd1234abcd1234abcd1234abcd1234
                              abcd1234abcd1234abcd1234abcd1234 abcd1234abcd1234abcd1234abcd1234"
        );

        let mut cpu_iv = ivecs.clone();
        chacha_cbc_encrypt_ledger(
            &blockstore,
            0,
            slots_per_segment as u64,
            out_path,
            &mut cpu_iv,
        )
        .unwrap();

        let ref_hash = sample_file(&out_path, &samples).unwrap();

        let hashes = chacha_cbc_encrypt_file_many_keys(
            &blockstore,
            0,
            slots_per_segment as u64,
            &mut ivecs,
            &samples,
        )
        .unwrap();

        assert_eq!(hashes[0], ref_hash);

        let _ignored = remove_dir_all(&ledger_path);
        let _ignored = remove_file(out_path);
    }

    #[test]
    fn test_encrypt_file_many_keys_multiple_keys() {
        solana_logger::setup();
        if perf_libs::api().is_none() {
            info!("perf-libs unavailable, skipped");
            return;
        }

        let ledger_path = get_tmp_ledger_path!();
        let ticks_per_slot = 90;
        let entries = create_ticks(2 * ticks_per_slot, 0, Hash::default());
        let blockstore = Arc::new(Blockstore::open(&ledger_path).unwrap());
        blockstore
            .write_entries(
                0,
                0,
                0,
                ticks_per_slot,
                Some(0),
                true,
                &Arc::new(Keypair::new()),
                entries,
                0,
            )
            .unwrap();

        let out_path = Path::new("test_chacha_encrypt_file_many_keys_multiple_output.txt.enc");

        let samples = [0, 1, 3, 4, 5, 150];
        let mut ivecs = Vec::new();
        let mut ref_hashes: Vec<Hash> = vec![];
        for i in 0..2 {
            let mut ivec = hex!(
                "abc123abc123abc123abc123abc123abc123abababababababababababababab
                                 abc123abc123abc123abc123abc123abc123abababababababababababababab"
            );
            ivec[0] = i;
            ivecs.extend(ivec.clone().iter());
            chacha_cbc_encrypt_ledger(
                &blockstore.clone(),
                0,
                DEFAULT_SLOTS_PER_SEGMENT,
                out_path,
                &mut ivec,
            )
            .unwrap();

            ref_hashes.push(sample_file(&out_path, &samples).unwrap());
            info!(
                "ivec: {:?} hash: {:?} ivecs: {:?}",
                ivec.to_vec(),
                ref_hashes.last(),
                ivecs
            );
        }

        let hashes = chacha_cbc_encrypt_file_many_keys(
            &blockstore,
            0,
            DEFAULT_SLOTS_PER_SEGMENT,
            &mut ivecs,
            &samples,
        )
        .unwrap();

        assert_eq!(hashes, ref_hashes);

        let _ignored = remove_dir_all(&ledger_path);
        let _ignored = remove_file(out_path);
    }

    #[test]
    fn test_encrypt_file_many_keys_bad_key_length() {
        solana_logger::setup();
        if perf_libs::api().is_none() {
            info!("perf-libs unavailable, skipped");
            return;
        }

        let mut keys = hex!("abc123");
        let ledger_path = get_tmp_ledger_path!();
        let samples = [0];
        let blockstore = Arc::new(Blockstore::open(&ledger_path).unwrap());
        assert!(chacha_cbc_encrypt_file_many_keys(
            &blockstore,
            0,
            DEFAULT_SLOTS_PER_SEGMENT,
            &mut keys,
            &samples,
        )
        .is_err());
    }
}