forked from zcash/zcash
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpaymentdisclosuredb.cpp
92 lines (75 loc) · 2.71 KB
/
paymentdisclosuredb.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
// Copyright (c) 2017 The Zcash developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or https://www.opensource.org/licenses/mit-license.php .
#include "wallet/paymentdisclosuredb.h"
#include "fs.h"
#include "util.h"
#include "dbwrapper.h"
using namespace std;
static fs::path emptyPath;
/**
* Static method to return the shared/default payment disclosure database.
*/
shared_ptr<PaymentDisclosureDB> PaymentDisclosureDB::sharedInstance() {
// Thread-safe in C++11 and gcc 4.3
static shared_ptr<PaymentDisclosureDB> ptr = std::make_shared<PaymentDisclosureDB>();
return ptr;
}
// C++11 delegated constructor
PaymentDisclosureDB::PaymentDisclosureDB() : PaymentDisclosureDB(emptyPath) {
}
PaymentDisclosureDB::PaymentDisclosureDB(const fs::path& dbPath) {
fs::path path(dbPath);
if (path.empty()) {
path = GetDataDir() / "paymentdisclosure";
LogPrintf("PaymentDisclosure: using default path for database: %s\n", path.string());
} else {
LogPrintf("PaymentDisclosure: using custom path for database: %s\n", path.string());
}
TryCreateDirectory(path);
options.create_if_missing = true;
leveldb::Status status = leveldb::DB::Open(options, path.string(), &db);
dbwrapper_private::HandleError(status); // throws exception
LogPrintf("PaymentDisclosure: Opened LevelDB successfully\n");
}
PaymentDisclosureDB::~PaymentDisclosureDB() {
if (db != nullptr) {
delete db;
}
}
bool PaymentDisclosureDB::Put(const PaymentDisclosureKey& key, const PaymentDisclosureInfo& info)
{
if (db == nullptr) {
return false;
}
std::lock_guard<std::mutex> guard(lock_);
CDataStream ssValue(SER_DISK, CLIENT_VERSION);
ssValue.reserve(GetSerializeSize(ssValue, info));
ssValue << info;
leveldb::Slice slice(&ssValue[0], ssValue.size());
leveldb::Status status = db->Put(writeOptions, key.ToString(), slice);
dbwrapper_private::HandleError(status);
return true;
}
bool PaymentDisclosureDB::Get(const PaymentDisclosureKey& key, PaymentDisclosureInfo& info)
{
if (db == nullptr) {
return false;
}
std::lock_guard<std::mutex> guard(lock_);
std::string strValue;
leveldb::Status status = db->Get(readOptions, key.ToString(), &strValue);
if (!status.ok()) {
if (status.IsNotFound())
return false;
LogPrintf("PaymentDisclosure: LevelDB read failure: %s\n", status.ToString());
dbwrapper_private::HandleError(status);
}
try {
CDataStream ssValue(strValue.data(), strValue.data() + strValue.size(), SER_DISK, CLIENT_VERSION);
ssValue >> info;
} catch (const std::exception&) {
return false;
}
return true;
}