Bitcoin Core  27.99.0
P2P Digital Currency
sqlite.cpp
Go to the documentation of this file.
1 // Copyright (c) 2020-2022 The Bitcoin Core developers
2 // Distributed under the MIT software license, see the accompanying
3 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
4 
5 #include <config/bitcoin-config.h> // IWYU pragma: keep
6 
7 #include <wallet/sqlite.h>
8 
9 #include <chainparams.h>
10 #include <crypto/common.h>
11 #include <logging.h>
12 #include <sync.h>
13 #include <util/fs_helpers.h>
14 #include <util/check.h>
15 #include <util/strencodings.h>
16 #include <util/translation.h>
17 #include <wallet/db.h>
18 
19 #include <sqlite3.h>
20 #include <stdint.h>
21 
22 #include <optional>
23 #include <utility>
24 #include <vector>
25 
26 namespace wallet {
27 static constexpr int32_t WALLET_SCHEMA_VERSION = 0;
28 
29 static Span<const std::byte> SpanFromBlob(sqlite3_stmt* stmt, int col)
30 {
31  return {reinterpret_cast<const std::byte*>(sqlite3_column_blob(stmt, col)),
32  static_cast<size_t>(sqlite3_column_bytes(stmt, col))};
33 }
34 
35 static void ErrorLogCallback(void* arg, int code, const char* msg)
36 {
37  // From sqlite3_config() documentation for the SQLITE_CONFIG_LOG option:
38  // "The void pointer that is the second argument to SQLITE_CONFIG_LOG is passed through as
39  // the first parameter to the application-defined logger function whenever that function is
40  // invoked."
41  // Assert that this is the case:
42  assert(arg == nullptr);
43  LogPrintf("SQLite Error. Code: %d. Message: %s\n", code, msg);
44 }
45 
46 static int TraceSqlCallback(unsigned code, void* context, void* param1, void* param2)
47 {
48  auto* db = static_cast<SQLiteDatabase*>(context);
49  if (code == SQLITE_TRACE_STMT) {
50  auto* stmt = static_cast<sqlite3_stmt*>(param1);
51  // To be conservative and avoid leaking potentially secret information
52  // in the log file, only expand statements that query the database, not
53  // statements that update the database.
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);
57  }
58  return SQLITE_OK;
59 }
60 
61 static bool BindBlobToStatement(sqlite3_stmt* stmt,
62  int index,
64  const std::string& description)
65 {
66  // Pass a pointer to the empty string "" below instead of passing the
67  // blob.data() pointer if the blob.data() pointer is null. Passing a null
68  // data pointer to bind_blob would cause sqlite to bind the SQL NULL value
69  // instead of the empty blob value X'', which would mess up SQL comparisons.
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  LogPrintf("Unable to bind %s to statement: %s\n", description, sqlite3_errstr(res));
73  sqlite3_clear_bindings(stmt);
74  sqlite3_reset(stmt);
75  return false;
76  }
77 
78  return true;
79 }
80 
81 static std::optional<int> ReadPragmaInteger(sqlite3* db, const std::string& key, const std::string& description, bilingual_str& error)
82 {
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)));
89  return std::nullopt;
90  }
91  ret = sqlite3_step(pragma_read_stmt);
92  if (ret != SQLITE_ROW) {
93  sqlite3_finalize(pragma_read_stmt);
94  error = Untranslated(strprintf("SQLiteDatabase: Failed to fetch %s: %s", description, sqlite3_errstr(ret)));
95  return std::nullopt;
96  }
97  int result = sqlite3_column_int(pragma_read_stmt, 0);
98  sqlite3_finalize(pragma_read_stmt);
99  return result;
100 }
101 
102 static void SetPragma(sqlite3* db, const std::string& key, const std::string& value, const std::string& err_msg)
103 {
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)));
108  }
109 }
110 
112 int SQLiteDatabase::g_sqlite_count = 0;
113 
114 SQLiteDatabase::SQLiteDatabase(const fs::path& dir_path, const fs::path& file_path, const DatabaseOptions& options, bool mock)
115  : WalletDatabase(), m_mock(mock), m_dir_path(fs::PathToString(dir_path)), m_file_path(fs::PathToString(file_path)), m_write_semaphore(1), m_use_unsafe_sync(options.use_unsafe_sync)
116 {
117  {
119  LogPrintf("Using SQLite Version %s\n", SQLiteDatabaseVersion());
120  LogPrintf("Using wallet %s\n", m_dir_path);
121 
122  if (++g_sqlite_count == 1) {
123  // Setup logging
124  int ret = sqlite3_config(SQLITE_CONFIG_LOG, ErrorLogCallback, nullptr);
125  if (ret != SQLITE_OK) {
126  throw std::runtime_error(strprintf("SQLiteDatabase: Failed to setup error log: %s\n", sqlite3_errstr(ret)));
127  }
128  // Force serialized threading mode
129  ret = sqlite3_config(SQLITE_CONFIG_SERIALIZED);
130  if (ret != SQLITE_OK) {
131  throw std::runtime_error(strprintf("SQLiteDatabase: Failed to configure serialized threading mode: %s\n", sqlite3_errstr(ret)));
132  }
133  }
134  int ret = sqlite3_initialize(); // This is a no-op if sqlite3 is already initialized
135  if (ret != SQLITE_OK) {
136  throw std::runtime_error(strprintf("SQLiteDatabase: Failed to initialize SQLite: %s\n", sqlite3_errstr(ret)));
137  }
138  }
139 
140  try {
141  Open();
142  } catch (const std::runtime_error&) {
143  // If open fails, cleanup this object and rethrow the exception
144  Cleanup();
145  throw;
146  }
147 }
148 
150 {
151  const std::vector<std::pair<sqlite3_stmt**, const char*>> statements{
152  {&m_read_stmt, "SELECT value FROM main WHERE key = ?"},
153  {&m_insert_stmt, "INSERT INTO main VALUES(?, ?)"},
154  {&m_overwrite_stmt, "INSERT or REPLACE into main values(?, ?)"},
155  {&m_delete_stmt, "DELETE FROM main WHERE key = ?"},
156  {&m_delete_prefix_stmt, "DELETE FROM main WHERE instr(key, ?) = 1"},
157  };
158 
159  for (const auto& [stmt_prepared, stmt_text] : statements) {
160  if (*stmt_prepared == nullptr) {
161  int res = sqlite3_prepare_v2(m_database.m_db, stmt_text, -1, stmt_prepared, nullptr);
162  if (res != SQLITE_OK) {
163  throw std::runtime_error(strprintf(
164  "SQLiteDatabase: Failed to setup SQL statements: %s\n", sqlite3_errstr(res)));
165  }
166  }
167  }
168 }
169 
171 {
172  Cleanup();
173 }
174 
175 void SQLiteDatabase::Cleanup() noexcept
176 {
178 
179  Close();
180 
182  if (--g_sqlite_count == 0) {
183  int ret = sqlite3_shutdown();
184  if (ret != SQLITE_OK) {
185  LogPrintf("SQLiteDatabase: Failed to shutdown SQLite: %s\n", sqlite3_errstr(ret));
186  }
187  }
188 }
189 
191 {
192  assert(m_db);
193 
194  // Check the application ID matches our network magic
195  auto read_result = ReadPragmaInteger(m_db, "application_id", "the application id", error);
196  if (!read_result.has_value()) return false;
197  uint32_t app_id = static_cast<uint32_t>(read_result.value());
198  uint32_t net_magic = ReadBE32(Params().MessageStart().data());
199  if (app_id != net_magic) {
200  error = strprintf(_("SQLiteDatabase: Unexpected application id. Expected %u, got %u"), net_magic, app_id);
201  return false;
202  }
203 
204  // Check our schema version
205  read_result = ReadPragmaInteger(m_db, "user_version", "sqlite wallet schema version", error);
206  if (!read_result.has_value()) return false;
207  int32_t user_ver = read_result.value();
208  if (user_ver != WALLET_SCHEMA_VERSION) {
209  error = strprintf(_("SQLiteDatabase: Unknown sqlite wallet schema version %d. Only version %d is supported"), user_ver, WALLET_SCHEMA_VERSION);
210  return false;
211  }
212 
213  sqlite3_stmt* stmt{nullptr};
214  int ret = sqlite3_prepare_v2(m_db, "PRAGMA integrity_check", -1, &stmt, nullptr);
215  if (ret != SQLITE_OK) {
216  sqlite3_finalize(stmt);
217  error = strprintf(_("SQLiteDatabase: Failed to prepare statement to verify database: %s"), sqlite3_errstr(ret));
218  return false;
219  }
220  while (true) {
221  ret = sqlite3_step(stmt);
222  if (ret == SQLITE_DONE) {
223  break;
224  }
225  if (ret != SQLITE_ROW) {
226  error = strprintf(_("SQLiteDatabase: Failed to execute statement to verify database: %s"), sqlite3_errstr(ret));
227  break;
228  }
229  const char* msg = (const char*)sqlite3_column_text(stmt, 0);
230  if (!msg) {
231  error = strprintf(_("SQLiteDatabase: Failed to read database verification error: %s"), sqlite3_errstr(ret));
232  break;
233  }
234  std::string str_msg(msg);
235  if (str_msg == "ok") {
236  continue;
237  }
238  if (error.empty()) {
239  error = _("Failed to verify database") + Untranslated("\n");
240  }
241  error += Untranslated(strprintf("%s\n", str_msg));
242  }
243  sqlite3_finalize(stmt);
244  return error.empty();
245 }
246 
248 {
249  int flags = SQLITE_OPEN_FULLMUTEX | SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE;
250  if (m_mock) {
251  flags |= SQLITE_OPEN_MEMORY; // In memory database for mock db
252  }
253 
254  if (m_db == nullptr) {
255  if (!m_mock) {
257  }
258  int ret = sqlite3_open_v2(m_file_path.c_str(), &m_db, flags, nullptr);
259  if (ret != SQLITE_OK) {
260  throw std::runtime_error(strprintf("SQLiteDatabase: Failed to open database: %s\n", sqlite3_errstr(ret)));
261  }
262  ret = sqlite3_extended_result_codes(m_db, 1);
263  if (ret != SQLITE_OK) {
264  throw std::runtime_error(strprintf("SQLiteDatabase: Failed to enable extended result codes: %s\n", sqlite3_errstr(ret)));
265  }
266  // Trace SQL statements if tracing is enabled with -debug=walletdb -loglevel=walletdb:trace
268  ret = sqlite3_trace_v2(m_db, SQLITE_TRACE_STMT, TraceSqlCallback, this);
269  if (ret != SQLITE_OK) {
270  LogPrintf("Failed to enable SQL tracing for %s\n", Filename());
271  }
272  }
273  }
274 
275  if (sqlite3_db_readonly(m_db, "main") != 0) {
276  throw std::runtime_error("SQLiteDatabase: Database opened in readonly mode but read-write permissions are needed");
277  }
278 
279  // Acquire an exclusive lock on the database
280  // First change the locking mode to exclusive
281  SetPragma(m_db, "locking_mode", "exclusive", "Unable to change database locking mode to exclusive");
282  // Now begin a transaction to acquire the exclusive lock. This lock won't be released until we close because of the exclusive locking mode.
283  int ret = sqlite3_exec(m_db, "BEGIN EXCLUSIVE TRANSACTION", nullptr, nullptr, nullptr);
284  if (ret != SQLITE_OK) {
285  throw std::runtime_error("SQLiteDatabase: Unable to obtain an exclusive lock on the database, is it being used by another instance of " PACKAGE_NAME "?\n");
286  }
287  ret = sqlite3_exec(m_db, "COMMIT", nullptr, nullptr, nullptr);
288  if (ret != SQLITE_OK) {
289  throw std::runtime_error(strprintf("SQLiteDatabase: Unable to end exclusive lock transaction: %s\n", sqlite3_errstr(ret)));
290  }
291 
292  // Enable fullfsync for the platforms that use it
293  SetPragma(m_db, "fullfsync", "true", "Failed to enable fullfsync");
294 
295  if (m_use_unsafe_sync) {
296  // Use normal synchronous mode for the journal
297  LogPrintf("WARNING SQLite is configured to not wait for data to be flushed to disk. Data loss and corruption may occur.\n");
298  SetPragma(m_db, "synchronous", "OFF", "Failed to set synchronous mode to OFF");
299  }
300 
301  // Make the table for our key-value pairs
302  // First check that the main table exists
303  sqlite3_stmt* check_main_stmt{nullptr};
304  ret = sqlite3_prepare_v2(m_db, "SELECT name FROM sqlite_master WHERE type='table' AND name='main'", -1, &check_main_stmt, nullptr);
305  if (ret != SQLITE_OK) {
306  throw std::runtime_error(strprintf("SQLiteDatabase: Failed to prepare statement to check table existence: %s\n", sqlite3_errstr(ret)));
307  }
308  ret = sqlite3_step(check_main_stmt);
309  if (sqlite3_finalize(check_main_stmt) != SQLITE_OK) {
310  throw std::runtime_error(strprintf("SQLiteDatabase: Failed to finalize statement checking table existence: %s\n", sqlite3_errstr(ret)));
311  }
312  bool table_exists;
313  if (ret == SQLITE_DONE) {
314  table_exists = false;
315  } else if (ret == SQLITE_ROW) {
316  table_exists = true;
317  } else {
318  throw std::runtime_error(strprintf("SQLiteDatabase: Failed to execute statement to check table existence: %s\n", sqlite3_errstr(ret)));
319  }
320 
321  // Do the db setup things because the table doesn't exist only when we are creating a new wallet
322  if (!table_exists) {
323  ret = sqlite3_exec(m_db, "CREATE TABLE main(key BLOB PRIMARY KEY NOT NULL, value BLOB NOT NULL)", nullptr, nullptr, nullptr);
324  if (ret != SQLITE_OK) {
325  throw std::runtime_error(strprintf("SQLiteDatabase: Failed to create new database: %s\n", sqlite3_errstr(ret)));
326  }
327 
328  // Set the application id
329  uint32_t app_id = ReadBE32(Params().MessageStart().data());
330  SetPragma(m_db, "application_id", strprintf("%d", static_cast<int32_t>(app_id)),
331  "Failed to set the application id");
332 
333  // Set the user version
334  SetPragma(m_db, "user_version", strprintf("%d", WALLET_SCHEMA_VERSION),
335  "Failed to set the wallet schema version");
336  }
337 }
338 
339 bool SQLiteDatabase::Rewrite(const char* skip)
340 {
341  // Rewrite the database using the VACUUM command: https://sqlite.org/lang_vacuum.html
342  int ret = sqlite3_exec(m_db, "VACUUM", nullptr, nullptr, nullptr);
343  return ret == SQLITE_OK;
344 }
345 
346 bool SQLiteDatabase::Backup(const std::string& dest) const
347 {
348  sqlite3* db_copy;
349  int res = sqlite3_open(dest.c_str(), &db_copy);
350  if (res != SQLITE_OK) {
351  sqlite3_close(db_copy);
352  return false;
353  }
354  sqlite3_backup* backup = sqlite3_backup_init(db_copy, "main", m_db, "main");
355  if (!backup) {
356  LogPrintf("%s: Unable to begin backup: %s\n", __func__, sqlite3_errmsg(m_db));
357  sqlite3_close(db_copy);
358  return false;
359  }
360  // Specifying -1 will copy all of the pages
361  res = sqlite3_backup_step(backup, -1);
362  if (res != SQLITE_DONE) {
363  LogPrintf("%s: Unable to backup: %s\n", __func__, sqlite3_errstr(res));
364  sqlite3_backup_finish(backup);
365  sqlite3_close(db_copy);
366  return false;
367  }
368  res = sqlite3_backup_finish(backup);
369  sqlite3_close(db_copy);
370  return res == SQLITE_OK;
371 }
372 
374 {
375  int res = sqlite3_close(m_db);
376  if (res != SQLITE_OK) {
377  throw std::runtime_error(strprintf("SQLiteDatabase: Failed to close database: %s\n", sqlite3_errstr(res)));
378  }
379  m_db = nullptr;
380 }
381 
383 {
384  // 'sqlite3_get_autocommit' returns true by default, and false if a transaction has begun and not been committed or rolled back.
385  return m_db && sqlite3_get_autocommit(m_db) == 0;
386 }
387 
388 int SQliteExecHandler::Exec(SQLiteDatabase& database, const std::string& statement)
389 {
390  return sqlite3_exec(database.m_db, statement.data(), nullptr, nullptr, nullptr);
391 }
392 
393 std::unique_ptr<DatabaseBatch> SQLiteDatabase::MakeBatch(bool flush_on_close)
394 {
395  // We ignore flush_on_close because we don't do manual flushing for SQLite
396  return std::make_unique<SQLiteBatch>(*this);
397 }
398 
400  : m_database(database)
401 {
402  // Make sure we have a db handle
404 
406 }
407 
409 {
410  bool force_conn_refresh = false;
411 
412  // If we began a transaction, and it wasn't committed, abort the transaction in progress
413  if (m_txn) {
414  if (TxnAbort()) {
415  LogPrintf("SQLiteBatch: Batch closed unexpectedly without the transaction being explicitly committed or aborted\n");
416  } else {
417  // If transaction cannot be aborted, it means there is a bug or there has been data corruption. Try to recover in this case
418  // by closing and reopening the database. Closing the database should also ensure that any changes made since the transaction
419  // was opened will be rolled back and future transactions can succeed without committing old data.
420  force_conn_refresh = true;
421  LogPrintf("SQLiteBatch: Batch closed and failed to abort transaction, resetting db connection..\n");
422  }
423  }
424 
425  // Free all of the prepared statements
426  const std::vector<std::pair<sqlite3_stmt**, const char*>> statements{
427  {&m_read_stmt, "read"},
428  {&m_insert_stmt, "insert"},
429  {&m_overwrite_stmt, "overwrite"},
430  {&m_delete_stmt, "delete"},
431  {&m_delete_prefix_stmt, "delete prefix"},
432  };
433 
434  for (const auto& [stmt_prepared, stmt_description] : statements) {
435  int res = sqlite3_finalize(*stmt_prepared);
436  if (res != SQLITE_OK) {
437  LogPrintf("SQLiteBatch: Batch closed but could not finalize %s statement: %s\n",
438  stmt_description, sqlite3_errstr(res));
439  }
440  *stmt_prepared = nullptr;
441  }
442 
443  if (force_conn_refresh) {
444  m_database.Close();
445  try {
446  m_database.Open();
447  // If TxnAbort failed and we refreshed the connection, the semaphore was not released, so release it here to avoid deadlocks on future writes.
449  } catch (const std::runtime_error&) {
450  // If open fails, cleanup this object and rethrow the exception
451  m_database.Close();
452  throw;
453  }
454  }
455 }
456 
458 {
459  if (!m_database.m_db) return false;
461 
462  // Bind: leftmost parameter in statement is index 1
463  if (!BindBlobToStatement(m_read_stmt, 1, key, "key")) return false;
464  int res = sqlite3_step(m_read_stmt);
465  if (res != SQLITE_ROW) {
466  if (res != SQLITE_DONE) {
467  // SQLITE_DONE means "not found", don't log an error in that case.
468  LogPrintf("%s: Unable to execute statement: %s\n", __func__, sqlite3_errstr(res));
469  }
470  sqlite3_clear_bindings(m_read_stmt);
471  sqlite3_reset(m_read_stmt);
472  return false;
473  }
474  // Leftmost column in result is index 0
475  value.clear();
476  value.write(SpanFromBlob(m_read_stmt, 0));
477 
478  sqlite3_clear_bindings(m_read_stmt);
479  sqlite3_reset(m_read_stmt);
480  return true;
481 }
482 
483 bool SQLiteBatch::WriteKey(DataStream&& key, DataStream&& value, bool overwrite)
484 {
485  if (!m_database.m_db) return false;
487 
488  sqlite3_stmt* stmt;
489  if (overwrite) {
490  stmt = m_overwrite_stmt;
491  } else {
492  stmt = m_insert_stmt;
493  }
494 
495  // Bind: leftmost parameter in statement is index 1
496  // Insert index 1 is key, 2 is value
497  if (!BindBlobToStatement(stmt, 1, key, "key")) return false;
498  if (!BindBlobToStatement(stmt, 2, value, "value")) return false;
499 
500  // Acquire semaphore if not previously acquired when creating a transaction.
502 
503  // Execute
504  int res = sqlite3_step(stmt);
505  sqlite3_clear_bindings(stmt);
506  sqlite3_reset(stmt);
507  if (res != SQLITE_DONE) {
508  LogPrintf("%s: Unable to execute statement: %s\n", __func__, sqlite3_errstr(res));
509  }
510 
512 
513  return res == SQLITE_DONE;
514 }
515 
516 bool SQLiteBatch::ExecStatement(sqlite3_stmt* stmt, Span<const std::byte> blob)
517 {
518  if (!m_database.m_db) return false;
519  assert(stmt);
520 
521  // Bind: leftmost parameter in statement is index 1
522  if (!BindBlobToStatement(stmt, 1, blob, "key")) return false;
523 
524  // Acquire semaphore if not previously acquired when creating a transaction.
526 
527  // Execute
528  int res = sqlite3_step(stmt);
529  sqlite3_clear_bindings(stmt);
530  sqlite3_reset(stmt);
531  if (res != SQLITE_DONE) {
532  LogPrintf("%s: Unable to execute statement: %s\n", __func__, sqlite3_errstr(res));
533  }
534 
536 
537  return res == SQLITE_DONE;
538 }
539 
541 {
542  return ExecStatement(m_delete_stmt, key);
543 }
544 
546 {
548 }
549 
551 {
552  if (!m_database.m_db) return false;
554 
555  // Bind: leftmost parameter in statement is index 1
556  if (!BindBlobToStatement(m_read_stmt, 1, key, "key")) return false;
557  int res = sqlite3_step(m_read_stmt);
558  sqlite3_clear_bindings(m_read_stmt);
559  sqlite3_reset(m_read_stmt);
560  return res == SQLITE_ROW;
561 }
562 
564 {
565  int res = sqlite3_step(m_cursor_stmt);
566  if (res == SQLITE_DONE) {
567  return Status::DONE;
568  }
569  if (res != SQLITE_ROW) {
570  LogPrintf("%s: Unable to execute cursor step: %s\n", __func__, sqlite3_errstr(res));
571  return Status::FAIL;
572  }
573 
574  key.clear();
575  value.clear();
576 
577  // Leftmost column in result is index 0
579  value.write(SpanFromBlob(m_cursor_stmt, 1));
580  return Status::MORE;
581 }
582 
584 {
585  sqlite3_clear_bindings(m_cursor_stmt);
586  sqlite3_reset(m_cursor_stmt);
587  int res = sqlite3_finalize(m_cursor_stmt);
588  if (res != SQLITE_OK) {
589  LogPrintf("%s: cursor closed but could not finalize cursor statement: %s\n",
590  __func__, sqlite3_errstr(res));
591  }
592 }
593 
594 std::unique_ptr<DatabaseCursor> SQLiteBatch::GetNewCursor()
595 {
596  if (!m_database.m_db) return nullptr;
597  auto cursor = std::make_unique<SQLiteCursor>();
598 
599  const char* stmt_text = "SELECT key, value FROM main";
600  int res = sqlite3_prepare_v2(m_database.m_db, stmt_text, -1, &cursor->m_cursor_stmt, nullptr);
601  if (res != SQLITE_OK) {
602  throw std::runtime_error(strprintf(
603  "%s: Failed to setup cursor SQL statement: %s\n", __func__, sqlite3_errstr(res)));
604  }
605 
606  return cursor;
607 }
608 
610 {
611  if (!m_database.m_db) return nullptr;
612 
613  // To get just the records we want, the SQL statement does a comparison of the binary data
614  // where the data must be greater than or equal to the prefix, and less than
615  // the prefix incremented by one (when interpreted as an integer)
616  std::vector<std::byte> start_range(prefix.begin(), prefix.end());
617  std::vector<std::byte> end_range(prefix.begin(), prefix.end());
618  auto it = end_range.rbegin();
619  for (; it != end_range.rend(); ++it) {
620  if (*it == std::byte(std::numeric_limits<unsigned char>::max())) {
621  *it = std::byte(0);
622  continue;
623  }
624  *it = std::byte(std::to_integer<unsigned char>(*it) + 1);
625  break;
626  }
627  if (it == end_range.rend()) {
628  // If the prefix is all 0xff bytes, clear end_range as we won't need it
629  end_range.clear();
630  }
631 
632  auto cursor = std::make_unique<SQLiteCursor>(start_range, end_range);
633  if (!cursor) return nullptr;
634 
635  const char* stmt_text = end_range.empty() ? "SELECT key, value FROM main WHERE key >= ?" :
636  "SELECT key, value FROM main WHERE key >= ? AND key < ?";
637  int res = sqlite3_prepare_v2(m_database.m_db, stmt_text, -1, &cursor->m_cursor_stmt, nullptr);
638  if (res != SQLITE_OK) {
639  throw std::runtime_error(strprintf(
640  "SQLiteDatabase: Failed to setup cursor SQL statement: %s\n", sqlite3_errstr(res)));
641  }
642 
643  if (!BindBlobToStatement(cursor->m_cursor_stmt, 1, cursor->m_prefix_range_start, "prefix_start")) return nullptr;
644  if (!end_range.empty()) {
645  if (!BindBlobToStatement(cursor->m_cursor_stmt, 2, cursor->m_prefix_range_end, "prefix_end")) return nullptr;
646  }
647 
648  return cursor;
649 }
650 
652 {
653  if (!m_database.m_db || m_txn) return false;
656  int res = Assert(m_exec_handler)->Exec(m_database, "BEGIN TRANSACTION");
657  if (res != SQLITE_OK) {
658  LogPrintf("SQLiteBatch: Failed to begin the transaction\n");
660  } else {
661  m_txn = true;
662  }
663  return res == SQLITE_OK;
664 }
665 
667 {
668  if (!m_database.m_db || !m_txn) return false;
670  int res = Assert(m_exec_handler)->Exec(m_database, "COMMIT TRANSACTION");
671  if (res != SQLITE_OK) {
672  LogPrintf("SQLiteBatch: Failed to commit the transaction\n");
673  } else {
674  m_txn = false;
676  }
677  return res == SQLITE_OK;
678 }
679 
681 {
682  if (!m_database.m_db || !m_txn) return false;
684  int res = Assert(m_exec_handler)->Exec(m_database, "ROLLBACK TRANSACTION");
685  if (res != SQLITE_OK) {
686  LogPrintf("SQLiteBatch: Failed to abort the transaction\n");
687  } else {
688  m_txn = false;
690  }
691  return res == SQLITE_OK;
692 }
693 
694 std::unique_ptr<SQLiteDatabase> MakeSQLiteDatabase(const fs::path& path, const DatabaseOptions& options, DatabaseStatus& status, bilingual_str& error)
695 {
696  try {
697  fs::path data_file = SQLiteDataFile(path);
698  auto db = std::make_unique<SQLiteDatabase>(data_file.parent_path(), data_file, options);
699  if (options.verify && !db->Verify(error)) {
701  return nullptr;
702  }
703  status = DatabaseStatus::SUCCESS;
704  return db;
705  } catch (const std::runtime_error& e) {
707  error = Untranslated(e.what());
708  return nullptr;
709  }
710 }
711 
713 {
714  return std::string(sqlite3_libversion());
715 }
716 } // namespace wallet
int ret
#define PACKAGE_NAME
int flags
Definition: bitcoin-tx.cpp:533
const CChainParams & Params()
Return the currently selected parameters.
#define Assert(val)
Identity function.
Definition: check.h:77
void wait() noexcept
Definition: sync.h:324
void post() noexcept
Definition: sync.h:341
Double ended buffer combining vector and stream-like interfaces.
Definition: streams.h:147
void write(Span< const value_type > src)
Definition: streams.h:251
void clear()
Definition: streams.h:187
constexpr std::size_t size() const noexcept
Definition: span.h:187
constexpr C * data() const noexcept
Definition: span.h:174
Path class wrapper to block calls to the fs::path(std::string) implicit constructor and the fs::path:...
Definition: fs.h:33
bool ReadKey(DataStream &&key, DataStream &value) override
Definition: sqlite.cpp:457
bool TxnCommit() override
Definition: sqlite.cpp:666
SQLiteBatch(SQLiteDatabase &database)
Definition: sqlite.cpp:399
std::unique_ptr< SQliteExecHandler > m_exec_handler
Definition: sqlite.h:53
bool HasKey(DataStream &&key) override
Definition: sqlite.cpp:550
bool m_txn
Whether this batch has started a database transaction and whether it owns SQLiteDatabase::m_write_sem...
Definition: sqlite.h:71
std::unique_ptr< DatabaseCursor > GetNewCursor() override
Definition: sqlite.cpp:594
bool ErasePrefix(Span< const std::byte > prefix) override
Definition: sqlite.cpp:545
bool EraseKey(DataStream &&key) override
Definition: sqlite.cpp:540
sqlite3_stmt * m_delete_stmt
Definition: sqlite.h:58
bool TxnBegin() override
Definition: sqlite.cpp:651
sqlite3_stmt * m_read_stmt
Definition: sqlite.h:55
void Close() override
Definition: sqlite.cpp:408
sqlite3_stmt * m_overwrite_stmt
Definition: sqlite.h:57
bool ExecStatement(sqlite3_stmt *stmt, Span< const std::byte > blob)
Definition: sqlite.cpp:516
std::unique_ptr< DatabaseCursor > GetNewPrefixCursor(Span< const std::byte > prefix) override
Definition: sqlite.cpp:609
sqlite3_stmt * m_delete_prefix_stmt
Definition: sqlite.h:59
void SetupSQLStatements()
Definition: sqlite.cpp:149
sqlite3_stmt * m_insert_stmt
Definition: sqlite.h:56
SQLiteDatabase & m_database
Definition: sqlite.h:52
bool TxnAbort() override
Definition: sqlite.cpp:680
bool WriteKey(DataStream &&key, DataStream &&value, bool overwrite=true) override
Definition: sqlite.cpp:483
~SQLiteCursor() override
Definition: sqlite.cpp:583
Status Next(DataStream &key, DataStream &value) override
Definition: sqlite.cpp:563
sqlite3_stmt * m_cursor_stmt
Definition: sqlite.h:23
An instance of this class represents one SQLite3 database.
Definition: sqlite.h:103
static Mutex g_sqlite_mutex
This mutex protects SQLite initialization and shutdown.
Definition: sqlite.h:117
CSemaphore m_write_semaphore
Definition: sqlite.h:132
void Open() override
Open the database if it is not already opened.
Definition: sqlite.cpp:247
std::string Filename() override
Return path to main database file for logs and error messages.
Definition: sqlite.h:167
bool Rewrite(const char *skip=nullptr) override
Rewrite the entire database on disk.
Definition: sqlite.cpp:339
void Cleanup() noexcept EXCLUSIVE_LOCKS_REQUIRED(!g_sqlite_mutex)
Definition: sqlite.cpp:175
const bool m_mock
Definition: sqlite.h:105
void Close() override
Close the database.
Definition: sqlite.cpp:373
bool Backup(const std::string &dest) const override
Back up the entire database to a file.
Definition: sqlite.cpp:346
const std::string m_dir_path
Definition: sqlite.h:107
const std::string m_file_path
Definition: sqlite.h:109
std::unique_ptr< DatabaseBatch > MakeBatch(bool flush_on_close=true) override
Make a SQLiteBatch connected to this database.
Definition: sqlite.cpp:393
bool Verify(bilingual_str &error)
Definition: sqlite.cpp:190
bool HasActiveTxn()
Return true if there is an on-going txn in this connection.
Definition: sqlite.cpp:382
virtual int Exec(SQLiteDatabase &database, const std::string &statement)
Definition: sqlite.cpp:388
An instance of this class represents one database.
Definition: db.h:130
static uint32_t ReadBE32(const unsigned char *ptr)
Definition: common.h:59
bool TryCreateDirectories(const fs::path &p)
Ignores exceptions thrown by create_directories if the requested directory exists.
Definition: fs_helpers.cpp:261
static bool LogAcceptCategory(BCLog::LogFlags category, BCLog::Level level)
Return true if log accepts specified category, at the specified level.
Definition: logging.h:209
#define LogTrace(category,...)
Definition: logging.h:260
#define LogPrintf(...)
Definition: logging.h:244
@ WALLETDB
Definition: logging.h:47
Filesystem operations and types.
static std::string PathToString(const path &path)
Convert path object to a byte string.
Definition: fs.h:151
static path PathFromString(const std::string &string)
Convert byte string to path object.
Definition: fs.h:174
std::unique_ptr< SQLiteDatabase > MakeSQLiteDatabase(const fs::path &path, const DatabaseOptions &options, DatabaseStatus &status, bilingual_str &error)
Definition: sqlite.cpp:694
fs::path SQLiteDataFile(const fs::path &path)
Definition: db.cpp:81
static constexpr int32_t WALLET_SCHEMA_VERSION
Definition: sqlite.cpp:27
static int TraceSqlCallback(unsigned code, void *context, void *param1, void *param2)
Definition: sqlite.cpp:46
static bool BindBlobToStatement(sqlite3_stmt *stmt, int index, Span< const std::byte > blob, const std::string &description)
Definition: sqlite.cpp:61
static void SetPragma(sqlite3 *db, const std::string &key, const std::string &value, const std::string &err_msg)
Definition: sqlite.cpp:102
static std::optional< int > ReadPragmaInteger(sqlite3 *db, const std::string &key, const std::string &description, bilingual_str &error)
Definition: sqlite.cpp:81
std::string SQLiteDatabaseVersion()
Definition: sqlite.cpp:712
static void ErrorLogCallback(void *arg, int code, const char *msg)
Definition: sqlite.cpp:35
DatabaseStatus
Definition: db.h:204
static Span< const std::byte > SpanFromBlob(sqlite3_stmt *stmt, int col)
Definition: sqlite.cpp:29
const char * prefix
Definition: rest.cpp:1007
Bilingual messages:
Definition: translation.h:18
bool empty() const
Definition: translation.h:29
bool verify
Check data integrity on load.
Definition: db.h:198
#define AssertLockNotHeld(cs)
Definition: sync.h:147
#define LOCK(cs)
Definition: sync.h:257
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1161
bilingual_str _(ConstevalStringLiteral str)
Translation function.
Definition: translation.h:80
bilingual_str Untranslated(std::string original)
Mark a bilingual_str as untranslated.
Definition: translation.h:48
assert(!tx.IsCoinBase())