forked from MakisChristou/rieMiner
-
Notifications
You must be signed in to change notification settings - Fork 0
/
GBTClient.cpp
265 lines (255 loc) · 11.3 KB
/
GBTClient.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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
// (c) 2018-2022 Pttn (https://riecoin.dev/en/rieMiner)
#include "Client.hpp"
#include "main.hpp"
const std::string cbMsg("/rM0.93/");
static std::vector<uint8_t> coinbaseGen(const std::vector<uint8_t> &scriptPubKey, const uint32_t height, const uint64_t coinbasevalue, const std::vector<uint8_t> &dwc) {
std::vector<uint8_t> coinbase;
// Version (01000000)
coinbase.insert(coinbase.end(), {0x01, 0x00, 0x00, 0x00});
// Marker (00) and Flag (01) for SegWit
if (dwc.size() > 0)
coinbase.insert(coinbase.end(), {0x00, 0x01});
// Input Count (01)
coinbase.push_back(1);
// Input TXID (0000000000000000000000000000000000000000000000000000000000000000)
for (uint32_t i(0) ; i < 32 ; i++) coinbase.push_back(0x00);
// Input VOUT (FFFFFFFF)
for (uint32_t i(0) ; i < 4 ; i++) coinbase.push_back(0xFF);
// (ScriptSig Construction)
std::vector<uint8_t> scriptSig;
// Block Height (Bip 34)
if (height < 17)
scriptSig.push_back(80 + height);
else if (height < 128) {
scriptSig.push_back(1);
scriptSig.push_back(height);
}
else if (height < 32768) {
scriptSig.push_back(2);
scriptSig.push_back(height % 256);
scriptSig.push_back((height/256) % 256);
}
else {
scriptSig.push_back(3);
scriptSig.push_back(height % 256);
scriptSig.push_back((height/256) % 256);
scriptSig.push_back((height/65536) % 256);
}
// Coinbase Message
for (uint32_t i(0) ; i < cbMsg.size() ; i++) scriptSig.push_back(cbMsg[i]);
// Randomization to avoid having 2 threads working on the same problem
for (uint32_t i(0) ; i < 4 ; i++) scriptSig.push_back(rand(0x00, 0xFF));
// ScriptSig Size
coinbase.push_back(scriptSig.size());
// ScriptSig
coinbase.insert(coinbase.end(), scriptSig.begin(), scriptSig.end());
// Input Sequence (FFFFFFFF)
coinbase.insert(coinbase.end(), {0xFF, 0xFF, 0xFF, 0xFF});
// Output Count
coinbase.push_back(1U);
if (dwc.size() > 0) coinbase.back()++; // Dummy Output for SegWit
// Output Value
uint64_t reward(coinbasevalue);
for (uint32_t i(0) ; i < 8 ; i++) {
coinbase.push_back(reward % 256);
reward /= 256;
}
// Output/ScriptPubKey Length
coinbase.push_back(scriptPubKey.size());
// ScriptPubKey (for the payout address)
coinbase.insert(coinbase.end(), scriptPubKey.begin(), scriptPubKey.end());
// Dummy output and witness for SegWit
if (dwc.size() > 0) {
for (uint32_t i(0) ; i < 8 ; i++) coinbase.push_back(0); // No reward
coinbase.push_back(dwc.size()); // Output Length
coinbase.insert(coinbase.end(), dwc.begin(), dwc.end()); // Default Witness Commitment
coinbase.push_back(1); // Number of Witnesses/stack items
coinbase.push_back(32); // Witness Length
for (uint32_t i(0) ; i < 32 ; i++) coinbase.push_back(0x00); // Witness of the Coinbase Input (0000000000000000000000000000000000000000000000000000000000000000)
}
// Lock Time (00000000)
coinbase.insert(coinbase.end(), {0x00, 0x00, 0x00, 0x00});
return coinbase;
}
std::array<uint8_t, 32> coinbaseTxId(const std::vector<uint8_t> &coinbase) {
std::vector<uint8_t> coinbase2;
for (uint32_t i(0) ; i < 4 ; i++) coinbase2.push_back(coinbase[i]); // nVersion
for (uint32_t i(6) ; i < coinbase.size() - 38 ; i++) coinbase2.push_back(coinbase[i]); // txins . txouts
for (uint32_t i(coinbase.size() - 4) ; i < coinbase.size() ; i++) coinbase2.push_back(coinbase[i]); // nLockTime
return sha256sha256(coinbase2.data(), coinbase2.size());
}
static std::array<uint8_t, 32> calculateMerkleRoot(const std::vector<std::array<uint8_t, 32>> &txHashes) {
std::array<uint8_t, 32> merkleRoot{};
if (txHashes.size() == 0)
logger.log("No transaction to hash!\n"s, MessageType::ERROR);
else if (txHashes.size() == 1)
return txHashes[0];
else {
std::vector<std::array<uint8_t, 32>> txHashes2;
for (uint32_t i(0) ; i < txHashes.size() ; i += 2) {
std::array<uint8_t, 64> concat;
std::copy(txHashes[i].begin(), txHashes[i].end(), concat.begin());
if (i == txHashes.size() - 1) // Concatenation of the last element with itself for an odd number of transactions
std::copy(txHashes[i].begin(), txHashes[i].end(), concat.begin() + 32);
else
std::copy(txHashes[i + 1].begin(), txHashes[i + 1].end(), concat.begin() + 32);
txHashes2.push_back(sha256sha256(concat.data(), 64));
}
// Process the next step
merkleRoot = calculateMerkleRoot(txHashes2);
}
return merkleRoot;
}
static size_t curlWriteCallback(void *data, size_t size, size_t nmemb, std::string *s) {
s->append((char*) data, size*nmemb);
return size*nmemb;
}
nlohmann::json GBTClient::_sendRequestToWallet(const std::string &method, const nlohmann::json ¶ms) const {
static uint64_t id(0ULL);
nlohmann::json jsonObj;
if (_curl) {
std::string s;
const nlohmann::json request{{"method", method}, {"params", params}, {"id", id++}};
const std::string requestStr(request.dump());
curl_easy_setopt(_curl, CURLOPT_URL, _url.c_str());
curl_easy_setopt(_curl, CURLOPT_POSTFIELDSIZE, requestStr.size());
curl_easy_setopt(_curl, CURLOPT_POSTFIELDS, requestStr.c_str());
curl_easy_setopt(_curl, CURLOPT_WRITEFUNCTION, curlWriteCallback);
curl_easy_setopt(_curl, CURLOPT_WRITEDATA, &s);
curl_easy_setopt(_curl, CURLOPT_USERPWD, _credentials.c_str());
curl_easy_setopt(_curl, CURLOPT_TIMEOUT, 10);
const CURLcode cc(curl_easy_perform(_curl));
if (cc != CURLE_OK)
logger.log("Curl_easy_perform() failed: "s + curl_easy_strerror(cc) + "\n"s, MessageType::ERROR);
else {
try {jsonObj = nlohmann::json::parse(s);}
catch (nlohmann::json::parse_error &e) {
if (s.size() == 0)
logger.log("Nothing was received from the server!\n"s, MessageType::ERROR);
else {
logger.log("Received bad JSON object!\n"s
"Server message was: "s + s + "\n"s, MessageType::ERROR);
}
}
}
}
return jsonObj;
}
bool GBTClient::_fetchJob() {
nlohmann::json getblocktemplate, getblocktemplateResult;
try {
getblocktemplate = _sendRequestToWallet("getblocktemplate", {{{"rules", _rules}}});
if (getblocktemplate == nullptr)
return false;
getblocktemplateResult = getblocktemplate["result"];
}
catch (...) {
logger.log("Could not get GetBlockTemplate Data!\n"s, MessageType::ERROR);
return false;
}
JobTemplate newJobTemplate;
std::vector<std::vector<uint64_t>> acceptedPatterns;
try { // Extract and build GetBlockTemplate data
newJobTemplate.job.clientData.bh.version = getblocktemplateResult["version"];
newJobTemplate.job.clientData.bh.previousblockhash = v8ToA8(reverse(hexStrToV8(getblocktemplateResult["previousblockhash"])));
newJobTemplate.job.clientData.bh.curtime = getblocktemplateResult["curtime"];
newJobTemplate.job.clientData.bh.bits = std::stoll(std::string(getblocktemplateResult["bits"]), nullptr, 16);
newJobTemplate.coinbasevalue = getblocktemplateResult["coinbasevalue"];
std::vector<std::array<uint8_t, 32>> wTxIds{std::array<uint8_t, 32>{}};
for (const auto &transaction : getblocktemplateResult["transactions"]) {
const std::vector<uint8_t> txId(reverse(hexStrToV8(transaction["txid"])));
newJobTemplate.job.clientData.transactionsHex += transaction["data"];
newJobTemplate.txHashes.push_back(v8ToA8(txId));
wTxIds.push_back(v8ToA8(reverse(hexStrToV8(transaction["hash"]))));
}
newJobTemplate.default_witness_commitment = "6a24aa21a9ed" + v8ToHexStr(a8ToV8(calculateMerkleRoot({calculateMerkleRoot(wTxIds), std::array<uint8_t, 32>{}})));
newJobTemplate.job.clientData.txCount = newJobTemplate.txHashes.size() + 1; // Include Coinbase
newJobTemplate.job.height = getblocktemplateResult["height"];
newJobTemplate.job.powVersion = getblocktemplateResult["powversion"];
if (newJobTemplate.job.powVersion != 1) {
logger.log("Unsupported PoW Version "s + std::to_string(newJobTemplate.job.powVersion) + ", your rieMiner version is likely outdated!\n"s, MessageType::ERROR);
return false;
}
newJobTemplate.job.acceptedPatterns = getblocktemplateResult["patterns"].get<decltype(newJobTemplate.job.acceptedPatterns)>();
if (newJobTemplate.job.acceptedPatterns.size() == 0) {
logger.log("Empty or invalid accepted patterns list!\n"s, MessageType::ERROR);
return false;
}
newJobTemplate.job.primeCountTarget = newJobTemplate.job.acceptedPatterns[0].size();
newJobTemplate.job.primeCountMin = newJobTemplate.job.primeCountTarget;
newJobTemplate.job.difficulty = decodeBits(newJobTemplate.job.clientData.bh.bits, newJobTemplate.job.powVersion);
}
catch (...) {
logger.log("Received GetBlockTemplate Data with invalid parameters!\n"s
"Json Object was: "s + getblocktemplate.dump() + "\n"s, MessageType::ERROR);
return false;
}
std::lock_guard<std::mutex> lock(_jobMutex);
_currentJobTemplate = newJobTemplate;
return true;
}
void GBTClient::_submit(const Job& job) {
logger.log("Submitting block with "s + std::to_string(job.clientData.txCount) + " transaction(s) (including coinbase)...\n"s, MessageType::BOLD);
BlockHeader bh(job.clientData.bh);
bh.nOffset = job.encodedOffset();
std::ostringstream oss;
oss << v8ToHexStr(bh.toV8());
// Using the Variable Length Integer format; having more than 65535 transactions is currently impossible
if (job.clientData.txCount < 0xFD)
oss << std::setfill('0') << std::setw(2) << std::hex << job.clientData.txCount;
else
oss << "fd" << std::setfill('0') << std::setw(2) << std::hex << job.clientData.txCount % 256 << std::setw(2) << job.clientData.txCount/256;
oss << job.clientData.transactionsHex;
try {
nlohmann::json submitblockResponse(_sendRequestToWallet("submitblock", {oss.str()}));
if (submitblockResponse["result"] == nullptr && submitblockResponse["error"] == nullptr)
logger.log("Submission accepted :D !\n"s, MessageType::SUCCESS);
else
logger.log("Submission rejected :| ! Received: " + submitblockResponse.dump() + "\n"s, MessageType::WARNING);
}
catch (std::exception &e) {
logger.log("Failure submitting block :| !\n"s, MessageType::ERROR);
return;
}
}
void GBTClient::connect() {
if (!_connected) {
_currentJobTemplate = JobTemplate();
_pendingSubmissions = {};
process();
if (_currentJobTemplate.job.height == 0) {
logger.log("Could not get a first job from the server!\n"s, MessageType::ERROR);
return;
}
_connected = true;
}
}
void GBTClient::process() {
// Process pending submissions
_submitMutex.lock();
if (_pendingSubmissions.size() > 0) {
for (const auto &submission : _pendingSubmissions) _submit(submission);
_pendingSubmissions.clear();
}
_submitMutex.unlock();
// Update work
if (!_fetchJob()) {
_connected = false; // If _fetchJob() failed, this means that the client is disconnected
std::lock_guard<std::mutex> lock(_jobMutex);
_currentJobTemplate.job.height = 0;
}
}
Job GBTClient::getJob(const bool) {
std::lock_guard<std::mutex> lock(_jobMutex);
Job job(_currentJobTemplate.job);
if (job.height == 0) // Invalid Job
return job;
const std::vector<uint8_t> coinbase(coinbaseGen(_scriptPubKey, job.height, _currentJobTemplate.coinbasevalue, hexStrToV8(_currentJobTemplate.default_witness_commitment)));
job.clientData.transactionsHex = v8ToHexStr(coinbase) + job.clientData.transactionsHex;
std::vector<std::array<uint8_t, 32>> txHashesWithCoinbase{coinbaseTxId(coinbase)};
txHashesWithCoinbase.insert(txHashesWithCoinbase.end(), _currentJobTemplate.txHashes.begin(), _currentJobTemplate.txHashes.end());
_jobMutex.unlock();
job.clientData.bh.merkleRoot = calculateMerkleRoot(txHashesWithCoinbase);
job.target = job.clientData.bh.target(job.powVersion);
return job;
}