Skip to content

Commit 3992bbe

Browse files
committed
fix: validate sqlite chain length metadata
1 parent 28ce0a6 commit 3992bbe

2 files changed

Lines changed: 22 additions & 0 deletions

File tree

minichain/persistence.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -219,11 +219,24 @@ def _load_snapshot_from_sqlite(db_path: str) -> dict[str, Any]:
219219
account_rows = conn.execute(
220220
"SELECT address, account_json FROM accounts ORDER BY address ASC"
221221
).fetchall()
222+
chain_length_row = conn.execute(
223+
"SELECT value FROM metadata WHERE key = ?",
224+
("chain_length",),
225+
).fetchone()
222226
except sqlite3.DatabaseError as exc:
223227
raise ValueError(f"Invalid SQLite persistence data in '{db_path}'") from exc
224228
finally:
225229
conn.close()
226230

231+
if chain_length_row is None:
232+
raise ValueError(f"Invalid SQLite persistence data in '{db_path}'")
233+
try:
234+
expected_chain_length = int(chain_length_row["value"])
235+
except (TypeError, ValueError) as exc:
236+
raise ValueError(f"Invalid SQLite persistence data in '{db_path}'") from exc
237+
if expected_chain_length != len(block_rows):
238+
raise ValueError(f"Invalid SQLite persistence data in '{db_path}'")
239+
227240
try:
228241
chain = [json.loads(row["block_json"]) for row in block_rows]
229242
state = {

tests/test_persistence.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -152,6 +152,15 @@ def test_missing_required_sqlite_table_raises(self):
152152
with self.assertRaises(ValueError):
153153
load(path=self.tmpdir)
154154

155+
def test_truncated_chain_rows_raises_value_error(self):
156+
bc, _, _ = self._chain_with_tx()
157+
save(bc, path=self.tmpdir)
158+
db_path = os.path.join(self.tmpdir, DB_FILE)
159+
with sqlite3.connect(db_path) as conn:
160+
conn.execute("DELETE FROM blocks WHERE height = 1")
161+
with self.assertRaises(ValueError):
162+
load(path=self.tmpdir)
163+
155164
def test_malformed_block_row_raises_value_error(self):
156165
bc = Blockchain()
157166
save(bc, path=self.tmpdir)

0 commit comments

Comments
 (0)