1use anyhow::{Context, Result, ensure};
4use gent_crypto::{
5 Checkpoint, MAX_CHAIN_BYTES, MAX_CHAIN_LENGTH, SignedState, TrustAnchor, VerifiedState,
6};
7use rusqlite::{Connection, OptionalExtension, TransactionBehavior, params};
8use std::{
9 fs,
10 io::ErrorKind,
11 os::unix::fs::{OpenOptionsExt, PermissionsExt},
12 path::Path,
13};
14
15pub struct Replica {
16 db: Connection,
17}
18
19impl Replica {
20 pub fn open(home: &Path) -> Result<Self> {
22 crate::recovery::ensure_active(home)?;
23 crate::config::private_dir(home)?;
24 let path = home.join("authority.sqlite3");
25 match fs::OpenOptions::new()
26 .write(true)
27 .create_new(true)
28 .mode(0o600)
29 .open(&path)
30 {
31 Ok(_) => {}
32 Err(error) if error.kind() == ErrorKind::AlreadyExists => {}
33 Err(error) => return Err(error.into()),
34 }
35 let metadata = fs::symlink_metadata(&path)?;
36 ensure!(
37 metadata.is_file()
38 && !metadata.file_type().is_symlink()
39 && metadata.permissions().mode() & 0o077 == 0,
40 "authority database must be a private regular file"
41 );
42 let db = Connection::open(path)?;
43 db.busy_timeout(std::time::Duration::from_secs(5))?;
44 let version: i64 = db.pragma_query_value(None, "user_version", |row| row.get(0))?;
45 ensure!(
46 matches!(version, 0..=2),
47 "unsupported authority database version"
48 );
49 crate::storage::configure(&db)?;
50 db.execute_batch(
51 "
52 CREATE TABLE IF NOT EXISTS cluster_state (
53 singleton INTEGER PRIMARY KEY CHECK(singleton=1),
54 anchor BLOB NOT NULL, checkpoint BLOB NOT NULL, state BLOB NOT NULL
55 );
56 CREATE TABLE IF NOT EXISTS cluster_history (
57 revision INTEGER PRIMARY KEY, state BLOB NOT NULL
58 );
59 PRAGMA user_version=2;",
60 )?;
61 Ok(Self { db })
62 }
63
64 pub fn initialize(&mut self, state: &VerifiedState) -> Result<()> {
66 ensure!(
67 state.checkpoint().revision == 0,
68 "initialize with pinned genesis, then apply its history"
69 );
70 let tx = self
71 .db
72 .transaction_with_behavior(TransactionBehavior::Immediate)?;
73 tx.execute(
74 "INSERT INTO cluster_state VALUES (1,?1,?2,?3)",
75 params![
76 serde_json::to_vec(state.anchor())?,
77 serde_json::to_vec(state.checkpoint())?,
78 state.signed().encode()?
79 ],
80 )
81 .context("replica already initialized or storage unavailable")?;
82 tx.execute(
83 "INSERT INTO cluster_history VALUES (0,?1)",
84 [state.signed().encode()?],
85 )?;
86 tx.commit()?;
87 Ok(())
88 }
89
90 pub fn load(&self) -> Result<VerifiedState> {
91 load(&self.db)
92 }
93
94 pub fn apply(
97 &mut self,
98 expected: &Checkpoint,
99 updates: &[SignedState],
100 now: u64,
101 ) -> Result<VerifiedState> {
102 self.advance(expected, updates, Some(now))
103 }
104
105 pub fn apply_history(
108 &mut self,
109 expected: &Checkpoint,
110 updates: &[SignedState],
111 ) -> Result<VerifiedState> {
112 self.advance(expected, updates, None)
113 }
114
115 fn advance(
116 &mut self,
117 expected: &Checkpoint,
118 updates: &[SignedState],
119 now: Option<u64>,
120 ) -> Result<VerifiedState> {
121 let tx = self
122 .db
123 .transaction_with_behavior(TransactionBehavior::Immediate)?;
124 let mut current = load(&tx)?;
125 ensure!(
126 current.checkpoint() == expected,
127 "configuration changed; reload before applying this revision"
128 );
129 match now {
130 Some(now) => current.apply_chain(updates, now)?,
131 None => current.advance_history(updates)?,
132 }
133 for state in updates {
134 tx.execute(
135 "INSERT INTO cluster_history VALUES (?1,?2)",
136 params![i64::try_from(state.state.revision)?, state.encode()?],
137 )?;
138 }
139 tx.execute(
140 "UPDATE cluster_state SET checkpoint=?1,state=?2 WHERE singleton=1",
141 params![
142 serde_json::to_vec(current.checkpoint())?,
143 current.signed().encode()?
144 ],
145 )?;
146 tx.commit()?;
147 Ok(current)
148 }
149
150 pub fn history(&self, after_revision: u64, limit: usize) -> Result<Vec<SignedState>> {
152 ensure!(
153 limit > 0 && limit <= MAX_CHAIN_LENGTH,
154 "invalid history limit"
155 );
156 let mut statement = self.db.prepare(
157 "SELECT state FROM cluster_history WHERE revision>?1 ORDER BY revision LIMIT ?2",
158 )?;
159 let rows = statement.query_map(
160 params![i64::try_from(after_revision)?, i64::try_from(limit)?],
161 |row| row.get::<_, Vec<u8>>(0),
162 )?;
163 let mut history = Vec::new();
164 let mut total_bytes = 0;
165 for row in rows {
166 let bytes = row?;
167 if total_bytes + bytes.len() > MAX_CHAIN_BYTES {
168 break;
169 }
170 total_bytes += bytes.len();
171 history.push(SignedState::decode(&bytes)?);
172 }
173 Ok(history)
174 }
175}
176
177fn load(db: &Connection) -> Result<VerifiedState> {
178 let (anchor, checkpoint, state): (Vec<u8>, Vec<u8>, Vec<u8>) = db
179 .query_row(
180 "SELECT anchor,checkpoint,state FROM cluster_state WHERE singleton=1",
181 [],
182 |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)),
183 )
184 .optional()?
185 .context("authority replica is not initialized")?;
186 VerifiedState::restore(
187 serde_json::from_slice::<TrustAnchor>(&anchor)?,
188 serde_json::from_slice::<Checkpoint>(&checkpoint)?,
189 SignedState::decode(&state)?,
190 )
191}