forked from amjuarez/bytecoin
-
Notifications
You must be signed in to change notification settings - Fork 102
Expand file tree
/
Copy pathCryptoNoteFormatUtils.cpp
More file actions
executable file
·411 lines (336 loc) · 11.9 KB
/
CryptoNoteFormatUtils.cpp
File metadata and controls
executable file
·411 lines (336 loc) · 11.9 KB
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
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
// Copyright (c) 2012-2017, The CryptoNote developers, The Bytecoin developers
//
// This file is part of Bytecoin.
//
// Bytecoin is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Bytecoin is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with Bytecoin. If not, see <http://www.gnu.org/licenses/>.
#include "CryptoNoteFormatUtils.h"
#include <set>
#include <Logging/LoggerRef.h>
#include <Common/Varint.h>
#include "Serialization/BinaryOutputStreamSerializer.h"
#include "Serialization/BinaryInputStreamSerializer.h"
#include "Account.h"
#include "CryptoNoteBasicImpl.h"
#include "CryptoNoteSerialization.h"
#include "TransactionExtra.h"
#include "CryptoNoteTools.h"
#include "CryptoNoteConfig.h"
using namespace Logging;
using namespace Crypto;
using namespace Common;
namespace CryptoNote {
bool parseAndValidateTransactionFromBinaryArray(const BinaryArray& tx_blob, Transaction& tx, Hash& tx_hash, Hash& tx_prefix_hash) {
if (!fromBinaryArray(tx, tx_blob)) {
return false;
}
//TODO: validate tx
cn_fast_hash(tx_blob.data(), tx_blob.size(), tx_hash);
getObjectHash(*static_cast<TransactionPrefix*>(&tx), tx_prefix_hash);
return true;
}
bool generate_key_image_helper(const AccountKeys& ack, const PublicKey& tx_public_key, size_t real_output_index, KeyPair& in_ephemeral, KeyImage& ki) {
KeyDerivation recv_derivation;
bool r = generate_key_derivation(tx_public_key, ack.viewSecretKey, recv_derivation);
assert(r && "key image helper: failed to generate_key_derivation");
if (!r) {
return false;
}
r = derive_public_key(recv_derivation, real_output_index, ack.address.spendPublicKey, in_ephemeral.publicKey);
assert(r && "key image helper: failed to derive_public_key");
if (!r) {
return false;
}
derive_secret_key(recv_derivation, real_output_index, ack.spendSecretKey, in_ephemeral.secretKey);
generate_key_image(in_ephemeral.publicKey, in_ephemeral.secretKey, ki);
return true;
}
uint64_t power_integral(uint64_t a, uint64_t b) {
if (b == 0)
return 1;
uint64_t total = a;
for (uint64_t i = 1; i != b; i++)
total *= a;
return total;
}
bool get_tx_fee(const Transaction& tx, uint64_t & fee) {
uint64_t amount_in = 0;
uint64_t amount_out = 0;
for (const auto& in : tx.inputs) {
if (in.type() == typeid(KeyInput)) {
amount_in += boost::get<KeyInput>(in).amount;
}
}
for (const auto& o : tx.outputs) {
amount_out += o.amount;
}
if (!(amount_in >= amount_out)) {
return false;
}
fee = amount_in - amount_out;
return true;
}
uint64_t get_tx_fee(const Transaction& tx) {
uint64_t r = 0;
if (!get_tx_fee(tx, r))
return 0;
return r;
}
std::vector<uint32_t> relativeOutputOffsetsToAbsolute(const std::vector<uint32_t>& off) {
std::vector<uint32_t> res = off;
for (size_t i = 1; i < res.size(); i++)
res[i] += res[i - 1];
return res;
}
std::vector<uint32_t> absolute_output_offsets_to_relative(const std::vector<uint32_t>& off) {
if (off.empty()) return {};
auto copy = off;
for (size_t i = 1; i < copy.size(); ++i) {
copy[i] = off[i] - off[i-1];
}
return copy;
}
bool constructTransaction(
const AccountKeys& sender_account_keys,
const std::vector<TransactionSourceEntry>& sources,
const std::vector<TransactionDestinationEntry>& destinations,
std::vector<uint8_t> extra,
Transaction& tx,
uint64_t unlock_time,
Logging::ILogger& log) {
LoggerRef logger(log, "construct_tx");
tx.inputs.clear();
tx.outputs.clear();
tx.signatures.clear();
tx.version = CURRENT_TRANSACTION_VERSION;
tx.unlockTime = unlock_time;
tx.extra = extra;
KeyPair txkey = generateKeyPair();
addTransactionPublicKeyToExtra(tx.extra, txkey.publicKey);
struct input_generation_context_data {
KeyPair in_ephemeral;
};
std::vector<input_generation_context_data> in_contexts;
uint64_t summary_inputs_money = 0;
//fill inputs
for (const TransactionSourceEntry& src_entr : sources) {
if (src_entr.realOutput >= src_entr.outputs.size()) {
logger(ERROR) << "real_output index (" << src_entr.realOutput << ")bigger than output_keys.size()=" << src_entr.outputs.size();
return false;
}
summary_inputs_money += src_entr.amount;
//KeyDerivation recv_derivation;
in_contexts.push_back(input_generation_context_data());
KeyPair& in_ephemeral = in_contexts.back().in_ephemeral;
KeyImage img;
if (!generate_key_image_helper(sender_account_keys, src_entr.realTransactionPublicKey, src_entr.realOutputIndexInTransaction, in_ephemeral, img))
return false;
//check that derived key is equal with real output key
if (!(in_ephemeral.publicKey == src_entr.outputs[src_entr.realOutput].second)) {
logger(ERROR) << "derived public key mismatch with output public key! " << ENDL << "derived_key:"
<< Common::podToHex(in_ephemeral.publicKey) << ENDL << "real output_public_key:"
<< Common::podToHex(src_entr.outputs[src_entr.realOutput].second);
return false;
}
//put key image into tx input
KeyInput input_to_key;
input_to_key.amount = src_entr.amount;
input_to_key.keyImage = img;
//fill outputs array and use relative offsets
for (const TransactionSourceEntry::OutputEntry& out_entry : src_entr.outputs) {
input_to_key.outputIndexes.push_back(out_entry.first);
}
input_to_key.outputIndexes = absolute_output_offsets_to_relative(input_to_key.outputIndexes);
tx.inputs.push_back(input_to_key);
}
// "Shuffle" outs
std::vector<TransactionDestinationEntry> shuffled_dsts(destinations);
std::sort(shuffled_dsts.begin(), shuffled_dsts.end(), [](const TransactionDestinationEntry& de1, const TransactionDestinationEntry& de2) { return de1.amount < de2.amount; });
uint64_t summary_outs_money = 0;
//fill outputs
size_t output_index = 0;
for (const TransactionDestinationEntry& dst_entr : shuffled_dsts) {
if (!(dst_entr.amount > 0)) {
logger(ERROR, BRIGHT_RED) << "Destination with wrong amount: " << dst_entr.amount;
return false;
}
KeyDerivation derivation;
PublicKey out_eph_public_key;
bool r = generate_key_derivation(dst_entr.addr.viewPublicKey, txkey.secretKey, derivation);
if (!(r)) {
logger(ERROR, BRIGHT_RED)
<< "at creation outs: failed to generate_key_derivation("
<< dst_entr.addr.viewPublicKey << ", " << txkey.secretKey << ")";
return false;
}
r = derive_public_key(derivation, output_index,
dst_entr.addr.spendPublicKey,
out_eph_public_key);
if (!(r)) {
logger(ERROR, BRIGHT_RED)
<< "at creation outs: failed to derive_public_key(" << derivation
<< ", " << output_index << ", " << dst_entr.addr.spendPublicKey
<< ")";
return false;
}
TransactionOutput out;
out.amount = dst_entr.amount;
KeyOutput tk;
tk.key = out_eph_public_key;
out.target = tk;
tx.outputs.push_back(out);
output_index++;
summary_outs_money += dst_entr.amount;
}
//check money
if (summary_outs_money > summary_inputs_money) {
logger(ERROR) << "Transaction inputs money (" << summary_inputs_money << ") less than outputs money (" << summary_outs_money << ")";
return false;
}
//generate ring signatures
Hash tx_prefix_hash;
getObjectHash(*static_cast<TransactionPrefix*>(&tx), tx_prefix_hash);
size_t i = 0;
for (const TransactionSourceEntry& src_entr : sources) {
std::vector<const PublicKey*> keys_ptrs;
for (const TransactionSourceEntry::OutputEntry& o : src_entr.outputs) {
keys_ptrs.push_back(&o.second);
}
tx.signatures.push_back(std::vector<Signature>());
std::vector<Signature>& sigs = tx.signatures.back();
sigs.resize(src_entr.outputs.size());
generate_ring_signature(tx_prefix_hash, boost::get<KeyInput>(tx.inputs[i]).keyImage, keys_ptrs,
in_contexts[i].in_ephemeral.secretKey, src_entr.realOutput, sigs.data());
i++;
}
return true;
}
bool getInputsMoneyAmount(const Transaction& tx, uint64_t& money) {
money = 0;
for (const auto& in : tx.inputs) {
uint64_t amount = 0;
if (in.type() == typeid(KeyInput)) {
amount = boost::get<KeyInput>(in).amount;
}
money += amount;
}
return true;
}
bool checkInputTypesSupported(const TransactionPrefix& tx) {
for (const auto& in : tx.inputs) {
if (in.type() != typeid(KeyInput)) {
return false;
}
}
return true;
}
bool checkOutsValid(const TransactionPrefix& tx, std::string* error) {
for (const TransactionOutput& out : tx.outputs) {
if (out.target.type() == typeid(KeyOutput)) {
if (out.amount == 0) {
if (error) {
*error = "Zero amount ouput";
}
return false;
}
if (!check_key(boost::get<KeyOutput>(out.target).key)) {
if (error) {
*error = "Output with invalid key";
}
return false;
}
} else {
if (error) {
*error = "Output with invalid type";
}
return false;
}
}
return true;
}
bool checkMoneyOverflow(const TransactionPrefix &tx) {
return checkInputsOverflow(tx) && checkOutsOverflow(tx);
}
bool checkInputsOverflow(const TransactionPrefix &tx) {
uint64_t money = 0;
for (const auto &in : tx.inputs) {
uint64_t amount = 0;
if (in.type() == typeid(KeyInput)) {
amount = boost::get<KeyInput>(in).amount;
}
if (money > amount + money)
return false;
money += amount;
}
return true;
}
bool checkOutsOverflow(const TransactionPrefix& tx) {
uint64_t money = 0;
for (const auto& o : tx.outputs) {
if (money > o.amount + money)
return false;
money += o.amount;
}
return true;
}
uint64_t get_outs_money_amount(const Transaction& tx) {
uint64_t outputs_amount = 0;
for (const auto& o : tx.outputs) {
outputs_amount += o.amount;
}
return outputs_amount;
}
std::string short_hash_str(const Hash& h) {
std::string res = Common::podToHex(h);
if (res.size() == 64) {
auto erased_pos = res.erase(8, 48);
res.insert(8, "....");
}
return res;
}
bool is_out_to_acc(const AccountKeys& acc, const KeyOutput& out_key, const KeyDerivation& derivation, size_t keyIndex) {
PublicKey pk;
derive_public_key(derivation, keyIndex, acc.address.spendPublicKey, pk);
return pk == out_key.key;
}
bool is_out_to_acc(const AccountKeys& acc, const KeyOutput& out_key, const PublicKey& tx_pub_key, size_t keyIndex) {
KeyDerivation derivation;
generate_key_derivation(tx_pub_key, acc.viewSecretKey, derivation);
return is_out_to_acc(acc, out_key, derivation, keyIndex);
}
bool lookup_acc_outs(const AccountKeys& acc, const Transaction& tx, std::vector<size_t>& outs, uint64_t& money_transfered) {
PublicKey transactionPublicKey = getTransactionPublicKeyFromExtra(tx.extra);
if (transactionPublicKey == NULL_PUBLIC_KEY)
return false;
return lookup_acc_outs(acc, tx, transactionPublicKey, outs, money_transfered);
}
bool lookup_acc_outs(const AccountKeys& acc, const Transaction& tx, const PublicKey& tx_pub_key, std::vector<size_t>& outs, uint64_t& money_transfered) {
money_transfered = 0;
size_t keyIndex = 0;
size_t outputIndex = 0;
KeyDerivation derivation;
generate_key_derivation(tx_pub_key, acc.viewSecretKey, derivation);
for (const TransactionOutput& o : tx.outputs) {
assert(o.target.type() == typeid(KeyOutput));
if (o.target.type() == typeid(KeyOutput)) {
if (is_out_to_acc(acc, boost::get<KeyOutput>(o.target), derivation, keyIndex)) {
outs.push_back(outputIndex);
money_transfered += o.amount;
}
++keyIndex;
}
++outputIndex;
}
return true;
}
}