use std::{
collections::HashSet,
fmt::Display,
io::{Cursor, Write},
num::NonZero,
ops::{Add, Sub},
path::Path,
time::{Duration, SystemTime},
};
use digest::Digest;
use flate2::write::{DeflateEncoder, GzEncoder};
use getset::CopyGetters;
use r2d2::Pool;
use r2d2_sqlite::SqliteConnectionManager;
use rand::Rng;
use rusqlite::{
OptionalExtension, ToSql, Transaction, TransactionBehavior, named_params, params,
types::{FromSql, FromSqlError, FromSqlResult, ToSqlOutput, ValueRef},
};
use saturating_time::SaturatingTime;
use tor_basic_utils::RngExt;
use tor_dircommon::config::DirTolerance;
use tor_error::into_internal;
use tor_netdoc::doc::{
authcert::{AuthCert, AuthCertKeyIds},
netstatus::ConsensusFlavor,
};
use crate::err::DatabaseError;
const V1_SCHEMA: &str = include_str!("schema_v1.sql");
const GLOBAL_OPTIONS: &str = sql!(
"
PRAGMA journal_mode=WAL;
PRAGMA foreign_keys=ON;
PRAGMA busy_timeout=1000;
"
);
macro_rules! impl_hash_wrapper {
($name:ident, $algo:ty, $size:literal) => {
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub(crate) struct $name([u8; $size]);
impl $name {
pub(crate) fn digest(data: &[u8]) -> Self {
Self(<$algo>::digest(data).into())
}
}
impl Display for $name {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", hex::encode_upper(self.0))
}
}
impl FromSql for $name {
fn column_result(value: ValueRef<'_>) -> FromSqlResult<Self> {
let data: [u8; $size] = value
.as_str()
.map(hex::decode)?
.map_err(|e| {
FromSqlError::Other(Box::new(tor_error::internal!(
"non hex data in database? {e}"
)))
})?
.try_into()
.map_err(|_| {
FromSqlError::Other(Box::new(tor_error::internal!(
"$name with invalid length in database?"
)))
})?;
Ok(Self(data))
}
}
impl ToSql for $name {
fn to_sql(&self) -> rusqlite::Result<ToSqlOutput<'_>> {
Ok(ToSqlOutput::from(self.to_string()))
}
}
impl PartialEq<&str> for $name {
fn eq(&self, other: &&str) -> bool {
self.to_string() == other.to_uppercase()
}
}
#[cfg(test)]
impl From<[u8; $size]> for $name {
fn from(value: [u8; $size]) -> Self {
Self(value)
}
}
};
}
impl_hash_wrapper!(Sha1, tor_llcrypto::d::Sha1, 20);
impl_hash_wrapper!(Sha256, tor_llcrypto::d::Sha256, 32);
impl_hash_wrapper!(Sha3_256, tor_llcrypto::d::Sha3_256, 32);
pub(crate) type DocumentId = Sha256;
#[derive(Debug, Clone, Copy, PartialEq, strum::EnumString, strum::Display, strum::EnumIter)]
#[strum(serialize_all = "kebab-case", ascii_case_insensitive)]
pub(crate) enum ContentEncoding {
Identity,
Deflate,
Gzip,
XZstd,
XTorLzma,
}
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
pub(crate) struct Timestamp(SystemTime);
impl From<SystemTime> for Timestamp {
fn from(value: SystemTime) -> Self {
Self(value)
}
}
impl From<Timestamp> for SystemTime {
fn from(value: Timestamp) -> Self {
value.0
}
}
impl Add<Duration> for Timestamp {
type Output = Self;
fn add(self, rhs: Duration) -> Self::Output {
Self(self.0.saturating_add(rhs))
}
}
impl Sub<Duration> for Timestamp {
type Output = Self;
fn sub(self, rhs: Duration) -> Self::Output {
Self(self.0.saturating_sub(rhs))
}
}
impl Sub<Timestamp> for Timestamp {
type Output = Duration;
fn sub(self, rhs: Timestamp) -> Self::Output {
#[allow(unstable_name_collisions)]
self.0.saturating_duration_since(rhs.0)
}
}
impl FromSql for Timestamp {
fn column_result(value: ValueRef<'_>) -> FromSqlResult<Self> {
let mut res = SystemTime::UNIX_EPOCH;
res = res.saturating_add(Duration::from_secs(value.as_i64()?.try_into().unwrap_or(0)));
Ok(Self(res))
}
}
impl ToSql for Timestamp {
fn to_sql(&self) -> rusqlite::Result<ToSqlOutput<'_>> {
#[allow(unstable_name_collisions)]
Ok(ToSqlOutput::from(
self.0
.saturating_duration_since(SystemTime::UNIX_EPOCH)
.as_secs()
.try_into()
.unwrap_or(i64::MAX),
))
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, CopyGetters)]
#[get_copy = "pub(crate)"]
pub(crate) struct ConsensusMeta {
docid: DocumentId,
unsigned_sha3_256: Sha3_256,
flavor: ConsensusFlavor,
valid_after: Timestamp,
fresh_until: Timestamp,
valid_until: Timestamp,
}
impl ConsensusMeta {
pub(crate) fn query_recent(
tx: &Transaction,
flavor: ConsensusFlavor,
tolerance: &DirTolerance,
now: Timestamp,
) -> Result<Option<Self>, DatabaseError> {
let mut meta_stmt = tx.prepare_cached(sql!(
"
SELECT docid, unsigned_sha3_256, valid_after, fresh_until, valid_until
FROM consensus
WHERE
flavor = :flavor
AND :now >= valid_after - :pre_valid
AND :now <= valid_until + :post_valid
ORDER BY valid_after DESC
LIMIT 1
"
))?;
let res = meta_stmt.query_one(named_params! {
":flavor": flavor.name(),
":now": now,
":pre_valid": tolerance.pre_valid_tolerance().as_secs().try_into().unwrap_or(i64::MAX),
":post_valid": tolerance.post_valid_tolerance().as_secs().try_into().unwrap_or(i64::MAX),
}, |row| {
Ok(Self {
docid: row.get(0)?,
unsigned_sha3_256: row.get(1)?,
flavor,
valid_after: row.get(2)?,
fresh_until: row.get(3)?,
valid_until: row.get(4)?,
})
}).optional()?;
Ok(res)
}
pub(crate) fn data(&self, tx: &Transaction<'_>) -> Result<String, DatabaseError> {
let mut stmt = tx.prepare_cached(sql!(
"
SELECT content
FROM store
WHERE docid = :docid
"
))?;
let raw = stmt.query_one(named_params! {":docid": self.docid}, |row| {
row.get::<_, Vec<u8>>(0)
})?;
let raw = String::from_utf8(raw).map_err(into_internal!("utf-8 constraint violated?"))?;
Ok(raw)
}
pub(crate) fn lifetime<R: Rng>(&self, rng: &mut R) -> Timestamp {
assert!(self.fresh_until < self.valid_until);
let offset = rng
.gen_range_checked(0..=((self.valid_until - self.fresh_until).as_secs() / 2))
.expect("invalid range?");
self.fresh_until + Duration::from_secs(offset)
}
pub(crate) fn missing_servers(
&self,
tx: &Transaction<'_>,
) -> Result<HashSet<Sha1>, DatabaseError> {
if self.flavor != ConsensusFlavor::Plain {
return Ok(HashSet::new());
}
let mut stmt = tx.prepare_cached(sql!(
"
SELECT cr.unsigned_sha1
FROM consensus_router_descriptor_member AS cr
LEFT JOIN router_descriptor AS server ON cr.unsigned_sha1 = server.unsigned_sha1
WHERE
cr.consensus_docid = :docid
AND cr.unsigned_sha1 IS NOT NULL
AND server.unsigned_sha1 IS NULL
"
))?;
let missing = stmt
.query_map(named_params! {":docid": self.docid}, |row| row.get(0))?
.collect::<Result<HashSet<_>, _>>()?;
Ok(missing)
}
pub(crate) fn missing_extras(
&self,
tx: &Transaction<'_>,
) -> Result<HashSet<Sha1>, DatabaseError> {
if self.flavor != ConsensusFlavor::Plain {
return Ok(HashSet::new());
}
let mut stmt = tx.prepare_cached(sql!(
"
SELECT server.extra_unsigned_sha1
FROM consensus_router_descriptor_member AS cr
INNER JOIN router_descriptor AS server ON cr.unsigned_sha1 = server.unsigned_sha1
LEFT JOIN router_extra_info AS extra ON server.extra_unsigned_sha1 = extra.unsigned_sha1
WHERE
cr.consensus_docid = :docid
AND server.extra_unsigned_sha1 IS NOT NULL
AND extra.unsigned_sha1 IS NULL
"
))?;
let missing = stmt
.query_map(named_params! {":docid": self.docid}, |row| row.get(0))?
.collect::<Result<HashSet<_>, _>>()?;
Ok(missing)
}
pub(crate) fn missing_micros(
&self,
tx: &Transaction<'_>,
) -> Result<HashSet<Sha256>, DatabaseError> {
if self.flavor != ConsensusFlavor::Microdesc {
return Ok(HashSet::new());
}
let mut stmt = tx.prepare_cached(sql!(
"
SELECT cr.unsigned_sha2
FROM consensus_router_descriptor_member AS cr
LEFT JOIN router_descriptor AS micro ON cr.unsigned_sha2 = micro.unsigned_sha2
WHERE
cr.consensus_docid = :docid
AND cr.unsigned_sha2 IS NOT NULL
AND micro.unsigned_sha2 IS NULL
"
))?;
let missing = stmt
.query_map(named_params! {":docid": self.docid}, |row| row.get(0))?
.collect::<Result<HashSet<_>, _>>()?;
Ok(missing)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, CopyGetters)]
#[get_copy = "pub(crate)"]
pub(crate) struct AuthCertMeta {
docid: DocumentId,
kp_auth_id_rsa_sha1: Sha1,
kp_auth_sign_rsa_sha1: Sha1,
dir_key_published: Timestamp,
dir_key_expires: Timestamp,
}
impl AuthCertMeta {
pub(crate) fn query_recent(
tx: &Transaction,
signatories: &[AuthCertKeyIds],
tolerance: &DirTolerance,
now: Timestamp,
) -> Result<(Vec<Self>, Vec<AuthCertKeyIds>), DatabaseError> {
let mut stmt = tx.prepare_cached(sql!(
"
SELECT docid, kp_auth_id_rsa_sha1, kp_auth_sign_rsa_sha1,
dir_key_published, dir_key_expires
FROM authority_key_certificate
WHERE
(:id_rsa, :sk_rsa) = (kp_auth_id_rsa_sha1, kp_auth_sign_rsa_sha1)
AND :now >= dir_key_published - :pre_tolerance
AND :now <= dir_key_expires + :post_tolerance
ORDER BY dir_key_published DESC
LIMIT 1
"
))?;
let mut found = Vec::new();
let mut missing = Vec::new();
for kp in signatories {
let res = stmt
.query_one(
named_params! {
":id_rsa": kp.id_fingerprint.as_hex_upper(),
":sk_rsa": kp.sk_fingerprint.as_hex_upper(),
":now": now,
":pre_tolerance": tolerance.pre_valid_tolerance().as_secs().try_into().unwrap_or(i64::MAX),
":post_tolerance": tolerance.post_valid_tolerance().as_secs().try_into().unwrap_or(i64::MAX),
},
|row| Ok(Self {
docid: row.get(0)?,
kp_auth_id_rsa_sha1: row.get(1)?,
kp_auth_sign_rsa_sha1: row.get(2)?,
dir_key_published: row.get(3)?,
dir_key_expires: row.get(4)?,
})
)
.optional()?;
match res {
Some(cert) => found.push(cert),
None => missing.push(*kp),
}
}
Ok((found, missing))
}
pub(crate) fn data(&self, tx: &Transaction<'_>) -> Result<String, DatabaseError> {
let mut stmt = tx.prepare_cached(sql!(
"
SELECT content
FROM store
WHERE docid = :docid
"
))?;
let raw = stmt.query_one(named_params! {":docid": self.docid}, |row| {
row.get::<_, Vec<u8>>(0)
})?;
let raw = String::from_utf8(raw).map_err(into_internal!("utf-8 constraint violated?"))?;
Ok(raw)
}
pub(crate) fn insert<I: Iterator<Item = ContentEncoding>>(
tx: &Transaction<'_>,
encodings: I,
cert: &AuthCert,
data: &str,
) -> Result<(), DatabaseError> {
let mut stmt = tx.prepare_cached(sql!(
"
INSERT INTO authority_key_certificate
(docid, kp_auth_id_rsa_sha1, kp_auth_sign_rsa_sha1, dir_key_published, dir_key_expires)
VALUES
(:docid, :id_rsa, :sign_rsa, :published, :expires)
"
))?;
let docid = store_insert(tx, data.as_bytes(), encodings)?;
stmt.execute(named_params! {
":docid": docid,
":id_rsa": cert.dir_identity_key.to_rsa_identity().as_hex_upper(),
":sign_rsa": cert.dir_signing_key.to_rsa_identity().as_hex_upper(),
":published": Timestamp::from(cert.dir_key_published.0),
":expires": Timestamp::from(cert.dir_key_expires.0),
})?;
Ok(())
}
}
macro_rules! sql {
($s:literal) => {
$s
};
}
pub(crate) use sql;
pub(crate) fn open<P: AsRef<Path>>(
path: P,
) -> Result<Pool<SqliteConnectionManager>, DatabaseError> {
let num_cores = std::thread::available_parallelism()
.unwrap_or(NonZero::new(8).expect("8 == 0?"))
.get() as u32;
let manager = r2d2_sqlite::SqliteConnectionManager::file(&path);
let pool = Pool::builder().max_size(num_cores).build(manager)?;
rw_tx(&pool, |tx| {
let has_arti_dirserver_schema_version = match tx.query_one(
sql!(
"
SELECT name
FROM sqlite_master
WHERE type = 'table'
AND name = 'arti_dirserver_schema_version'
"
),
params![],
|_| Ok(()),
) {
Ok(()) => true,
Err(rusqlite::Error::QueryReturnedNoRows) => false,
Err(e) => return Err(DatabaseError::LowLevel(e)),
};
if has_arti_dirserver_schema_version {
let version = tx.query_one(
sql!("SELECT version FROM arti_dirserver_schema_version WHERE rowid = 1"),
params![],
|row| row.get::<_, String>(0),
)?;
match version.as_ref() {
"1" => {}
unknown => {
return Err(DatabaseError::IncompatibleSchema {
version: unknown.into(),
});
}
}
} else {
tx.execute_batch(V1_SCHEMA)?;
}
Ok::<_, DatabaseError>(())
})??;
Ok(pool)
}
pub(crate) fn read_tx<U, F>(pool: &Pool<SqliteConnectionManager>, op: F) -> Result<U, DatabaseError>
where
F: FnOnce(&Transaction<'_>) -> U,
{
let mut conn = pool.get()?;
conn.execute_batch(GLOBAL_OPTIONS)?;
let tx = conn.transaction_with_behavior(TransactionBehavior::Deferred)?;
let res = op(&tx);
tx.rollback()?;
Ok(res)
}
pub(crate) fn rw_tx<U, F>(pool: &Pool<SqliteConnectionManager>, op: F) -> Result<U, DatabaseError>
where
F: FnOnce(&Transaction<'_>) -> U,
{
let mut conn = pool.get()?;
conn.execute_batch(GLOBAL_OPTIONS)?;
let tx = conn.transaction_with_behavior(TransactionBehavior::Exclusive)?;
let res = op(&tx);
tx.commit()?;
Ok(res)
}
pub(crate) fn store_insert<I: Iterator<Item = ContentEncoding>>(
tx: &Transaction,
data: &[u8],
encodings: I,
) -> Result<DocumentId, DatabaseError> {
let mut store_stmt = tx.prepare_cached(sql!(
"
INSERT OR REPLACE INTO store (docid, content)
VALUES
(:docid, :content)
"
))?;
let mut compressed_stmt = tx.prepare_cached(sql!(
"
INSERT OR REPLACE INTO compressed_document (algorithm, identity_docid, compressed_docid)
VALUES
(:algorithm, :identity_docid, :compressed_docid)
"
))?;
let identity_docid = DocumentId::digest(data);
store_stmt.execute(named_params! {
":docid": identity_docid,
":content": data
})?;
for encoding in encodings {
if encoding == ContentEncoding::Identity {
continue;
}
let compressed = compress(data, encoding).map_err(into_internal!("{encoding} failed?"))?;
let compressed_docid = DocumentId::digest(&compressed);
store_stmt.execute(named_params! {
":docid": compressed_docid,
":content": compressed,
})?;
compressed_stmt.execute(named_params! {
":algorithm": encoding.to_string(),
":identity_docid": identity_docid,
":compressed_docid": compressed_docid,
})?;
}
Ok(identity_docid)
}
fn compress(data: &[u8], encoding: ContentEncoding) -> Result<Vec<u8>, std::io::Error> {
match encoding {
ContentEncoding::Identity => Ok(data.to_vec()),
ContentEncoding::Deflate => {
let mut w = DeflateEncoder::new(Vec::new(), Default::default());
w.write_all(data)?;
w.finish()
}
ContentEncoding::Gzip => {
let mut w = GzEncoder::new(Vec::new(), Default::default());
w.write_all(data)?;
w.finish()
}
ContentEncoding::XZstd => zstd::encode_all(data, Default::default()),
ContentEncoding::XTorLzma => {
let mut res = Vec::new();
lzma_rs::lzma_compress(&mut Cursor::new(data), &mut res)?;
Ok(res)
}
}
}
#[cfg(test)]
mod test {
#![allow(clippy::bool_assert_comparison)]
#![allow(clippy::clone_on_copy)]
#![allow(clippy::dbg_macro)]
#![allow(clippy::mixed_attributes_style)]
#![allow(clippy::print_stderr)]
#![allow(clippy::print_stdout)]
#![allow(clippy::single_char_pattern)]
#![allow(clippy::unwrap_used)]
#![allow(clippy::unchecked_time_subtraction)]
#![allow(clippy::useless_vec)]
#![allow(clippy::needless_pass_by_value)]
#![allow(clippy::string_slice)] use std::{
collections::HashSet,
io::Read,
sync::{Arc, Once},
};
use flate2::read::{DeflateDecoder, GzDecoder};
use lazy_static::lazy_static;
use rusqlite::Connection;
use strum::IntoEnumIterator;
use tempfile::tempdir;
use tor_basic_utils::test_rng::testing_rng;
use tor_dircommon::config::DirToleranceBuilder;
use tor_llcrypto::pk::rsa::RsaIdentity;
use super::*;
lazy_static! {
static ref VALID_AFTER: Timestamp =
(SystemTime::UNIX_EPOCH + Duration::from_secs(1577836800)).into();
static ref FRESH_UNTIL: Timestamp =
*VALID_AFTER + Duration::from_secs(60 * 60);
static ref FRESH_UNTIL_HALF: Timestamp =
*FRESH_UNTIL + Duration::from_secs(60 * 60);
static ref VALID_UNTIL: Timestamp =
*FRESH_UNTIL + Duration::from_secs(60 * 60 * 2);
}
const CONSENSUS_CONTENT: &str = "Lorem ipsum dolor sit amet.";
const CONSENSUS_MD_CONTENT: &str = "Lorem ipsum dolor sit amet!";
const CERT_CONTENT: &[u8] = include_bytes!("../testdata/authcert-longclaw");
lazy_static! {
static ref CONSENSUS_DOCID: DocumentId = DocumentId::digest(CONSENSUS_CONTENT.as_bytes());
static ref CONSENSUS_MD_DOCID: DocumentId =
DocumentId::digest(CONSENSUS_MD_CONTENT.as_bytes());
static ref CERT_DOCID: DocumentId = DocumentId::digest(CERT_CONTENT);
}
fn create_dummy_db() -> Pool<SqliteConnectionManager> {
let pool = open("").unwrap();
rw_tx(&pool, |tx| {
tx.execute(
sql!("INSERT INTO store (docid, content) VALUES (?1, ?2)"),
params![*CONSENSUS_DOCID, CONSENSUS_CONTENT.as_bytes()],
)
.unwrap();
tx.execute(
sql!("INSERT INTO store (docid, content) VALUES (?1, ?2)"),
params![*CONSENSUS_MD_DOCID, CONSENSUS_MD_CONTENT.as_bytes()],
)
.unwrap();
tx.execute(
sql!("INSERT INTO store (docid, content) VALUES (?1, ?2)"),
params![*CERT_DOCID, CERT_CONTENT],
)
.unwrap();
tx.execute(
sql!("INSERT INTO store (docid, content) VALUES (?1, ?2)"),
params![
DocumentId::digest(include_bytes!("../testdata/descriptor1-ns")),
include_bytes!("../testdata/descriptor1-ns")
]
).unwrap();
tx.execute(
sql!("INSERT INTO store (docid, content) VALUES (?1, ?2)"),
params![
DocumentId::digest(include_bytes!("../testdata/descriptor1-extra-info")),
include_bytes!("../testdata/descriptor1-extra-info")
]
).unwrap();
tx.execute(
sql!("INSERT INTO store (docid, content) VALUES (?1, ?2)"),
params![
DocumentId::digest(include_bytes!("../testdata/descriptor1-md")),
include_bytes!("../testdata/descriptor1-md"),
]).unwrap();
tx.execute(sql!(
"
INSERT INTO router_extra_info
(docid, unsigned_sha1, kp_relay_id_rsa_sha1)
VALUES (?1, ?2, ?3)
"
), params![
Sha256::digest(include_bytes!("../testdata/descriptor1-extra-info")),
Sha1::digest(include_bytes!("../testdata/descriptor1-extra-info-unsigned")),
"000004ACBB9D29BCBA17256BB35928DDBFC8ABA9",
]).unwrap();
tx.execute(sql!(
"
INSERT INTO router_descriptor
(docid, unsigned_sha1, unsigned_sha2, kp_relay_id_rsa_sha1, flavor, extra_unsigned_sha1)
VALUES
(?1, ?2, ?3, ?4, 'ns', ?5)
"
), params![
DocumentId::digest(include_bytes!("../testdata/descriptor1-ns")),
Sha1::digest(include_bytes!("../testdata/descriptor1-ns-unsigned")),
Sha256::digest(include_bytes!("../testdata/descriptor1-ns-unsigned")),
Sha1::from([0, 0, 4, 172, 187, 157, 41, 188, 186, 23, 37, 107, 179, 89, 40, 221, 191, 200, 171, 169]),
Sha1::digest(include_bytes!("../testdata/descriptor1-extra-info-unsigned")),
]).unwrap();
tx.execute(sql!(
"
INSERT INTO router_descriptor
(docid, unsigned_sha1, unsigned_sha2, kp_relay_id_rsa_sha1, flavor)
VALUES (?1, ?2, ?3, ?4, 'microdesc')
"
), params![
DocumentId::digest(include_bytes!("../testdata/descriptor1-md")),
Sha1::digest(include_bytes!("../testdata/descriptor1-md")),
Sha256::digest(include_bytes!("../testdata/descriptor1-md")),
Sha1::from([0, 0, 4, 172, 187, 157, 41, 188, 186, 23, 37, 107, 179, 89, 40, 221, 191, 200, 171, 169]),
]).unwrap();
tx.execute(
sql!(
"
INSERT INTO consensus
(docid, unsigned_sha3_256, flavor, valid_after, fresh_until, valid_until)
VALUES
(?1, ?2, ?3, ?4, ?5, ?6)
"
),
params![
*CONSENSUS_DOCID,
"0000000000000000000000000000000000000000000000000000000000000000", ConsensusFlavor::Plain.name(),
*VALID_AFTER,
*FRESH_UNTIL,
*VALID_UNTIL,
],
)
.unwrap();
tx.execute(
sql!(
"
INSERT INTO consensus
(docid, unsigned_sha3_256, flavor, valid_after, fresh_until, valid_until)
VALUES
(?1, ?2, ?3, ?4, ?5, ?6)
"
),
params![
*CONSENSUS_MD_DOCID,
"0000000000000000000000000000000000000000000000000000000000000001", ConsensusFlavor::Microdesc.name(),
*VALID_AFTER,
*FRESH_UNTIL,
*VALID_UNTIL,
],
)
.unwrap();
tx.execute(sql!(
"
INSERT INTO consensus_router_descriptor_member
(consensus_docid, unsigned_sha1, unsigned_sha2)
VALUES
(?1, ?2, NULL),
(?1, ?3, NULL)
"
), params![
*CONSENSUS_DOCID,
Sha1::digest(include_bytes!("../testdata/descriptor1-ns-unsigned")),
Sha1::digest(include_bytes!("../testdata/descriptor2-ns-unsigned")),
]).unwrap();
tx.execute(sql!(
"
INSERT INTO consensus_router_descriptor_member
(consensus_docid, unsigned_sha1, unsigned_sha2)
VALUES
(?1, NULL, ?2),
(?1, NULL, ?3)
"
), params![
*CONSENSUS_MD_DOCID,
Sha256::digest(include_bytes!("../testdata/descriptor1-md")),
Sha256::digest(include_bytes!("../testdata/descriptor2-md")),
]).unwrap();
tx.execute(sql!(
"
INSERT INTO authority_key_certificate
(docid, kp_auth_id_rsa_sha1, kp_auth_sign_rsa_sha1, dir_key_published, dir_key_expires)
VALUES
(:docid, :id_rsa, :sk_rsa, :published, :expires)
"
),
named_params! {
":docid": *CERT_DOCID,
":id_rsa": "49015F787433103580E3B66A1707A00E60F2D15B",
":sk_rsa": "C5D153A6F0DA7CC22277D229DCBBF929D0589FE0",
":published": 1764543578,
":expires": 1772492378,
}).unwrap();
})
.unwrap();
pool
}
#[test]
fn open_test() {
let db_dir = tempdir().unwrap();
let db_path = db_dir.path().join("db");
open(&db_path).unwrap();
let conn = Connection::open(&db_path).unwrap();
let version = conn
.query_one(
"SELECT version FROM arti_dirserver_schema_version WHERE rowid = 1",
params![],
|row| row.get::<_, String>(0),
)
.unwrap();
assert_eq!(version, "1");
conn.execute(
"UPDATE arti_dirserver_schema_version SET version = 42",
params![],
)
.unwrap();
drop(conn);
assert_eq!(
open(&db_path).unwrap_err().to_string(),
"incompatible schema version: 42"
);
}
#[test]
fn read_tx_test() {
let db_dir = tempdir().unwrap();
let db_path = db_dir.path().join("db");
let pool = open(&db_path).unwrap();
read_tx(&pool, |tx| {
tx.execute_batch("DELETE FROM arti_dirserver_schema_version")
.unwrap();
let e = tx
.query_one(
sql!("SELECT version FROM arti_dirserver_schema_version"),
params![],
|row| row.get::<_, String>(0),
)
.unwrap_err();
assert_eq!(e, rusqlite::Error::QueryReturnedNoRows);
})
.unwrap();
let version: String = read_tx(&pool, |tx| {
tx.query_one(
sql!("SELECT version FROM arti_dirserver_schema_version"),
params![],
|row| row.get(0),
)
.unwrap()
})
.unwrap();
assert_eq!(version, "1");
}
#[test]
fn rw_tx_test() {
let db_dir = tempdir().unwrap();
let db_path = db_dir.path().join("db");
let pool = open(&db_path).unwrap();
rw_tx(&pool, |tx| {
tx.execute_batch("DELETE FROM arti_dirserver_schema_version")
.unwrap();
})
.unwrap();
read_tx(&pool, |tx| {
let e = tx
.query_one(
sql!("SELECT version FROM arti_dirserver_schema_version"),
params![],
|row| row.get::<_, String>(0),
)
.unwrap_err();
assert_eq!(e, rusqlite::Error::QueryReturnedNoRows);
})
.unwrap();
}
#[test]
fn rw_tx_busy_timeout_working() {
let db_dir = tempdir().unwrap();
let db_path = db_dir.path().join("db");
let pool = open(db_path).unwrap();
let t1_acquired_lock = Arc::new(Once::new());
let t2_is_waiting = Arc::new(Once::new());
let t1 = std::thread::spawn({
let pool = pool.clone();
let t1_acquired_lock = t1_acquired_lock.clone();
let t2_is_waiting = t2_is_waiting.clone();
move || {
rw_tx(&pool, move |_tx| {
t1_acquired_lock.call_once(|| ());
println!("t1 acquired write lock");
t2_is_waiting.wait();
})
.unwrap();
println!("t2 released write lock");
}
});
println!("t2 waits for t1 to acquire write lock");
t1_acquired_lock.wait();
t2_is_waiting.call_once(|| ());
rw_tx(&pool, |_| ()).unwrap();
println!("t2 acquired and released write lock");
t1.join().unwrap();
}
#[test]
fn rw_tx_busy_timeout_busy() {
let db_dir = tempdir().unwrap();
let db_path = db_dir.path().join("db");
let pool = open(db_path).unwrap();
let t1_acquired_lock = Arc::new(Once::new());
let t2_gave_up = Arc::new(Once::new());
let t1 = std::thread::spawn({
let pool = pool.clone();
let t1_acquired_lock = t1_acquired_lock.clone();
let t2_gave_up = t2_gave_up.clone();
move || {
rw_tx(&pool, move |_tx| {
t1_acquired_lock.call_once(|| ());
println!("t1 acquired write lock");
t2_gave_up.wait();
})
.unwrap();
println!("t1 released write lock");
}
});
println!("t2 waits for t1 to acquire write lock");
t1_acquired_lock.wait();
let e = rw_tx(&pool, |_| ()).unwrap_err();
assert_eq!(
e.to_string(),
"low-level rusqlite error: database is locked"
);
println!("t2 gave up on acquiring write lock");
t2_gave_up.call_once(|| ());
t1.join().unwrap();
}
#[test]
fn store_insert_test() {
let db_dir = tempdir().unwrap();
let db_path = db_dir.path().join("db");
open(&db_path).unwrap();
let mut conn = Connection::open(&db_path).unwrap();
let tx = conn.transaction().unwrap();
let docid = store_insert(&tx, "foobar".as_bytes(), ContentEncoding::iter()).unwrap();
assert_eq!(
docid,
"C3AB8FF13720E8AD9047DD39466B3C8974E592C2FA383D4A3960714CAEF0C4F2"
);
let res = tx
.query_one(
sql!(
"
SELECT content
FROM store
WHERE docid = 'C3AB8FF13720E8AD9047DD39466B3C8974E592C2FA383D4A3960714CAEF0C4F2'
"
),
params![],
|row| row.get::<_, Vec<u8>>(0),
)
.unwrap();
assert_eq!(res, "foobar".as_bytes());
let mut stmt = tx.prepare_cached(sql!(
"
SELECT algorithm
FROM compressed_document
WHERE identity_docid = 'C3AB8FF13720E8AD9047DD39466B3C8974E592C2FA383D4A3960714CAEF0C4F2'
"
)).unwrap();
let algorithms = stmt
.query_map(params![], |row| row.get::<_, String>(0))
.unwrap();
let algorithms = algorithms.map(|x| x.unwrap()).collect::<HashSet<_>>();
assert_eq!(
algorithms,
HashSet::from([
"deflate".to_string(),
"gzip".to_string(),
"x-zstd".to_string(),
"x-tor-lzma".to_string()
])
);
let docid_second = store_insert(&tx, "foobar".as_bytes(), ContentEncoding::iter()).unwrap();
assert_eq!(docid, docid_second);
let n = tx
.execute(
sql!(
"
DELETE FROM
compressed_document
WHERE algorithm IN ('deflate', 'x-zstd')
"
),
params![],
)
.unwrap();
assert_eq!(n, 2);
let docid_third = store_insert(&tx, "foobar".as_bytes(), ContentEncoding::iter()).unwrap();
assert_eq!(docid, docid_third);
let algorithms = stmt
.query_map(params![], |row| row.get::<_, String>(0))
.unwrap();
let algorithms = algorithms.map(|x| x.unwrap()).collect::<HashSet<_>>();
assert_eq!(
algorithms,
HashSet::from([
"deflate".to_string(),
"gzip".to_string(),
"x-zstd".to_string(),
"x-tor-lzma".to_string()
])
);
}
#[test]
fn compress_test() {
fn contains(encoding: ContentEncoding, res: &[(ContentEncoding, Vec<u8>)]) {
assert!(res.iter().any(|x| x.0 == encoding));
}
const INPUT: &[u8] = "foobar".as_bytes();
let res = ContentEncoding::iter()
.map(|encoding| (encoding, compress(INPUT, encoding).unwrap()))
.collect::<Vec<_>>();
assert_eq!(res.len(), 5);
contains(ContentEncoding::Identity, &res);
contains(ContentEncoding::Deflate, &res);
contains(ContentEncoding::Gzip, &res);
contains(ContentEncoding::XTorLzma, &res);
contains(ContentEncoding::XZstd, &res);
for (encoding, compressed) in res {
let mut decompressed = Vec::new();
match encoding {
ContentEncoding::Identity => decompressed = compressed,
ContentEncoding::Deflate => {
DeflateDecoder::new(Cursor::new(compressed))
.read_to_end(&mut decompressed)
.unwrap();
}
ContentEncoding::Gzip => {
GzDecoder::new(Cursor::new(compressed))
.read_to_end(&mut decompressed)
.unwrap();
}
ContentEncoding::XTorLzma => {
lzma_rs::lzma_decompress(&mut Cursor::new(compressed), &mut decompressed)
.unwrap();
}
ContentEncoding::XZstd => {
decompressed = zstd::decode_all(Cursor::new(compressed)).unwrap();
}
}
assert_eq!(decompressed, INPUT);
}
}
#[test]
fn recent_consensus() {
let pool = create_dummy_db();
let no_tolerance = DirToleranceBuilder::default()
.pre_valid_tolerance(Duration::ZERO)
.post_valid_tolerance(Duration::ZERO)
.build()
.unwrap();
let liberal_tolerance = DirToleranceBuilder::default()
.pre_valid_tolerance(Duration::from_secs(60 * 60)) .post_valid_tolerance(Duration::from_secs(60 * 60)) .build()
.unwrap();
read_tx(&pool, move |tx| {
assert!(
ConsensusMeta::query_recent(
tx,
ConsensusFlavor::Plain,
&no_tolerance,
SystemTime::UNIX_EPOCH.into(),
)
.unwrap()
.is_none()
);
assert!(
ConsensusMeta::query_recent(
tx,
ConsensusFlavor::Plain,
&no_tolerance,
*VALID_UNTIL + Duration::from_secs(60 * 60 * 24 * 365),
)
.unwrap()
.is_none()
);
assert!(
ConsensusMeta::query_recent(
tx,
ConsensusFlavor::Plain,
&no_tolerance,
*VALID_AFTER - Duration::from_secs(1),
)
.unwrap()
.is_none()
);
assert!(
ConsensusMeta::query_recent(
tx,
ConsensusFlavor::Plain,
&no_tolerance,
*VALID_UNTIL + Duration::from_secs(1),
)
.unwrap()
.is_none()
);
let res1 = ConsensusMeta::query_recent(
tx,
ConsensusFlavor::Plain,
&no_tolerance,
*VALID_AFTER,
)
.unwrap()
.unwrap();
let res2 = ConsensusMeta::query_recent(
tx,
ConsensusFlavor::Plain,
&no_tolerance,
*VALID_UNTIL,
)
.unwrap()
.unwrap();
let res3 = ConsensusMeta::query_recent(
tx,
ConsensusFlavor::Plain,
&no_tolerance,
*VALID_AFTER + Duration::from_secs(60 * 30),
)
.unwrap()
.unwrap();
assert_eq!(
res1,
ConsensusMeta {
docid: *CONSENSUS_DOCID,
unsigned_sha3_256: Sha3_256::from([0; 32]),
flavor: ConsensusFlavor::Plain,
valid_after: *VALID_AFTER,
fresh_until: *FRESH_UNTIL,
valid_until: *VALID_UNTIL,
}
);
assert_eq!(res1, res2);
assert_eq!(res2, res3);
let res1 = ConsensusMeta::query_recent(
tx,
ConsensusFlavor::Plain,
&liberal_tolerance,
*VALID_AFTER - Duration::from_secs(60 * 30),
)
.unwrap()
.unwrap();
let res2 = ConsensusMeta::query_recent(
tx,
ConsensusFlavor::Plain,
&liberal_tolerance,
*VALID_UNTIL + Duration::from_secs(60 * 30),
)
.unwrap()
.unwrap();
assert_eq!(
res1,
ConsensusMeta {
docid: *CONSENSUS_DOCID,
unsigned_sha3_256: Sha3_256::from([0; 32]),
flavor: ConsensusFlavor::Plain,
valid_after: *VALID_AFTER,
fresh_until: *FRESH_UNTIL,
valid_until: *VALID_UNTIL,
}
);
assert_eq!(res1, res2);
})
.unwrap();
}
#[test]
fn sync_timeout() {
let cons = ConsensusMeta {
docid: *CONSENSUS_DOCID,
unsigned_sha3_256: Sha3_256::from([0; 32]),
flavor: ConsensusFlavor::Plain,
valid_after: *VALID_AFTER,
fresh_until: *FRESH_UNTIL,
valid_until: *VALID_UNTIL,
};
for _ in 0..10000 {
let when = cons.lifetime(&mut testing_rng());
assert!(when >= *FRESH_UNTIL);
assert!(when <= *FRESH_UNTIL_HALF);
}
}
#[test]
fn get_auth_cert() {
let pool = create_dummy_db();
let (found, missing) = read_tx(&pool, |tx| {
AuthCertMeta::query_recent(
tx,
&[],
&DirTolerance::default(),
(SystemTime::UNIX_EPOCH + Duration::from_secs(1765900013)).into(),
)
})
.unwrap()
.unwrap();
assert!(found.is_empty());
assert!(missing.is_empty());
let (found, missing) = read_tx(&pool, |tx| {
AuthCertMeta::query_recent(
tx,
&[
AuthCertKeyIds {
id_fingerprint: RsaIdentity::from_hex(
"49015F787433103580E3B66A1707A00E60F2D15B",
)
.unwrap(),
sk_fingerprint: RsaIdentity::from_hex(
"C5D153A6F0DA7CC22277D229DCBBF929D0589FE0",
)
.unwrap(),
},
AuthCertKeyIds {
id_fingerprint: RsaIdentity::from_hex(
"0000000000000000000000000000000000000000",
)
.unwrap(),
sk_fingerprint: RsaIdentity::from_hex(
"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF",
)
.unwrap(),
},
AuthCertKeyIds {
id_fingerprint: RsaIdentity::from_hex(
"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF",
)
.unwrap(),
sk_fingerprint: RsaIdentity::from_hex(
"0000000000000000000000000000000000000000",
)
.unwrap(),
},
],
&DirTolerance::default(),
(SystemTime::UNIX_EPOCH + Duration::from_secs(1765900013)).into(),
)
})
.unwrap()
.unwrap();
assert_eq!(
found,
vec![AuthCertMeta {
docid: DocumentId::digest(CERT_CONTENT),
kp_auth_id_rsa_sha1: Sha1::from([
73, 1, 95, 120, 116, 51, 16, 53, 128, 227, 182, 106, 23, 7, 160, 14, 96, 242,
209, 91
]),
kp_auth_sign_rsa_sha1: Sha1::from([
197, 209, 83, 166, 240, 218, 124, 194, 34, 119, 210, 41, 220, 187, 249, 41,
208, 88, 159, 224
]),
dir_key_published: (SystemTime::UNIX_EPOCH + Duration::from_secs(1764543578))
.into(),
dir_key_expires: (SystemTime::UNIX_EPOCH + Duration::from_secs(1772492378)).into()
}]
);
assert_eq!(
missing,
vec![
AuthCertKeyIds {
id_fingerprint: RsaIdentity::from_hex(
"0000000000000000000000000000000000000000",
)
.unwrap(),
sk_fingerprint: RsaIdentity::from_hex(
"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF",
)
.unwrap(),
},
AuthCertKeyIds {
id_fingerprint: RsaIdentity::from_hex(
"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF",
)
.unwrap(),
sk_fingerprint: RsaIdentity::from_hex(
"0000000000000000000000000000000000000000",
)
.unwrap(),
}
]
);
}
#[test]
fn missing_server_descriptors() {
let pool = create_dummy_db();
let meta = read_tx(&pool, |tx| {
ConsensusMeta::query_recent(
tx,
ConsensusFlavor::Plain,
&DirTolerance::default(),
*VALID_AFTER,
)
})
.unwrap()
.unwrap()
.unwrap();
let missing_servers = read_tx(&pool, |tx| meta.missing_servers(tx))
.unwrap()
.unwrap();
assert_eq!(
missing_servers,
HashSet::from([Sha1::digest(include_bytes!(
"../testdata/descriptor2-ns-unsigned"
))])
);
rw_tx(&pool, |tx| {
tx.execute(sql!("DELETE FROM router_descriptor"), params![])
})
.unwrap()
.unwrap();
let missing_servers = read_tx(&pool, |tx| meta.missing_servers(tx))
.unwrap()
.unwrap();
assert_eq!(
missing_servers,
HashSet::from([
Sha1::digest(include_bytes!("../testdata/descriptor1-ns-unsigned")),
Sha1::digest(include_bytes!("../testdata/descriptor2-ns-unsigned"))
])
);
}
#[test]
fn missing_extra_infos() {
let pool = create_dummy_db();
let meta = read_tx(&pool, |tx| {
ConsensusMeta::query_recent(
tx,
ConsensusFlavor::Plain,
&DirTolerance::default(),
*VALID_AFTER,
)
})
.unwrap()
.unwrap()
.unwrap();
let missing_extras = read_tx(&pool, |tx| meta.missing_extras(tx))
.unwrap()
.unwrap();
assert!(missing_extras.is_empty());
pool.get()
.unwrap()
.execute(sql!("DELETE FROM router_extra_info"), params![])
.unwrap();
let missing_extras = read_tx(&pool, |tx| meta.missing_extras(tx))
.unwrap()
.unwrap();
assert_eq!(
missing_extras,
HashSet::from([Sha1::digest(include_bytes!(
"../testdata/descriptor1-extra-info-unsigned"
))])
);
}
#[test]
fn missing_micro_descriptors() {
let pool = create_dummy_db();
let meta = read_tx(&pool, |tx| {
ConsensusMeta::query_recent(
tx,
ConsensusFlavor::Microdesc,
&DirTolerance::default(),
*VALID_AFTER,
)
})
.unwrap()
.unwrap()
.unwrap();
let missing_micros = read_tx(&pool, |tx| meta.missing_micros(tx))
.unwrap()
.unwrap();
assert_eq!(
missing_micros,
HashSet::from([Sha256::digest(include_bytes!("../testdata/descriptor2-md"))])
);
rw_tx(&pool, |tx| {
tx.execute(sql!("DELETE FROM router_descriptor"), params![])
})
.unwrap()
.unwrap();
let missing_servers = read_tx(&pool, |tx| meta.missing_micros(tx))
.unwrap()
.unwrap();
assert_eq!(
missing_servers,
HashSet::from([
Sha256::digest(include_bytes!("../testdata/descriptor1-md")),
Sha256::digest(include_bytes!("../testdata/descriptor2-md"))
])
);
}
}