Skip to content

Commit 12daf6f

Browse files
committed
walletdb: scope bdb::EraseRecords under a single db txn
so we erase all the records atomically or abort the entire procedure. and, at the same time, we can share the same db txn context for the db cursor and the erase functionality. extra note from the Db.cursor doc: "If transaction protection is enabled, cursors must be opened and closed within the context of a transaction" thus why added a `CloseCursor` call before calling to `TxnAbort/TxnCommit`.
1 parent 043fcb0 commit 12daf6f

File tree

1 file changed

+14
-4
lines changed

1 file changed

+14
-4
lines changed

src/wallet/walletdb.cpp

Lines changed: 14 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1136,6 +1136,9 @@ bool WalletBatch::WriteWalletFlags(const uint64_t flags)
11361136

11371137
bool WalletBatch::EraseRecords(const std::unordered_set<std::string>& types)
11381138
{
1139+
// Begin db txn
1140+
if (!m_batch->TxnBegin()) return false;
1141+
11391142
// Get cursor
11401143
std::unique_ptr<DatabaseCursor> cursor = m_batch->GetNewCursor();
11411144
if (!cursor)
@@ -1144,15 +1147,16 @@ bool WalletBatch::EraseRecords(const std::unordered_set<std::string>& types)
11441147
}
11451148

11461149
// Iterate the DB and look for any records that have the type prefixes
1147-
while (true)
1148-
{
1150+
while (true) {
11491151
// Read next record
11501152
DataStream key{};
11511153
DataStream value{};
11521154
DatabaseCursor::Status status = cursor->Next(key, value);
11531155
if (status == DatabaseCursor::Status::DONE) {
11541156
break;
11551157
} else if (status == DatabaseCursor::Status::FAIL) {
1158+
cursor.reset(nullptr);
1159+
m_batch->TxnAbort(); // abort db txn
11561160
return false;
11571161
}
11581162

@@ -1163,10 +1167,16 @@ bool WalletBatch::EraseRecords(const std::unordered_set<std::string>& types)
11631167
key >> type;
11641168

11651169
if (types.count(type) > 0) {
1166-
m_batch->Erase(key_data);
1170+
if (!m_batch->Erase(key_data)) {
1171+
cursor.reset(nullptr);
1172+
m_batch->TxnAbort();
1173+
return false; // erase failed
1174+
}
11671175
}
11681176
}
1169-
return true;
1177+
// Finish db txn
1178+
cursor.reset(nullptr);
1179+
return m_batch->TxnCommit();
11701180
}
11711181

11721182
bool WalletBatch::TxnBegin()

0 commit comments

Comments
 (0)