5#include <bitcoin-build-config.h>
9#include <chainparams.h>
29static std::span<const std::byte>
SpanFromBlob(sqlite3_stmt* stmt,
int col)
31 return {
reinterpret_cast<const std::byte*
>(sqlite3_column_blob(stmt, col)),
32 static_cast<size_t>(sqlite3_column_bytes(stmt, col))};
49 if (code == SQLITE_TRACE_STMT) {
50 auto* stmt =
static_cast<sqlite3_stmt*
>(param1);
54 char* expanded{sqlite3_stmt_readonly(stmt) ? sqlite3_expanded_sql(stmt) :
nullptr};
55 LogTrace(
BCLog::WALLETDB,
"[%s] SQLite Statement: %s\n", db->Filename(), expanded ? expanded : sqlite3_sql(stmt));
56 if (expanded) sqlite3_free(expanded);
63 std::span<const std::byte> blob,
64 const std::string& description)
70 int res = sqlite3_bind_blob(stmt, index, blob.data() ?
static_cast<const void*
>(blob.data()) :
"", blob.size(), SQLITE_STATIC);
71 if (res != SQLITE_OK) {
72 LogWarning(
"Unable to bind %s to statement: %s", description, sqlite3_errstr(res));
73 sqlite3_clear_bindings(stmt);
83 std::string stmt_text =
strprintf(
"PRAGMA %s", key);
84 sqlite3_stmt* pragma_read_stmt{
nullptr};
85 int ret = sqlite3_prepare_v2(db, stmt_text.c_str(), -1, &pragma_read_stmt,
nullptr);
86 if (
ret != SQLITE_OK) {
87 sqlite3_finalize(pragma_read_stmt);
88 error =
Untranslated(
strprintf(
"SQLiteDatabase: Failed to prepare the statement to fetch %s: %s", description, sqlite3_errstr(
ret)));
91 ret = sqlite3_step(pragma_read_stmt);
92 if (
ret != SQLITE_ROW) {
93 sqlite3_finalize(pragma_read_stmt);
97 int result = sqlite3_column_int(pragma_read_stmt, 0);
98 sqlite3_finalize(pragma_read_stmt);
102static void SetPragma(sqlite3* db,
const std::string& key,
const std::string& value,
const std::string& err_msg)
104 std::string stmt_text =
strprintf(
"PRAGMA %s = %s", key, value);
105 int ret = sqlite3_exec(db, stmt_text.c_str(),
nullptr,
nullptr,
nullptr);
106 if (
ret != SQLITE_OK) {
107 throw std::runtime_error(
strprintf(
"SQLiteDatabase: %s: %s\n", err_msg, sqlite3_errstr(
ret)));
112int SQLiteDatabase::g_sqlite_count = 0;
119 :
WalletDatabase(), m_dir_path(dir_path), m_file_path(fs::PathToString(file_path)), m_write_semaphore(1), m_use_unsafe_sync(options.use_unsafe_sync)
123 if (++g_sqlite_count == 1) {
126 if (
ret != SQLITE_OK) {
127 throw std::runtime_error(
strprintf(
"SQLiteDatabase: Failed to setup error log: %s\n", sqlite3_errstr(
ret)));
130 ret = sqlite3_config(SQLITE_CONFIG_SERIALIZED);
131 if (
ret != SQLITE_OK) {
132 throw std::runtime_error(
strprintf(
"SQLiteDatabase: Failed to configure serialized threading mode: %s\n", sqlite3_errstr(
ret)));
135 int ret = sqlite3_initialize();
136 if (
ret != SQLITE_OK) {
137 throw std::runtime_error(
strprintf(
"SQLiteDatabase: Failed to initialize SQLite: %s\n", sqlite3_errstr(
ret)));
142 Open(additional_flags);
143 }
catch (
const std::runtime_error&) {
152 const std::vector<std::pair<sqlite3_stmt**, const char*>> statements{
153 {&
m_read_stmt,
"SELECT value FROM main WHERE key = ?"},
160 for (
const auto& [stmt_prepared, stmt_text] : statements) {
161 if (*stmt_prepared ==
nullptr) {
162 int res = sqlite3_prepare_v2(
m_database.
m_db, stmt_text, -1, stmt_prepared,
nullptr);
163 if (res != SQLITE_OK) {
165 "SQLiteDatabase: Failed to setup SQL statements: %s\n", sqlite3_errstr(res)));
183 if (--g_sqlite_count == 0) {
184 int ret = sqlite3_shutdown();
185 if (
ret != SQLITE_OK) {
186 LogWarning(
"SQLiteDatabase: Failed to shutdown SQLite: %s", sqlite3_errstr(
ret));
197 if (!read_result.has_value())
return false;
198 uint32_t app_id =
static_cast<uint32_t
>(read_result.value());
200 if (app_id != net_magic) {
201 error =
strprintf(
_(
"SQLiteDatabase: Unexpected application id. Expected %u, got %u"), net_magic, app_id);
207 if (!read_result.has_value())
return false;
208 int32_t user_ver = read_result.value();
214 sqlite3_stmt* stmt{
nullptr};
215 int ret = sqlite3_prepare_v2(
m_db,
"PRAGMA integrity_check", -1, &stmt,
nullptr);
216 if (
ret != SQLITE_OK) {
217 sqlite3_finalize(stmt);
218 error =
strprintf(
_(
"SQLiteDatabase: Failed to prepare statement to verify database: %s"), sqlite3_errstr(
ret));
222 ret = sqlite3_step(stmt);
223 if (
ret == SQLITE_DONE) {
226 if (
ret != SQLITE_ROW) {
227 error =
strprintf(
_(
"SQLiteDatabase: Failed to execute statement to verify database: %s"), sqlite3_errstr(
ret));
230 const char*
msg = (
const char*)sqlite3_column_text(stmt, 0);
232 error =
strprintf(
_(
"SQLiteDatabase: Failed to read database verification error: %s"), sqlite3_errstr(
ret));
235 std::string str_msg(
msg);
236 if (str_msg ==
"ok") {
244 sqlite3_finalize(stmt);
245 return error.
empty();
255 int flags = SQLITE_OPEN_FULLMUTEX | SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | additional_flags;
257 if (
m_db ==
nullptr) {
258 if (!(
flags & SQLITE_OPEN_MEMORY)) {
262 if (
ret != SQLITE_OK) {
263 throw std::runtime_error(
strprintf(
"SQLiteDatabase: Failed to open database: %s\n", sqlite3_errstr(
ret)));
265 ret = sqlite3_extended_result_codes(
m_db, 1);
266 if (
ret != SQLITE_OK) {
267 throw std::runtime_error(
strprintf(
"SQLiteDatabase: Failed to enable extended result codes: %s\n", sqlite3_errstr(
ret)));
272 if (
ret != SQLITE_OK) {
278 if (sqlite3_db_readonly(
m_db,
"main") != 0) {
279 throw std::runtime_error(
"SQLiteDatabase: Database opened in readonly mode but read-write permissions are needed");
284 SetPragma(
m_db,
"locking_mode",
"exclusive",
"Unable to change database locking mode to exclusive");
286 int ret = sqlite3_exec(
m_db,
"BEGIN EXCLUSIVE TRANSACTION",
nullptr,
nullptr,
nullptr);
287 if (
ret != SQLITE_OK) {
288 throw std::runtime_error(
"SQLiteDatabase: Unable to obtain an exclusive lock on the database, is it being used by another instance of " CLIENT_NAME
"?\n");
290 ret = sqlite3_exec(
m_db,
"COMMIT",
nullptr,
nullptr,
nullptr);
291 if (
ret != SQLITE_OK) {
292 throw std::runtime_error(
strprintf(
"SQLiteDatabase: Unable to end exclusive lock transaction: %s\n", sqlite3_errstr(
ret)));
296 SetPragma(
m_db,
"fullfsync",
"true",
"Failed to enable fullfsync");
300 LogWarning(
"SQLite is configured to not wait for data to be flushed to disk. Data loss and corruption may occur.");
301 SetPragma(
m_db,
"synchronous",
"OFF",
"Failed to set synchronous mode to OFF");
306 sqlite3_stmt* check_main_stmt{
nullptr};
307 ret = sqlite3_prepare_v2(
m_db,
"SELECT name FROM sqlite_master WHERE type='table' AND name='main'", -1, &check_main_stmt,
nullptr);
308 if (
ret != SQLITE_OK) {
309 throw std::runtime_error(
strprintf(
"SQLiteDatabase: Failed to prepare statement to check table existence: %s\n", sqlite3_errstr(
ret)));
311 ret = sqlite3_step(check_main_stmt);
312 if (sqlite3_finalize(check_main_stmt) != SQLITE_OK) {
313 throw std::runtime_error(
strprintf(
"SQLiteDatabase: Failed to finalize statement checking table existence: %s\n", sqlite3_errstr(
ret)));
316 if (
ret == SQLITE_DONE) {
317 table_exists =
false;
318 }
else if (
ret == SQLITE_ROW) {
321 throw std::runtime_error(
strprintf(
"SQLiteDatabase: Failed to execute statement to check table existence: %s\n", sqlite3_errstr(
ret)));
326 ret = sqlite3_exec(
m_db,
"CREATE TABLE main(key BLOB PRIMARY KEY NOT NULL, value BLOB NOT NULL)",
nullptr,
nullptr,
nullptr);
327 if (
ret != SQLITE_OK) {
328 throw std::runtime_error(
strprintf(
"SQLiteDatabase: Failed to create new database: %s\n", sqlite3_errstr(
ret)));
334 "Failed to set the application id");
338 "Failed to set the wallet schema version");
345 int ret = sqlite3_exec(
m_db,
"VACUUM",
nullptr,
nullptr,
nullptr);
346 return ret == SQLITE_OK;
352 int res = sqlite3_open(dest.c_str(), &db_copy);
353 if (res != SQLITE_OK) {
354 sqlite3_close(db_copy);
357 sqlite3_backup* backup = sqlite3_backup_init(db_copy,
"main",
m_db,
"main");
359 LogWarning(
"Unable to begin sqlite backup: %s", sqlite3_errmsg(
m_db));
360 sqlite3_close(db_copy);
364 res = sqlite3_backup_step(backup, -1);
365 if (res != SQLITE_DONE) {
366 LogWarning(
"Unable to continue sqlite backup: %s", sqlite3_errstr(res));
367 sqlite3_backup_finish(backup);
368 sqlite3_close(db_copy);
371 res = sqlite3_backup_finish(backup);
372 sqlite3_close(db_copy);
373 return res == SQLITE_OK;
378 int res = sqlite3_close(
m_db);
379 if (res != SQLITE_OK) {
380 throw std::runtime_error(
strprintf(
"SQLiteDatabase: Failed to close database: %s\n", sqlite3_errstr(res)));
388 return m_db && sqlite3_get_autocommit(
m_db) == 0;
393 return sqlite3_exec(database.
m_db, statement.data(),
nullptr,
nullptr,
nullptr);
399 return std::make_unique<SQLiteBatch>(*
this);
403 : m_database(database)
413 bool force_conn_refresh =
false;
418 LogWarning(
"SQLiteBatch: Batch closed unexpectedly without the transaction being explicitly committed or aborted");
423 force_conn_refresh =
true;
424 LogWarning(
"SQLiteBatch: Batch closed and failed to abort transaction, resetting db connection..");
429 const std::vector<std::pair<sqlite3_stmt**, const char*>> statements{
437 for (
const auto& [stmt_prepared, stmt_description] : statements) {
438 int res = sqlite3_finalize(*stmt_prepared);
439 if (res != SQLITE_OK) {
440 LogWarning(
"SQLiteBatch: Batch closed but could not finalize %s statement: %s",
441 stmt_description, sqlite3_errstr(res));
443 *stmt_prepared =
nullptr;
446 if (force_conn_refresh) {
452 }
catch (
const std::runtime_error&) {
468 if (res != SQLITE_ROW) {
469 if (res != SQLITE_DONE) {
471 LogWarning(
"Unable to execute read statement: %s", sqlite3_errstr(res));
507 int res = sqlite3_step(stmt);
508 sqlite3_clear_bindings(stmt);
510 if (res != SQLITE_DONE) {
511 LogWarning(
"Unable to execute write statement: %s", sqlite3_errstr(res));
516 return res == SQLITE_DONE;
531 int res = sqlite3_step(stmt);
532 sqlite3_clear_bindings(stmt);
534 if (res != SQLITE_DONE) {
535 LogWarning(
"Unable to execute exec statement: %s", sqlite3_errstr(res));
540 return res == SQLITE_DONE;
563 return res == SQLITE_ROW;
569 if (res == SQLITE_DONE) {
572 if (res != SQLITE_ROW) {
573 LogWarning(
"Unable to execute cursor step: %s", sqlite3_errstr(res));
591 if (res != SQLITE_OK) {
592 LogWarning(
"Cursor closed but could not finalize cursor statement: %s",
593 sqlite3_errstr(res));
600 auto cursor = std::make_unique<SQLiteCursor>();
602 const char* stmt_text =
"SELECT key, value FROM main";
603 int res = sqlite3_prepare_v2(
m_database.
m_db, stmt_text, -1, &cursor->m_cursor_stmt,
nullptr);
604 if (res != SQLITE_OK) {
606 "%s: Failed to setup cursor SQL statement: %s\n", __func__, sqlite3_errstr(res)));
619 std::vector<std::byte> start_range(
prefix.begin(),
prefix.end());
620 std::vector<std::byte> end_range(
prefix.begin(),
prefix.end());
621 auto it = end_range.rbegin();
622 for (; it != end_range.rend(); ++it) {
623 if (*it == std::byte(std::numeric_limits<unsigned char>::max())) {
627 *it = std::byte(std::to_integer<unsigned char>(*it) + 1);
630 if (it == end_range.rend()) {
635 auto cursor = std::make_unique<SQLiteCursor>(start_range, end_range);
636 if (!cursor)
return nullptr;
638 const char* stmt_text = end_range.empty() ?
"SELECT key, value FROM main WHERE key >= ?" :
639 "SELECT key, value FROM main WHERE key >= ? AND key < ?";
640 int res = sqlite3_prepare_v2(
m_database.
m_db, stmt_text, -1, &cursor->m_cursor_stmt,
nullptr);
641 if (res != SQLITE_OK) {
643 "SQLiteDatabase: Failed to setup cursor SQL statement: %s\n", sqlite3_errstr(res)));
646 if (!
BindBlobToStatement(cursor->m_cursor_stmt, 1, cursor->m_prefix_range_start,
"prefix_start"))
return nullptr;
647 if (!end_range.empty()) {
648 if (!
BindBlobToStatement(cursor->m_cursor_stmt, 2, cursor->m_prefix_range_end,
"prefix_end"))
return nullptr;
660 if (res != SQLITE_OK) {
661 LogWarning(
"SQLiteBatch: Failed to begin the transaction");
666 return res == SQLITE_OK;
674 if (res != SQLITE_OK) {
675 LogWarning(
"SQLiteBatch: Failed to commit the transaction");
680 return res == SQLITE_OK;
688 if (res != SQLITE_OK) {
689 LogWarning(
"SQLiteBatch: Failed to abort the transaction");
694 return res == SQLITE_OK;
701 auto db = std::make_unique<SQLiteDatabase>(data_file.parent_path(), data_file, options);
702 if (options.
verify && !db->Verify(error)) {
708 }
catch (
const std::runtime_error& e) {
717 return std::string(sqlite3_libversion());
const CChainParams & Params()
Return the currently selected parameters.
#define Assert(val)
Identity function.
Double ended buffer combining vector and stream-like interfaces.
void write(std::span< const value_type > src)
bool ErasePrefix(std::span< const std::byte > prefix) override
bool ExecStatement(sqlite3_stmt *stmt, std::span< const std::byte > blob)
bool ReadKey(DataStream &&key, DataStream &value) override
bool TxnCommit() override
SQLiteBatch(SQLiteDatabase &database)
std::unique_ptr< SQliteExecHandler > m_exec_handler
bool HasKey(DataStream &&key) override
bool m_txn
Whether this batch has started a database transaction and whether it owns SQLiteDatabase::m_write_sem...
std::unique_ptr< DatabaseCursor > GetNewCursor() override
bool EraseKey(DataStream &&key) override
sqlite3_stmt * m_delete_stmt
std::unique_ptr< DatabaseCursor > GetNewPrefixCursor(std::span< const std::byte > prefix) override
sqlite3_stmt * m_read_stmt
sqlite3_stmt * m_overwrite_stmt
sqlite3_stmt * m_delete_prefix_stmt
void SetupSQLStatements()
sqlite3_stmt * m_insert_stmt
SQLiteDatabase & m_database
bool WriteKey(DataStream &&key, DataStream &&value, bool overwrite=true) override
Status Next(DataStream &key, DataStream &value) override
sqlite3_stmt * m_cursor_stmt
An instance of this class represents one SQLite3 database.
static Mutex g_sqlite_mutex
This mutex protects SQLite initialization and shutdown.
void Open() override
Open the database if it is not already opened.
std::string Filename() override
Return path to main database file for logs and error messages.
void Cleanup() noexcept EXCLUSIVE_LOCKS_REQUIRED(!g_sqlite_mutex)
const fs::path m_dir_path
void Close() override
Close the database.
bool Rewrite() override
Rewrite the entire database on disk.
bool Backup(const std::string &dest) const override
Back up the entire database to a file.
std::unique_ptr< DatabaseBatch > MakeBatch() override
Make a SQLiteBatch connected to this database.
void Open(int additional_flags)
std::binary_semaphore m_write_semaphore
const std::string m_file_path
bool Verify(bilingual_str &error)
bool HasActiveTxn()
Return true if there is an on-going txn in this connection.
virtual int Exec(SQLiteDatabase &database, const std::string &statement)
An instance of this class represents one database.
uint32_t ReadBE32(const B *ptr)
bool TryCreateDirectories(const fs::path &p)
Ignores exceptions thrown by create_directories if the requested directory exists.
#define LogTrace(category,...)
static bool LogAcceptCategory(BCLog::LogFlags category, BCLog::Level level)
Return true if log accepts specified category, at the specified level.
std::unique_ptr< SQLiteDatabase > MakeSQLiteDatabase(const fs::path &path, const DatabaseOptions &options, DatabaseStatus &status, bilingual_str &error)
fs::path SQLiteDataFile(const fs::path &path)
static std::span< const std::byte > SpanFromBlob(sqlite3_stmt *stmt, int col)
static std::optional< int > ReadPragmaInteger(sqlite3 *db, const std::string &key, const std::string &description, bilingual_str &error)
static constexpr int32_t WALLET_SCHEMA_VERSION
static bool BindBlobToStatement(sqlite3_stmt *stmt, int index, std::span< const std::byte > blob, const std::string &description)
static int TraceSqlCallback(unsigned code, void *context, void *param1, void *param2)
static void SetPragma(sqlite3 *db, const std::string &key, const std::string &value, const std::string &err_msg)
std::string SQLiteDatabaseVersion()
static void ErrorLogCallback(void *arg, int code, const char *msg)
bool verify
Check data integrity on load.
#define AssertLockNotHeld(cs)
consteval auto _(util::TranslatedLiteral str)
bilingual_str Untranslated(std::string original)
Mark a bilingual_str as untranslated.