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
use std::cell::RefCell;
use std::fs::File;
use std::io::{Read, Seek, SeekFrom, Write};
use std::path::PathBuf;

use indy_utils::base58;
use sha2::{Digest, Sha256};
use tempfile;

use crate::error::Result;
use crate::ursa::{
    cl::{RevocationTailsAccessor, RevocationTailsGenerator, Tail},
    errors::{UrsaCryptoError, UrsaCryptoErrorKind},
};

const TAILS_BLOB_TAG_SZ: u8 = 2;
const TAIL_SIZE: usize = Tail::BYTES_REPR_SIZE;

#[derive(Debug)]
pub struct TailsReader {
    inner: Box<RefCell<dyn TailsReaderImpl>>,
}

impl TailsReader {
    pub(crate) fn new<TR: TailsReaderImpl + 'static>(inner: TR) -> Self {
        Self {
            inner: Box::new(RefCell::new(inner)),
        }
    }
}

pub trait TailsReaderImpl: std::fmt::Debug + Send {
    fn hash(&mut self) -> Result<Vec<u8>>;
    fn read(&mut self, size: usize, offset: usize) -> Result<Vec<u8>>;
}

impl RevocationTailsAccessor for TailsReader {
    fn access_tail(
        &self,
        tail_id: u32,
        accessor: &mut dyn FnMut(&Tail),
    ) -> std::result::Result<(), UrsaCryptoError> {
        trace!("access_tail >>> tail_id: {:?}", tail_id);

        let tail_bytes = self
            .inner
            .borrow_mut()
            .read(
                TAIL_SIZE,
                TAIL_SIZE * tail_id as usize + TAILS_BLOB_TAG_SZ as usize,
            )
            .map_err(|_| {
                UrsaCryptoError::from_msg(
                    UrsaCryptoErrorKind::InvalidState,
                    "Can't read tail bytes from file",
                )
            })?; // FIXME: IO error should be returned

        let tail = Tail::from_bytes(tail_bytes.as_slice())?;
        accessor(&tail);

        trace!("access_tail <<< res: ()");
        Ok(())
    }
}

#[derive(Debug)]
pub struct TailsFileReader {
    path: String,
    file: Option<File>,
    hash: Option<Vec<u8>>,
}

impl TailsFileReader {
    pub fn new(path: &str) -> TailsReader {
        TailsReader::new(Self {
            path: path.to_owned(),
            file: None,
            hash: None,
        })
    }

    pub fn open(&mut self) -> Result<()> {
        if self.file.is_some() {
            Ok(())
        } else {
            let file = File::open(self.path.clone())?;
            self.file.replace(file);
            Ok(())
        }
    }

    pub fn close(&mut self) {
        self.file.take();
    }
}

impl TailsReaderImpl for TailsFileReader {
    fn hash(&mut self) -> Result<Vec<u8>> {
        if self.hash.is_some() {
            return Ok(self.hash.as_ref().unwrap().clone());
        }

        self.open()?;
        let file = self.file.as_mut().unwrap();
        file.seek(SeekFrom::Start(0))?;
        let mut hasher = Sha256::default();
        let mut buf = [0u8; 1024];

        loop {
            let sz = file.read(&mut buf)?;
            if sz == 0 {
                self.hash = Some(hasher.finalize().to_vec());
                return Ok(self.hash.as_ref().unwrap().clone());
            }
            hasher.update(&buf[0..sz]);
        }
    }

    fn read(&mut self, size: usize, offset: usize) -> Result<Vec<u8>> {
        let mut buf = vec![0u8; size];

        self.open()?;
        let file = self.file.as_mut().unwrap();
        file.seek(SeekFrom::Start(offset as u64))?;
        file.read_exact(buf.as_mut_slice())?;

        Ok(buf)
    }
}

pub trait TailsWriter: std::fmt::Debug {
    fn write(&mut self, generator: &mut RevocationTailsGenerator) -> Result<(String, String)>;
}

#[derive(Debug)]
pub struct TailsFileWriter {
    root_path: PathBuf,
}

impl TailsFileWriter {
    pub fn new(root_path: Option<String>) -> Self {
        Self {
            root_path: root_path
                .map(PathBuf::from)
                .unwrap_or_else(|| std::env::temp_dir()),
        }
    }
}

impl TailsWriter for TailsFileWriter {
    fn write(&mut self, generator: &mut RevocationTailsGenerator) -> Result<(String, String)> {
        let mut tempf = tempfile::NamedTempFile::new_in(self.root_path.clone())?;
        let file = tempf.as_file_mut();
        let mut hasher = Sha256::default();
        let version = &[0u8, 2u8];
        file.write(version)?;
        hasher.update(version);
        while let Some(tail) = generator.try_next()? {
            let tail_bytes = tail.to_bytes()?;
            file.write(tail_bytes.as_slice())?;
            hasher.update(tail_bytes);
        }
        let tails_size = &file.seek(SeekFrom::Current(0))?;
        let hash = base58::encode(hasher.finalize());
        let path = tempf.path().with_file_name(hash.clone());
        let _outf = match tempf.persist_noclobber(&path) {
            Ok(f) => f,
            Err(err) => {
                return Err(err_msg!(IOError, "Error persisting tails file: {}", err,));
            }
        };
        let path = path.to_string_lossy().into_owned();
        debug!(
            "TailsFileWriter: wrote tails file [size {}]: {}",
            tails_size, path
        );
        Ok((path, hash))
    }
}