Debian Codegraph @

monero/src/cryptonote_basic/cryptonote_format_utils.cpp

raw symbols SCIP
1 // Copyright (c) 2014-2022, The Monero Project
2 //
3 // All rights reserved.
4 //
5 // Redistribution and use in source and binary forms, with or without modification, are
6 // permitted provided that the following conditions are met:
7 //
8 // 1. Redistributions of source code must retain the above copyright notice, this list of
9 // conditions and the following disclaimer.
10 //
11 // 2. Redistributions in binary form must reproduce the above copyright notice, this list
12 // of conditions and the following disclaimer in the documentation and/or other
13 // materials provided with the distribution.
14 //
15 // 3. Neither the name of the copyright holder nor the names of its contributors may be
16 // used to endorse or promote products derived from this software without specific
17 // prior written permission.
18 //
19 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
20 // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
21 // MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
22 // THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
24 // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
25 // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
26 // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
27 // THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28 //
29 // Parts of this file are originally copyright (c) 2012-2013 The Cryptonote developers
30
31 #include <atomic>
32 #include <boost/algorithm/string.hpp>
33 #include "wipeable_string.h"
34 #include "string_tools.h"
35 #include "string_tools_lexical.h"
36 #include "serialization/string.h"
37 #include "cryptonote_format_utils.h"
38 #include "cryptonote_config.h"
39 #include "crypto/crypto.h"
40 #include "crypto/hash.h"
41 #include "ringct/rctSigs.h"
42
43 using namespace epee;
44
45 #undef MONERO_DEFAULT_LOG_CATEGORY
46 #define MONERO_DEFAULT_LOG_CATEGORY "cn"
47
48 // #define ENABLE_HASH_CASH_INTEGRITY_CHECK
49
50 using namespace crypto;
51
52 static const uint64_t valid_decomposed_outputs[] = {
53 (uint64_t)1, (uint64_t)2, (uint64_t)3, (uint64_t)4, (uint64_t)5, (uint64_t)6, (uint64_t)7, (uint64_t)8, (uint64_t)9, // 1 piconero
54 (uint64_t)10, (uint64_t)20, (uint64_t)30, (uint64_t)40, (uint64_t)50, (uint64_t)60, (uint64_t)70, (uint64_t)80, (uint64_t)90,
55 (uint64_t)100, (uint64_t)200, (uint64_t)300, (uint64_t)400, (uint64_t)500, (uint64_t)600, (uint64_t)700, (uint64_t)800, (uint64_t)900,
56 (uint64_t)1000, (uint64_t)2000, (uint64_t)3000, (uint64_t)4000, (uint64_t)5000, (uint64_t)6000, (uint64_t)7000, (uint64_t)8000, (uint64_t)9000,
57 (uint64_t)10000, (uint64_t)20000, (uint64_t)30000, (uint64_t)40000, (uint64_t)50000, (uint64_t)60000, (uint64_t)70000, (uint64_t)80000, (uint64_t)90000,
58 (uint64_t)100000, (uint64_t)200000, (uint64_t)300000, (uint64_t)400000, (uint64_t)500000, (uint64_t)600000, (uint64_t)700000, (uint64_t)800000, (uint64_t)900000,
59 (uint64_t)1000000, (uint64_t)2000000, (uint64_t)3000000, (uint64_t)4000000, (uint64_t)5000000, (uint64_t)6000000, (uint64_t)7000000, (uint64_t)8000000, (uint64_t)9000000, // 1 micronero
60 (uint64_t)10000000, (uint64_t)20000000, (uint64_t)30000000, (uint64_t)40000000, (uint64_t)50000000, (uint64_t)60000000, (uint64_t)70000000, (uint64_t)80000000, (uint64_t)90000000,
61 (uint64_t)100000000, (uint64_t)200000000, (uint64_t)300000000, (uint64_t)400000000, (uint64_t)500000000, (uint64_t)600000000, (uint64_t)700000000, (uint64_t)800000000, (uint64_t)900000000,
62 (uint64_t)1000000000, (uint64_t)2000000000, (uint64_t)3000000000, (uint64_t)4000000000, (uint64_t)5000000000, (uint64_t)6000000000, (uint64_t)7000000000, (uint64_t)8000000000, (uint64_t)9000000000,
63 (uint64_t)10000000000, (uint64_t)20000000000, (uint64_t)30000000000, (uint64_t)40000000000, (uint64_t)50000000000, (uint64_t)60000000000, (uint64_t)70000000000, (uint64_t)80000000000, (uint64_t)90000000000,
64 (uint64_t)100000000000, (uint64_t)200000000000, (uint64_t)300000000000, (uint64_t)400000000000, (uint64_t)500000000000, (uint64_t)600000000000, (uint64_t)700000000000, (uint64_t)800000000000, (uint64_t)900000000000,
65 (uint64_t)1000000000000, (uint64_t)2000000000000, (uint64_t)3000000000000, (uint64_t)4000000000000, (uint64_t)5000000000000, (uint64_t)6000000000000, (uint64_t)7000000000000, (uint64_t)8000000000000, (uint64_t)9000000000000, // 1 monero
66 (uint64_t)10000000000000, (uint64_t)20000000000000, (uint64_t)30000000000000, (uint64_t)40000000000000, (uint64_t)50000000000000, (uint64_t)60000000000000, (uint64_t)70000000000000, (uint64_t)80000000000000, (uint64_t)90000000000000,
67 (uint64_t)100000000000000, (uint64_t)200000000000000, (uint64_t)300000000000000, (uint64_t)400000000000000, (uint64_t)500000000000000, (uint64_t)600000000000000, (uint64_t)700000000000000, (uint64_t)800000000000000, (uint64_t)900000000000000,
68 (uint64_t)1000000000000000, (uint64_t)2000000000000000, (uint64_t)3000000000000000, (uint64_t)4000000000000000, (uint64_t)5000000000000000, (uint64_t)6000000000000000, (uint64_t)7000000000000000, (uint64_t)8000000000000000, (uint64_t)9000000000000000,
69 (uint64_t)10000000000000000, (uint64_t)20000000000000000, (uint64_t)30000000000000000, (uint64_t)40000000000000000, (uint64_t)50000000000000000, (uint64_t)60000000000000000, (uint64_t)70000000000000000, (uint64_t)80000000000000000, (uint64_t)90000000000000000,
70 (uint64_t)100000000000000000, (uint64_t)200000000000000000, (uint64_t)300000000000000000, (uint64_t)400000000000000000, (uint64_t)500000000000000000, (uint64_t)600000000000000000, (uint64_t)700000000000000000, (uint64_t)800000000000000000, (uint64_t)900000000000000000,
71 (uint64_t)1000000000000000000, (uint64_t)2000000000000000000, (uint64_t)3000000000000000000, (uint64_t)4000000000000000000, (uint64_t)5000000000000000000, (uint64_t)6000000000000000000, (uint64_t)7000000000000000000, (uint64_t)8000000000000000000, (uint64_t)9000000000000000000, // 1 meganero
72 (uint64_t)10000000000000000000ull
73 };
74
75 static std::atomic<unsigned int> default_decimal_point(CRYPTONOTE_DISPLAY_DECIMAL_POINT);
76
77 static std::atomic<uint64_t> tx_hashes_calculated_count(0);
78 static std::atomic<uint64_t> tx_hashes_cached_count(0);
79 static std::atomic<uint64_t> block_hashes_calculated_count(0);
80 static std::atomic<uint64_t> block_hashes_cached_count(0);
81
82 #define CHECK_AND_ASSERT_THROW_MES_L1(expr, message) {if(!(expr)) {MWARNING(message); throw std::runtime_error(message);}}
83
84 namespace cryptonote
85 {
86 static inline unsigned char *operator &(ec_point &point) {
87 return &reinterpret_cast<unsigned char &>(point);
88 }
89 static inline const unsigned char *operator &(const ec_point &point) {
90 return &reinterpret_cast<const unsigned char &>(point);
91 }
92
93 // a copy of rct::addKeys, since we can't link to libringct to avoid circular dependencies
94 static void add_public_key(crypto::public_key &AB, const crypto::public_key &A, const crypto::public_key &B) {
95 ge_p3 B2, A2;
96 CHECK_AND_ASSERT_THROW_MES_L1(ge_frombytes_vartime(&B2, &B) == 0, "ge_frombytes_vartime failed at "+boost::lexical_cast<std::string>(__LINE__));
97 CHECK_AND_ASSERT_THROW_MES_L1(ge_frombytes_vartime(&A2, &A) == 0, "ge_frombytes_vartime failed at "+boost::lexical_cast<std::string>(__LINE__));
98 ge_cached tmp2;
99 ge_p3_to_cached(&tmp2, &B2);
100 ge_p1p1 tmp3;
101 ge_add(&tmp3, &A2, &tmp2);
102 ge_p1p1_to_p3(&A2, &tmp3);
103 ge_p3_tobytes(&AB, &A2);
104 }
105
106 uint64_t get_transaction_weight_clawback(const transaction &tx, size_t n_padded_outputs)
107 {
108 const rct::rctSig &rv = tx.rct_signatures;
109 const bool plus = rv.type == rct::RCTTypeBulletproofPlus;
110 const uint64_t bp_base = (32 * ((plus ? 6 : 9) + 7 * 2)) / 2; // notional size of a 2 output proof, normalized to 1 proof (ie, divided by 2)
111 const size_t n_outputs = tx.vout.size();
112 if (n_padded_outputs <= 2)
113 return 0;
114 size_t nlr = 0;
115 while ((1u << nlr) < n_padded_outputs)
116 ++nlr;
117 nlr += 6;
118 const size_t bp_size = 32 * ((plus ? 6 : 9) + 2 * nlr);
119 CHECK_AND_ASSERT_THROW_MES_L1(n_outputs <= BULLETPROOF_MAX_OUTPUTS, "maximum number of outputs is " + std::to_string(BULLETPROOF_MAX_OUTPUTS) + " per transaction");
120 CHECK_AND_ASSERT_THROW_MES_L1(bp_base * n_padded_outputs >= bp_size, "Invalid bulletproof clawback: bp_base " + std::to_string(bp_base) + ", n_padded_outputs "
121 + std::to_string(n_padded_outputs) + ", bp_size " + std::to_string(bp_size));
122 const uint64_t bp_clawback = (bp_base * n_padded_outputs - bp_size) * 4 / 5;
123 return bp_clawback;
124 }
125 //---------------------------------------------------------------
126 }
127
128 namespace cryptonote
129 {
130 //---------------------------------------------------------------
131 void get_transaction_prefix_hash(const transaction_prefix& tx, crypto::hash& h, hw::device &hwdev)
132 {
133 hwdev.get_transaction_prefix_hash(tx,h);
134 }
135
136 //---------------------------------------------------------------
137 crypto::hash get_transaction_prefix_hash(const transaction_prefix& tx, hw::device &hwdev)
138 {
139 crypto::hash h = null_hash;
140 get_transaction_prefix_hash(tx, h, hwdev);
141 return h;
142 }
143
144 bool expand_transaction_1(transaction &tx, bool base_only)
145 {
146 if (tx.version >= 2 && !is_coinbase(tx))
147 {
148 rct::rctSig &rv = tx.rct_signatures;
149 if (rv.type == rct::RCTTypeNull)
150 return true;
151 if (rv.outPk.size() != tx.vout.size())
152 {
153 LOG_PRINT_L1("Failed to parse transaction from blob, bad outPk size in tx " << get_transaction_hash(tx));
154 return false;
155 }
156 for (size_t n = 0; n < tx.rct_signatures.outPk.size(); ++n)
157 {
158 crypto::public_key output_public_key;
159 if (!get_output_public_key(tx.vout[n], output_public_key))
160 {
161 LOG_PRINT_L1("Failed to get output public key for output " << n << " in tx " << get_transaction_hash(tx));
162 return false;
163 }
164 rv.outPk[n].dest = rct::pk2rct(output_public_key);
165 }
166
167 if (!base_only)
168 {
169 const bool bulletproof = rct::is_rct_bulletproof(rv.type);
170 const bool bulletproof_plus = rct::is_rct_bulletproof_plus(rv.type);
171 if (bulletproof_plus)
172 {
173 if (rv.p.bulletproofs_plus.size() != 1)
174 {
175 LOG_PRINT_L1("Failed to parse transaction from blob, bad bulletproofs_plus size in tx " << get_transaction_hash(tx));
176 return false;
177 }
178 if (rv.p.bulletproofs_plus[0].L.size() < 6)
179 {
180 LOG_PRINT_L1("Failed to parse transaction from blob, bad bulletproofs_plus L size in tx " << get_transaction_hash(tx));
181 return false;
182 }
183 const size_t max_outputs = rct::n_bulletproof_plus_max_amounts(rv.p.bulletproofs_plus[0]);
184 if (max_outputs < tx.vout.size())
185 {
186 LOG_PRINT_L1("Failed to parse transaction from blob, bad bulletproofs_plus max outputs in tx " << get_transaction_hash(tx));
187 return false;
188 }
189 const size_t n_amounts = tx.vout.size();
190 CHECK_AND_ASSERT_MES(n_amounts == rv.outPk.size(), false, "Internal error filling out V");
191 rv.p.bulletproofs_plus[0].V.resize(n_amounts);
192 for (size_t i = 0; i < n_amounts; ++i)
193 rv.p.bulletproofs_plus[0].V[i] = rct::scalarmultKey(rv.outPk[i].mask, rct::INV_EIGHT);
194 }
195 else if (bulletproof)
196 {
197 if (rv.p.bulletproofs.size() != 1)
198 {
199 LOG_PRINT_L1("Failed to parse transaction from blob, bad bulletproofs size in tx " << get_transaction_hash(tx));
200 return false;
201 }
202 if (rv.p.bulletproofs[0].L.size() < 6)
203 {
204 LOG_PRINT_L1("Failed to parse transaction from blob, bad bulletproofs L size in tx " << get_transaction_hash(tx));
205 return false;
206 }
207 const size_t max_outputs = 1 << (rv.p.bulletproofs[0].L.size() - 6);
208 if (max_outputs < tx.vout.size())
209 {
210 LOG_PRINT_L1("Failed to parse transaction from blob, bad bulletproofs max outputs in tx " << get_transaction_hash(tx));
211 return false;
212 }
213 const size_t n_amounts = tx.vout.size();
214 CHECK_AND_ASSERT_MES(n_amounts == rv.outPk.size(), false, "Internal error filling out V");
215 rv.p.bulletproofs[0].V.resize(n_amounts);
216 for (size_t i = 0; i < n_amounts; ++i)
217 rv.p.bulletproofs[0].V[i] = rct::scalarmultKey(rv.outPk[i].mask, rct::INV_EIGHT);
218 }
219 }
220 }
221 return true;
222 }
223 //---------------------------------------------------------------
224 bool parse_and_validate_tx_from_blob(const blobdata_ref& tx_blob, transaction& tx)
225 {
226 binary_archive<false> ba{epee::strspan<std::uint8_t>(tx_blob)};
227 bool r = ::serialization::serialize(ba, tx);
228 CHECK_AND_ASSERT_MES(r, false, "Failed to parse transaction from blob");
229 CHECK_AND_ASSERT_MES(expand_transaction_1(tx, false), false, "Failed to expand transaction data");
230 tx.invalidate_hashes();
231 tx.set_blob_size(tx_blob.size());
232 return true;
233 }
234 //---------------------------------------------------------------
235 bool parse_and_validate_tx_base_from_blob(const blobdata_ref& tx_blob, transaction& tx)
236 {
237 binary_archive<false> ba{epee::strspan<std::uint8_t>(tx_blob)};
238 bool r = tx.serialize_base(ba);
239 CHECK_AND_ASSERT_MES(r, false, "Failed to parse transaction from blob");
240 CHECK_AND_ASSERT_MES(expand_transaction_1(tx, true), false, "Failed to expand transaction data");
241 tx.invalidate_hashes();
242 return true;
243 }
244 //---------------------------------------------------------------
245 bool parse_and_validate_tx_prefix_from_blob(const blobdata_ref& tx_blob, transaction_prefix& tx)
246 {
247 binary_archive<false> ba{epee::strspan<std::uint8_t>(tx_blob)};
248 bool r = ::serialization::serialize_noeof(ba, tx);
249 CHECK_AND_ASSERT_MES(r, false, "Failed to parse transaction prefix from blob");
250 return true;
251 }
252 //---------------------------------------------------------------
253 bool parse_and_validate_tx_from_blob(const blobdata_ref& tx_blob, transaction& tx, crypto::hash& tx_hash)
254 {
255 binary_archive<false> ba{epee::strspan<std::uint8_t>(tx_blob)};
256 bool r = ::serialization::serialize(ba, tx);
257 CHECK_AND_ASSERT_MES(r, false, "Failed to parse transaction from blob");
258 CHECK_AND_ASSERT_MES(expand_transaction_1(tx, false), false, "Failed to expand transaction data");
259 tx.invalidate_hashes();
260 tx.set_blob_size(tx_blob.size());
261 //TODO: validate tx
262
263 return get_transaction_hash(tx, tx_hash);
264 }
265 //---------------------------------------------------------------
266 bool parse_and_validate_tx_from_blob(const blobdata_ref& tx_blob, transaction& tx, crypto::hash& tx_hash, crypto::hash& tx_prefix_hash)
267 {
268 if (!parse_and_validate_tx_from_blob(tx_blob, tx, tx_hash))
269 return false;
270 get_transaction_prefix_hash(tx, tx_prefix_hash);
271 return true;
272 }
273 //---------------------------------------------------------------
274 bool is_v1_tx(const blobdata_ref& tx_blob)
275 {
276 uint64_t version;
277 const char* begin = static_cast<const char*>(tx_blob.data());
278 const char* end = begin + tx_blob.size();
279 int read = tools::read_varint(begin, end, version);
280 if (read <= 0)
281 throw std::runtime_error("Internal error getting transaction version");
282 return version <= 1;
283 }
284 //---------------------------------------------------------------
285 bool is_v1_tx(const blobdata& tx_blob)
286 {
287 return is_v1_tx(blobdata_ref{tx_blob.data(), tx_blob.size()});
288 }
289 //---------------------------------------------------------------
290 bool generate_key_image_helper(const account_keys& ack, const std::unordered_map<crypto::public_key, subaddress_index>& subaddresses, const crypto::public_key& out_key, const crypto::public_key& tx_public_key, const std::vector<crypto::public_key>& additional_tx_public_keys, size_t real_output_index, keypair& in_ephemeral, crypto::key_image& ki, hw::device &hwdev)
291 {
292 crypto::key_derivation recv_derivation = AUTO_VAL_INIT(recv_derivation);
293 bool r = hwdev.generate_key_derivation(tx_public_key, ack.m_view_secret_key, recv_derivation);
294 if (!r)
295 {
296 MWARNING("key image helper: failed to generate_key_derivation(" << tx_public_key << ", <viewkey>)");
297 memcpy(&recv_derivation, rct::identity().bytes, sizeof(recv_derivation));
298 }
299
300 std::vector<crypto::key_derivation> additional_recv_derivations;
301 for (size_t i = 0; i < additional_tx_public_keys.size(); ++i)
302 {
303 crypto::key_derivation additional_recv_derivation = AUTO_VAL_INIT(additional_recv_derivation);
304 r = hwdev.generate_key_derivation(additional_tx_public_keys[i], ack.m_view_secret_key, additional_recv_derivation);
305 if (!r)
306 {
307 MWARNING("key image helper: failed to generate_key_derivation(" << additional_tx_public_keys[i] << ", <viewkey>)");
308 }
309 else
310 {
311 additional_recv_derivations.push_back(additional_recv_derivation);
312 }
313 }
314
315 boost::optional<subaddress_receive_info> subaddr_recv_info = is_out_to_acc_precomp(subaddresses, out_key, recv_derivation, additional_recv_derivations, real_output_index,hwdev);
316 CHECK_AND_ASSERT_MES(subaddr_recv_info, false, "key image helper: given output pubkey doesn't seem to belong to this address");
317
318 return generate_key_image_helper_precomp(ack, out_key, subaddr_recv_info->derivation, real_output_index, subaddr_recv_info->index, in_ephemeral, ki, hwdev);
319 }
320 //---------------------------------------------------------------
321 bool generate_key_image_helper_precomp(const account_keys& ack, const crypto::public_key& out_key, const crypto::key_derivation& recv_derivation, size_t real_output_index, const subaddress_index& received_index, keypair& in_ephemeral, crypto::key_image& ki, hw::device &hwdev)
322 {
323 if (hwdev.compute_key_image(ack, out_key, recv_derivation, real_output_index, received_index, in_ephemeral, ki))
324 {
325 return true;
326 }
327
328 if (ack.m_spend_secret_key == crypto::null_skey)
329 {
330 // for watch-only wallet, simply copy the known output pubkey
331 in_ephemeral.pub = out_key;
332 in_ephemeral.sec = crypto::null_skey;
333 }
334 else
335 {
336 // derive secret key with subaddress - step 1: original CN derivation
337 crypto::secret_key scalar_step1;
338 crypto::secret_key spend_skey = crypto::null_skey;
339
340 if (ack.m_multisig_keys.empty())
341 {
342 // if not multisig, use normal spend skey
343 spend_skey = ack.m_spend_secret_key;
344 }
345 else
346 {
347 // if multisig, use sum of multisig privkeys (local account's share of aggregate spend key)
348 for (const auto &multisig_key : ack.m_multisig_keys)
349 {
350 sc_add((unsigned char*)spend_skey.data,
351 (const unsigned char*)multisig_key.data,
352 (const unsigned char*)spend_skey.data);
353 }
354 }
355
356 // computes Hs(a*R || idx) + b
357 hwdev.derive_secret_key(recv_derivation, real_output_index, spend_skey, scalar_step1);
358
359 // step 2: add Hs(a || index_major || index_minor)
360 crypto::secret_key subaddr_sk;
361 crypto::secret_key scalar_step2;
362 if (received_index.is_zero())
363 {
364 scalar_step2 = scalar_step1; // treat index=(0,0) as a special case representing the main address
365 }
366 else
367 {
368 subaddr_sk = hwdev.get_subaddress_secret_key(ack.m_view_secret_key, received_index);
369 hwdev.sc_secret_add(scalar_step2, scalar_step1,subaddr_sk);
370 }
371
372 in_ephemeral.sec = scalar_step2;
373
374 if (ack.m_multisig_keys.empty())
375 {
376 // when not in multisig, we know the full spend secret key, so the output pubkey can be obtained by scalarmultBase
377 CHECK_AND_ASSERT_MES(hwdev.secret_key_to_public_key(in_ephemeral.sec, in_ephemeral.pub), false, "Failed to derive public key");
378 }
379 else
380 {
381 // when in multisig, we only know the partial spend secret key. but we do know the full spend public key, so the output pubkey can be obtained by using the standard CN key derivation
382 CHECK_AND_ASSERT_MES(hwdev.derive_public_key(recv_derivation, real_output_index, ack.m_account_address.m_spend_public_key, in_ephemeral.pub), false, "Failed to derive public key");
383 // and don't forget to add the contribution from the subaddress part
384 if (!received_index.is_zero())
385 {
386 crypto::public_key subaddr_pk;
387 CHECK_AND_ASSERT_MES(hwdev.secret_key_to_public_key(subaddr_sk, subaddr_pk), false, "Failed to derive public key");
388 add_public_key(in_ephemeral.pub, in_ephemeral.pub, subaddr_pk);
389 }
390 }
391
392 CHECK_AND_ASSERT_MES(in_ephemeral.pub == out_key,
393 false, "key image helper precomp: given output pubkey doesn't match the derived one");
394 }
395
396 hwdev.generate_key_image(in_ephemeral.pub, in_ephemeral.sec, ki);
397 return true;
398 }
399 //---------------------------------------------------------------
400 uint64_t power_integral(uint64_t a, uint64_t b)
401 {
402 if(b == 0)
403 return 1;
404 uint64_t total = a;
405 for(uint64_t i = 1; i != b; i++)
406 total *= a;
407 return total;
408 }
409 //---------------------------------------------------------------
410 bool parse_amount(uint64_t& amount, const std::string& str_amount_)
411 {
412 std::string str_amount = str_amount_;
413 boost::algorithm::trim(str_amount);
414
415 size_t point_index = str_amount.find_first_of('.');
416 size_t fraction_size;
417 if (std::string::npos != point_index)
418 {
419 fraction_size = str_amount.size() - point_index - 1;
420 while (default_decimal_point < fraction_size && '0' == str_amount.back())
421 {
422 str_amount.erase(str_amount.size() - 1, 1);
423 --fraction_size;
424 }
425 if (default_decimal_point < fraction_size)
426 return false;
427 str_amount.erase(point_index, 1);
428 }
429 else
430 {
431 fraction_size = 0;
432 }
433
434 if (str_amount.empty())
435 return false;
436
437 if (fraction_size < default_decimal_point)
438 {
439 str_amount.append(default_decimal_point - fraction_size, '0');
440 }
441
442 return string_tools::get_xtype_from_string(amount, str_amount);
443 }
444 //---------------------------------------------------------------
445 uint64_t get_transaction_weight(const transaction &tx, size_t blob_size)
446 {
447 CHECK_AND_ASSERT_MES(!tx.pruned, std::numeric_limits<uint64_t>::max(), "get_transaction_weight does not support pruned txes");
448 if (tx.version < 2)
449 return blob_size;
450 const rct::rctSig &rv = tx.rct_signatures;
451 const bool bulletproof = rct::is_rct_bulletproof(rv.type);
452 const bool bulletproof_plus = rct::is_rct_bulletproof_plus(rv.type);
453 if (!bulletproof && !bulletproof_plus)
454 return blob_size;
455 const size_t n_padded_outputs = bulletproof_plus ? rct::n_bulletproof_plus_max_amounts(rv.p.bulletproofs_plus) : rct::n_bulletproof_max_amounts(rv.p.bulletproofs);
456 uint64_t bp_clawback = get_transaction_weight_clawback(tx, n_padded_outputs);
457 CHECK_AND_ASSERT_THROW_MES_L1(bp_clawback <= std::numeric_limits<uint64_t>::max() - blob_size, "Weight overflow");
458 return blob_size + bp_clawback;
459 }
460 //---------------------------------------------------------------
461 uint64_t get_pruned_transaction_weight(const transaction &tx)
462 {
463 CHECK_AND_ASSERT_MES(tx.pruned, std::numeric_limits<uint64_t>::max(), "get_pruned_transaction_weight does not support non pruned txes");
464 CHECK_AND_ASSERT_MES(tx.version >= 2, std::numeric_limits<uint64_t>::max(), "get_pruned_transaction_weight does not support v1 txes");
465 CHECK_AND_ASSERT_MES(tx.rct_signatures.type == rct::RCTTypeBulletproof2 || tx.rct_signatures.type == rct::RCTTypeCLSAG || tx.rct_signatures.type == rct::RCTTypeBulletproofPlus,
466 std::numeric_limits<uint64_t>::max(), "Unsupported rct_signatures type in get_pruned_transaction_weight");
467 CHECK_AND_ASSERT_MES(!tx.vin.empty(), std::numeric_limits<uint64_t>::max(), "empty vin");
468 CHECK_AND_ASSERT_MES(tx.vin[0].type() == typeid(cryptonote::txin_to_key), std::numeric_limits<uint64_t>::max(), "empty vin");
469
470 // get pruned data size
471 std::ostringstream s;
472 binary_archive<true> a(s);
473 ::serialization::serialize(a, const_cast<transaction&>(tx));
474 uint64_t weight = s.str().size(), extra;
475
476 // nbps (technically varint)
477 weight += 1;
478
479 // calculate deterministic bulletproofs size (assumes canonical BP format)
480 size_t nrl = 0, n_padded_outputs;
481 while ((n_padded_outputs = (1u << nrl)) < tx.vout.size())
482 ++nrl;
483 nrl += 6;
484 extra = 32 * ((rct::is_rct_bulletproof_plus(tx.rct_signatures.type) ? 6 : 9) + 2 * nrl) + 2;
485 weight += extra;
486
487 // calculate deterministic CLSAG/MLSAG data size
488 const size_t ring_size = boost::get<cryptonote::txin_to_key>(tx.vin[0]).key_offsets.size();
489 if (rct::is_rct_clsag(tx.rct_signatures.type))
490 extra = tx.vin.size() * (ring_size + 2) * 32;
491 else
492 extra = tx.vin.size() * (ring_size * (1 + 1) * 32 + 32 /* cc */);
493 weight += extra;
494
495 // calculate deterministic pseudoOuts size
496 extra = 32 * (tx.vin.size());
497 weight += extra;
498
499 // clawback
500 uint64_t bp_clawback = get_transaction_weight_clawback(tx, n_padded_outputs);
501 CHECK_AND_ASSERT_THROW_MES_L1(bp_clawback <= std::numeric_limits<uint64_t>::max() - weight, "Weight overflow");
502 weight += bp_clawback;
503
504 return weight;
505 }
506 //---------------------------------------------------------------
507 uint64_t get_transaction_weight(const transaction &tx)
508 {
509 size_t blob_size;
510 if (tx.is_blob_size_valid())
511 {
512 blob_size = tx.blob_size;
513 }
514 else
515 {
516 std::ostringstream s;
517 binary_archive<true> a(s);
518 ::serialization::serialize(a, const_cast<transaction&>(tx));
519 blob_size = s.str().size();
520 }
521 return get_transaction_weight(tx, blob_size);
522 }
523 //---------------------------------------------------------------
524 uint64_t get_transaction_blob_size(const transaction& tx)
525 {
526 if (!tx.is_blob_size_valid())
527 {
528 const cryptonote::blobdata tx_blob = tx_to_blob(tx);
529 tx.set_blob_size(tx_blob.size());
530 }
531
532 CHECK_AND_ASSERT_THROW_MES(tx.is_blob_size_valid(), "BUG: blob size valid not set");
533
534 return tx.blob_size;
535 }
536 //---------------------------------------------------------------
537 bool get_tx_fee(const transaction& tx, uint64_t & fee)
538 {
539 if (tx.version > 1)
540 {
541 fee = tx.rct_signatures.txnFee;
542 return true;
543 }
544 uint64_t amount_in = 0;
545 uint64_t amount_out = 0;
546 for(auto& in: tx.vin)
547 {
548 CHECK_AND_ASSERT_MES(in.type() == typeid(txin_to_key), 0, "unexpected type id in transaction");
549 amount_in += boost::get<txin_to_key>(in).amount;
550 }
551 for(auto& o: tx.vout)
552 amount_out += o.amount;
553
554 CHECK_AND_ASSERT_MES(amount_in >= amount_out, false, "transaction spend (" <<amount_in << ") more than it has (" << amount_out << ")");
555 fee = amount_in - amount_out;
556 return true;
557 }
558 //---------------------------------------------------------------
559 uint64_t get_tx_fee(const transaction& tx)
560 {
561 uint64_t r = 0;
562 if(!get_tx_fee(tx, r))
563 return 0;
564 return r;
565 }
566 //---------------------------------------------------------------
567 bool parse_tx_extra(const std::vector<uint8_t>& tx_extra, std::vector<tx_extra_field>& tx_extra_fields)
568 {
569 tx_extra_fields.clear();
570
571 if(tx_extra.empty())
572 return true;
573
574 binary_archive<false> ar{epee::to_span(tx_extra)};
575
576 do
577 {
578 tx_extra_field field;
579 bool r = ::do_serialize(ar, field);
580 CHECK_AND_NO_ASSERT_MES_L1(r, false, "failed to deserialize extra field. extra = " << string_tools::buff_to_hex_nodelimer(std::string(reinterpret_cast<const char*>(tx_extra.data()), tx_extra.size())));
581 tx_extra_fields.push_back(field);
582 } while (!ar.eof());
583 CHECK_AND_NO_ASSERT_MES_L1(::serialization::check_stream_state(ar), false, "failed to deserialize extra field. extra = " << string_tools::buff_to_hex_nodelimer(std::string(reinterpret_cast<const char*>(tx_extra.data()), tx_extra.size())));
584
585 return true;
586 }
587 //---------------------------------------------------------------
588 template<typename T>
589 static bool pick(binary_archive<true> &ar, std::vector<tx_extra_field> &fields, uint8_t tag)
590 {
591 std::vector<tx_extra_field>::iterator it;
592 while ((it = std::find_if(fields.begin(), fields.end(), [](const tx_extra_field &f) { return f.type() == typeid(T); })) != fields.end())
593 {
594 bool r = ::do_serialize(ar, tag);
595 CHECK_AND_NO_ASSERT_MES_L1(r, false, "failed to serialize tx extra field");
596 r = ::do_serialize(ar, boost::get<T>(*it));
597 CHECK_AND_NO_ASSERT_MES_L1(r, false, "failed to serialize tx extra field");
598 fields.erase(it);
599 }
600 return true;
601 }
602 //---------------------------------------------------------------
603 bool sort_tx_extra(const std::vector<uint8_t>& tx_extra, std::vector<uint8_t> &sorted_tx_extra, bool allow_partial)
604 {
605 std::vector<tx_extra_field> tx_extra_fields;
606
607 if(tx_extra.empty())
608 {
609 sorted_tx_extra.clear();
610 return true;
611 }
612
613 binary_archive<false> ar{epee::to_span(tx_extra)};
614
615 size_t processed = 0;
616 do
617 {
618 tx_extra_field field;
619 bool r = ::do_serialize(ar, field);
620 if (!r)
621 {
622 MWARNING("failed to deserialize extra field. extra = " << string_tools::buff_to_hex_nodelimer(std::string(reinterpret_cast<const char*>(tx_extra.data()), tx_extra.size())));
623 if (!allow_partial)
624 return false;
625 break;
626 }
627 tx_extra_fields.push_back(field);
628 processed = ar.getpos();
629 } while (!ar.eof());
630 if (!::serialization::check_stream_state(ar))
631 {
632 MWARNING("failed to deserialize extra field. extra = " << string_tools::buff_to_hex_nodelimer(std::string(reinterpret_cast<const char*>(tx_extra.data()), tx_extra.size())));
633 if (!allow_partial)
634 return false;
635 }
636 MTRACE("Sorted " << processed << "/" << tx_extra.size());
637
638 std::ostringstream oss;
639 binary_archive<true> nar(oss);
640
641 // sort by:
642 if (!pick<tx_extra_pub_key>(nar, tx_extra_fields, TX_EXTRA_TAG_PUBKEY)) return false;
643 if (!pick<tx_extra_additional_pub_keys>(nar, tx_extra_fields, TX_EXTRA_TAG_ADDITIONAL_PUBKEYS)) return false;
644 if (!pick<tx_extra_nonce>(nar, tx_extra_fields, TX_EXTRA_NONCE)) return false;
645 if (!pick<tx_extra_merge_mining_tag>(nar, tx_extra_fields, TX_EXTRA_MERGE_MINING_TAG)) return false;
646 if (!pick<tx_extra_mysterious_minergate>(nar, tx_extra_fields, TX_EXTRA_MYSTERIOUS_MINERGATE_TAG)) return false;
647 if (!pick<tx_extra_padding>(nar, tx_extra_fields, TX_EXTRA_TAG_PADDING)) return false;
648
649 // if not empty, someone added a new type and did not add a case above
650 if (!tx_extra_fields.empty())
651 {
652 MERROR("tx_extra_fields not empty after sorting, someone forgot to add a case above");
653 return false;
654 }
655
656 std::string oss_str = oss.str();
657 if (allow_partial && processed < tx_extra.size())
658 {
659 MDEBUG("Appending unparsed data");
660 oss_str += std::string((const char*)tx_extra.data() + processed, tx_extra.size() - processed);
661 }
662 sorted_tx_extra = std::vector<uint8_t>(oss_str.begin(), oss_str.end());
663 return true;
664 }
665 //---------------------------------------------------------------
666 crypto::public_key get_tx_pub_key_from_extra(const std::vector<uint8_t>& tx_extra, size_t pk_index)
667 {
668 std::vector<tx_extra_field> tx_extra_fields;
669 parse_tx_extra(tx_extra, tx_extra_fields);
670
671 tx_extra_pub_key pub_key_field;
672 if(!find_tx_extra_field_by_type(tx_extra_fields, pub_key_field, pk_index))
673 return null_pkey;
674
675 return pub_key_field.pub_key;
676 }
677 //---------------------------------------------------------------
678 crypto::public_key get_tx_pub_key_from_extra(const transaction_prefix& tx_prefix, size_t pk_index)
679 {
680 return get_tx_pub_key_from_extra(tx_prefix.extra, pk_index);
681 }
682 //---------------------------------------------------------------
683 crypto::public_key get_tx_pub_key_from_extra(const transaction& tx, size_t pk_index)
684 {
685 return get_tx_pub_key_from_extra(tx.extra, pk_index);
686 }
687 //---------------------------------------------------------------
688 bool add_tx_pub_key_to_extra(transaction& tx, const crypto::public_key& tx_pub_key)
689 {
690 return add_tx_pub_key_to_extra(tx.extra, tx_pub_key);
691 }
692 //---------------------------------------------------------------
693 bool add_tx_pub_key_to_extra(transaction_prefix& tx, const crypto::public_key& tx_pub_key)
694 {
695 return add_tx_pub_key_to_extra(tx.extra, tx_pub_key);
696 }
697 //---------------------------------------------------------------
698 bool add_tx_pub_key_to_extra(std::vector<uint8_t>& tx_extra, const crypto::public_key& tx_pub_key)
699 {
700 tx_extra.resize(tx_extra.size() + 1 + sizeof(crypto::public_key));
701 tx_extra[tx_extra.size() - 1 - sizeof(crypto::public_key)] = TX_EXTRA_TAG_PUBKEY;
702 *reinterpret_cast<crypto::public_key*>(&tx_extra[tx_extra.size() - sizeof(crypto::public_key)]) = tx_pub_key;
703 return true;
704 }
705 //---------------------------------------------------------------
706 std::vector<crypto::public_key> get_additional_tx_pub_keys_from_extra(const std::vector<uint8_t>& tx_extra)
707 {
708 // parse
709 std::vector<tx_extra_field> tx_extra_fields;
710 parse_tx_extra(tx_extra, tx_extra_fields);
711 // find corresponding field
712 tx_extra_additional_pub_keys additional_pub_keys;
713 if(!find_tx_extra_field_by_type(tx_extra_fields, additional_pub_keys))
714 return {};
715 return additional_pub_keys.data;
716 }
717 //---------------------------------------------------------------
718 std::vector<crypto::public_key> get_additional_tx_pub_keys_from_extra(const transaction_prefix& tx)
719 {
720 return get_additional_tx_pub_keys_from_extra(tx.extra);
721 }
722 //---------------------------------------------------------------
723 bool add_additional_tx_pub_keys_to_extra(std::vector<uint8_t>& tx_extra, const std::vector<crypto::public_key>& additional_pub_keys)
724 {
725 // convert to variant
726 tx_extra_field field = tx_extra_additional_pub_keys{ additional_pub_keys };
727 // serialize
728 std::ostringstream oss;
729 binary_archive<true> ar(oss);
730 bool r = ::do_serialize(ar, field);
731 CHECK_AND_NO_ASSERT_MES_L1(r, false, "failed to serialize tx extra additional tx pub keys");
732 // append
733 std::string tx_extra_str = oss.str();
734 size_t pos = tx_extra.size();
735 tx_extra.resize(tx_extra.size() + tx_extra_str.size());
736 memcpy(&tx_extra[pos], tx_extra_str.data(), tx_extra_str.size());
737 return true;
738 }
739 //---------------------------------------------------------------
740 bool add_extra_nonce_to_tx_extra(std::vector<uint8_t>& tx_extra, const blobdata& extra_nonce)
741 {
742 CHECK_AND_ASSERT_MES(extra_nonce.size() <= TX_EXTRA_NONCE_MAX_COUNT, false, "extra nonce could be 255 bytes max");
743 size_t start_pos = tx_extra.size();
744 tx_extra.resize(tx_extra.size() + 2 + extra_nonce.size());
745 //write tag
746 tx_extra[start_pos] = TX_EXTRA_NONCE;
747 //write len
748 ++start_pos;
749 tx_extra[start_pos] = static_cast<uint8_t>(extra_nonce.size());
750 //write data
751 ++start_pos;
752 memcpy(&tx_extra[start_pos], extra_nonce.data(), extra_nonce.size());
753 return true;
754 }
755 //---------------------------------------------------------------
756 bool add_mm_merkle_root_to_tx_extra(std::vector<uint8_t>& tx_extra, const crypto::hash& mm_merkle_root, size_t mm_merkle_tree_depth)
757 {
758 CHECK_AND_ASSERT_MES(mm_merkle_tree_depth < 32, false, "merge mining merkle tree depth should be less than 32");
759 size_t start_pos = tx_extra.size();
760 tx_extra.resize(tx_extra.size() + 3 + 32);
761 //write tag
762 tx_extra[start_pos] = TX_EXTRA_MERGE_MINING_TAG;
763 //write data size
764 ++start_pos;
765 tx_extra[start_pos] = 33;
766 //write depth varint (always one byte here)
767 ++start_pos;
768 tx_extra[start_pos] = mm_merkle_tree_depth;
769 //write data
770 ++start_pos;
771 memcpy(&tx_extra[start_pos], &mm_merkle_root, 32);
772 return true;
773 }
774 //---------------------------------------------------------------
775 bool remove_field_from_tx_extra(std::vector<uint8_t>& tx_extra, const std::type_info &type)
776 {
777 if (tx_extra.empty())
778 return true;
779 std::string extra_str(reinterpret_cast<const char*>(tx_extra.data()), tx_extra.size());
780 binary_archive<false> ar{epee::strspan<std::uint8_t>(extra_str)};
781 std::ostringstream oss;
782 binary_archive<true> newar(oss);
783
784 do
785 {
786 tx_extra_field field;
787 bool r = ::do_serialize(ar, field);
788 CHECK_AND_NO_ASSERT_MES_L1(r, false, "failed to deserialize extra field. extra = " << string_tools::buff_to_hex_nodelimer(std::string(reinterpret_cast<const char*>(tx_extra.data()), tx_extra.size())));
789 if (field.type() != type)
790 ::do_serialize(newar, field);
791 } while (!ar.eof());
792 CHECK_AND_NO_ASSERT_MES_L1(::serialization::check_stream_state(ar), false, "failed to deserialize extra field. extra = " << string_tools::buff_to_hex_nodelimer(std::string(reinterpret_cast<const char*>(tx_extra.data()), tx_extra.size())));
793 tx_extra.clear();
794 std::string s = oss.str();
795 tx_extra.reserve(s.size());
796 std::copy(s.begin(), s.end(), std::back_inserter(tx_extra));
797 return true;
798 }
799 //---------------------------------------------------------------
800 void set_payment_id_to_tx_extra_nonce(blobdata& extra_nonce, const crypto::hash& payment_id)
801 {
802 extra_nonce.clear();
803 extra_nonce.push_back(TX_EXTRA_NONCE_PAYMENT_ID);
804 const uint8_t* payment_id_ptr = reinterpret_cast<const uint8_t*>(&payment_id);
805 std::copy(payment_id_ptr, payment_id_ptr + sizeof(payment_id), std::back_inserter(extra_nonce));
806 }
807 //---------------------------------------------------------------
808 void set_encrypted_payment_id_to_tx_extra_nonce(blobdata& extra_nonce, const crypto::hash8& payment_id)
809 {
810 extra_nonce.clear();
811 extra_nonce.push_back(TX_EXTRA_NONCE_ENCRYPTED_PAYMENT_ID);
812 const uint8_t* payment_id_ptr = reinterpret_cast<const uint8_t*>(&payment_id);
813 std::copy(payment_id_ptr, payment_id_ptr + sizeof(payment_id), std::back_inserter(extra_nonce));
814 }
815 //---------------------------------------------------------------
816 bool get_payment_id_from_tx_extra_nonce(const blobdata& extra_nonce, crypto::hash& payment_id)
817 {
818 if(sizeof(crypto::hash) + 1 != extra_nonce.size())
819 return false;
820 if(TX_EXTRA_NONCE_PAYMENT_ID != extra_nonce[0])
821 return false;
822 payment_id = *reinterpret_cast<const crypto::hash*>(extra_nonce.data() + 1);
823 return true;
824 }
825 //---------------------------------------------------------------
826 bool get_encrypted_payment_id_from_tx_extra_nonce(const blobdata& extra_nonce, crypto::hash8& payment_id)
827 {
828 if(sizeof(crypto::hash8) + 1 != extra_nonce.size())
829 return false;
830 if (TX_EXTRA_NONCE_ENCRYPTED_PAYMENT_ID != extra_nonce[0])
831 return false;
832 payment_id = *reinterpret_cast<const crypto::hash8*>(extra_nonce.data() + 1);
833 return true;
834 }
835 //---------------------------------------------------------------
836 bool get_inputs_money_amount(const transaction& tx, uint64_t& money)
837 {
838 money = 0;
839 for(const auto& in: tx.vin)
840 {
841 CHECKED_GET_SPECIFIC_VARIANT(in, const txin_to_key, tokey_in, false);
842 money += tokey_in.amount;
843 }
844 return true;
845 }
846 //---------------------------------------------------------------
847 uint64_t get_block_height(const block& b)
848 {
849 CHECK_AND_ASSERT_MES(b.miner_tx.vin.size() == 1, 0, "wrong miner tx in block: " << get_block_hash(b) << ", b.miner_tx.vin.size() != 1");
850 CHECKED_GET_SPECIFIC_VARIANT(b.miner_tx.vin[0], const txin_gen, coinbase_in, 0);
851 return coinbase_in.height;
852 }
853 //---------------------------------------------------------------
854 bool check_inputs_types_supported(const transaction& tx)
855 {
856 for(const auto& in: tx.vin)
857 {
858 CHECK_AND_ASSERT_MES(in.type() == typeid(txin_to_key), false, "wrong variant type: "
859 << in.type().name() << ", expected " << typeid(txin_to_key).name()
860 << ", in transaction id=" << get_transaction_hash(tx));
861
862 }
863 return true;
864 }
865 //-----------------------------------------------------------------------------------------------
866 bool check_outs_valid(const transaction& tx)
867 {
868 for(const tx_out& out: tx.vout)
869 {
870 crypto::public_key output_public_key;
871 CHECK_AND_ASSERT_MES(get_output_public_key(out, output_public_key), false, "Failed to get output public key (output type: "
872 << out.target.type().name() << "), in transaction id=" << get_transaction_hash(tx));
873
874 if (tx.version == 1)
875 {
876 CHECK_AND_NO_ASSERT_MES(0 < out.amount, false, "zero amount output in transaction id=" << get_transaction_hash(tx));
877 }
878
879 if(!check_key(output_public_key))
880 return false;
881 }
882 return true;
883 }
884 //-----------------------------------------------------------------------------------------------
885 bool check_money_overflow(const transaction& tx)
886 {
887 return check_inputs_overflow(tx) && check_outs_overflow(tx);
888 }
889 //---------------------------------------------------------------
890 bool check_inputs_overflow(const transaction& tx)
891 {
892 uint64_t money = 0;
893 for(const auto& in: tx.vin)
894 {
895 CHECKED_GET_SPECIFIC_VARIANT(in, const txin_to_key, tokey_in, false);
896 if(money > tokey_in.amount + money)
897 return false;
898 money += tokey_in.amount;
899 }
900 return true;
901 }
902 //---------------------------------------------------------------
903 bool check_outs_overflow(const transaction& tx)
904 {
905 uint64_t money = 0;
906 for(const auto& o: tx.vout)
907 {
908 if(money > o.amount + money)
909 return false;
910 money += o.amount;
911 }
912 return true;
913 }
914 //---------------------------------------------------------------
915 uint64_t get_outs_money_amount(const transaction& tx)
916 {
917 uint64_t outputs_amount = 0;
918 for(const auto& o: tx.vout)
919 outputs_amount += o.amount;
920 return outputs_amount;
921 }
922 //---------------------------------------------------------------
923 bool get_output_public_key(const cryptonote::tx_out& out, crypto::public_key& output_public_key)
924 {
925 // before HF_VERSION_VIEW_TAGS, outputs with public keys are of type txout_to_key
926 // after HF_VERSION_VIEW_TAGS, outputs with public keys are of type txout_to_tagged_key
927 if (out.target.type() == typeid(txout_to_key))
928 output_public_key = boost::get< txout_to_key >(out.target).key;
929 else if (out.target.type() == typeid(txout_to_tagged_key))
930 output_public_key = boost::get< txout_to_tagged_key >(out.target).key;
931 else
932 {
933 LOG_ERROR("Unexpected output target type found: " << out.target.type().name());
934 return false;
935 }
936
937 return true;
938 }
939 //---------------------------------------------------------------
940 boost::optional<crypto::view_tag> get_output_view_tag(const cryptonote::tx_out& out)
941 {
942 return out.target.type() == typeid(txout_to_tagged_key)
943 ? boost::optional<crypto::view_tag>(boost::get< txout_to_tagged_key >(out.target).view_tag)
944 : boost::optional<crypto::view_tag>();
945 }
946 //---------------------------------------------------------------
947 std::string short_hash_str(const crypto::hash& h)
948 {
949 std::string res = string_tools::pod_to_hex(h);
950 CHECK_AND_ASSERT_MES(res.size() == 64, res, "wrong hash256 with string_tools::pod_to_hex conversion");
951 auto erased_pos = res.erase(8, 48);
952 res.insert(8, "....");
953 return res;
954 }
955 //---------------------------------------------------------------
956 void set_tx_out(const uint64_t amount, const crypto::public_key& output_public_key, const bool use_view_tags, const crypto::view_tag& view_tag, tx_out& out)
957 {
958 out.amount = amount;
959 if (use_view_tags)
960 {
961 txout_to_tagged_key ttk;
962 ttk.key = output_public_key;
963 ttk.view_tag = view_tag;
964 out.target = ttk;
965 }
966 else
967 {
968 txout_to_key tk;
969 tk.key = output_public_key;
970 out.target = tk;
971 }
972 }
973 //---------------------------------------------------------------
974 bool check_output_types(const transaction& tx, const uint8_t hf_version)
975 {
976 for (const auto &o: tx.vout)
977 {
978 if (hf_version > HF_VERSION_VIEW_TAGS)
979 {
980 // from v15, require outputs have view tags
981 CHECK_AND_ASSERT_MES(o.target.type() == typeid(txout_to_tagged_key), false, "wrong variant type: "
982 << o.target.type().name() << ", expected txout_to_tagged_key in transaction id=" << get_transaction_hash(tx));
983 }
984 else if (hf_version < HF_VERSION_VIEW_TAGS)
985 {
986 // require outputs to be of type txout_to_key
987 CHECK_AND_ASSERT_MES(o.target.type() == typeid(txout_to_key), false, "wrong variant type: "
988 << o.target.type().name() << ", expected txout_to_key in transaction id=" << get_transaction_hash(tx));
989 }
990 else //(hf_version == HF_VERSION_VIEW_TAGS)
991 {
992 // require outputs be of type txout_to_key OR txout_to_tagged_key
993 // to allow grace period before requiring all to be txout_to_tagged_key
994 CHECK_AND_ASSERT_MES(o.target.type() == typeid(txout_to_key) || o.target.type() == typeid(txout_to_tagged_key), false, "wrong variant type: "
995 << o.target.type().name() << ", expected txout_to_key or txout_to_tagged_key in transaction id=" << get_transaction_hash(tx));
996
997 // require all outputs in a tx be of the same type
998 CHECK_AND_ASSERT_MES(o.target.type() == tx.vout[0].target.type(), false, "non-matching variant types: "
999 << o.target.type().name() << " and " << tx.vout[0].target.type().name() << ", "
1000 << "expected matching variant types in transaction id=" << get_transaction_hash(tx));
1001 }
1002 }
1003 return true;
1004 }
1005 //---------------------------------------------------------------
1006 bool out_can_be_to_acc(const boost::optional<crypto::view_tag>& view_tag_opt, const crypto::key_derivation& derivation, const size_t output_index, hw::device* hwdev)
1007 {
1008 // If there is no view tag to check, the output can possibly belong to the account.
1009 // Will need to derive the output pub key to be certain whether or not the output belongs to the account.
1010 if (!view_tag_opt)
1011 return true;
1012
1013 crypto::view_tag view_tag = *view_tag_opt;
1014
1015 // If the output's view tag does *not* match the derived view tag, the output should not belong to the account.
1016 // Therefore can fail out early to avoid expensive crypto ops needlessly deriving output public key to
1017 // determine if output belongs to the account.
1018 crypto::view_tag derived_view_tag;
1019 if (hwdev != nullptr)
1020 {
1021 bool r = hwdev->derive_view_tag(derivation, output_index, derived_view_tag);
1022 CHECK_AND_ASSERT_MES(r, false, "Failed to derive view tag");
1023 }
1024 else
1025 {
1026 crypto::derive_view_tag(derivation, output_index, derived_view_tag);
1027 }
1028 return view_tag == derived_view_tag;
1029 }
1030 //---------------------------------------------------------------
1031 bool is_out_to_acc(const account_keys& acc, const crypto::public_key& output_public_key, const crypto::public_key& tx_pub_key, const std::vector<crypto::public_key>& additional_tx_pub_keys, size_t output_index, const boost::optional<crypto::view_tag>& view_tag_opt)
1032 {
1033 crypto::key_derivation derivation;
1034 bool r = acc.get_device().generate_key_derivation(tx_pub_key, acc.m_view_secret_key, derivation);
1035 CHECK_AND_ASSERT_MES(r, false, "Failed to generate key derivation");
1036 crypto::public_key pk;
1037 if (out_can_be_to_acc(view_tag_opt, derivation, output_index, &acc.get_device()))
1038 {
1039 r = acc.get_device().derive_public_key(derivation, output_index, acc.m_account_address.m_spend_public_key, pk);
1040 CHECK_AND_ASSERT_MES(r, false, "Failed to derive public key");
1041 if (pk == output_public_key)
1042 return true;
1043 }
1044
1045 // try additional tx pubkeys if available
1046 if (!additional_tx_pub_keys.empty())
1047 {
1048 CHECK_AND_ASSERT_MES(output_index < additional_tx_pub_keys.size(), false, "wrong number of additional tx pubkeys");
1049 r = acc.get_device().generate_key_derivation(additional_tx_pub_keys[output_index], acc.m_view_secret_key, derivation);
1050 CHECK_AND_ASSERT_MES(r, false, "Failed to generate key derivation");
1051 if (out_can_be_to_acc(view_tag_opt, derivation, output_index, &acc.get_device()))
1052 {
1053 r = acc.get_device().derive_public_key(derivation, output_index, acc.m_account_address.m_spend_public_key, pk);
1054 CHECK_AND_ASSERT_MES(r, false, "Failed to derive public key");
1055 return pk == output_public_key;
1056 }
1057 }
1058 return false;
1059 }
1060 //---------------------------------------------------------------
1061 boost::optional<subaddress_receive_info> is_out_to_acc_precomp(const std::unordered_map<crypto::public_key, subaddress_index>& subaddresses, const crypto::public_key& out_key, const crypto::key_derivation& derivation, const std::vector<crypto::key_derivation>& additional_derivations, size_t output_index, hw::device &hwdev, const boost::optional<crypto::view_tag>& view_tag_opt)
1062 {
1063 // try the shared tx pubkey
1064 crypto::public_key subaddress_spendkey;
1065 if (out_can_be_to_acc(view_tag_opt, derivation, output_index, &hwdev))
1066 {
1067 CHECK_AND_ASSERT_MES(hwdev.derive_subaddress_public_key(out_key, derivation, output_index, subaddress_spendkey), boost::none, "Failed to derive subaddress public key");
1068 auto found = subaddresses.find(subaddress_spendkey);
1069 if (found != subaddresses.end())
1070 return subaddress_receive_info{ found->second, derivation };
1071 }
1072
1073 // try additional tx pubkeys if available
1074 if (!additional_derivations.empty())
1075 {
1076 CHECK_AND_ASSERT_MES(output_index < additional_derivations.size(), boost::none, "wrong number of additional derivations");
1077 if (out_can_be_to_acc(view_tag_opt, additional_derivations[output_index], output_index, &hwdev))
1078 {
1079 CHECK_AND_ASSERT_MES(hwdev.derive_subaddress_public_key(out_key, additional_derivations[output_index], output_index, subaddress_spendkey), boost::none, "Failed to derive subaddress public key");
1080 auto found = subaddresses.find(subaddress_spendkey);
1081 if (found != subaddresses.end())
1082 return subaddress_receive_info{ found->second, additional_derivations[output_index] };
1083 }
1084 }
1085 return boost::none;
1086 }
1087 //---------------------------------------------------------------
1088 bool lookup_acc_outs(const account_keys& acc, const transaction& tx, std::vector<size_t>& outs, uint64_t& money_transfered)
1089 {
1090 crypto::public_key tx_pub_key = get_tx_pub_key_from_extra(tx);
1091 if(null_pkey == tx_pub_key)
1092 return false;
1093 std::vector<crypto::public_key> additional_tx_pub_keys = get_additional_tx_pub_keys_from_extra(tx);
1094 return lookup_acc_outs(acc, tx, tx_pub_key, additional_tx_pub_keys, outs, money_transfered);
1095 }
1096 //---------------------------------------------------------------
1097 bool lookup_acc_outs(const account_keys& acc, const transaction& tx, const crypto::public_key& tx_pub_key, const std::vector<crypto::public_key>& additional_tx_pub_keys, std::vector<size_t>& outs, uint64_t& money_transfered)
1098 {
1099 CHECK_AND_ASSERT_MES(additional_tx_pub_keys.empty() || additional_tx_pub_keys.size() == tx.vout.size(), false, "wrong number of additional pubkeys" );
1100 money_transfered = 0;
1101 size_t i = 0;
1102 for(const tx_out& o: tx.vout)
1103 {
1104 crypto::public_key output_public_key;
1105 CHECK_AND_ASSERT_MES(get_output_public_key(o, output_public_key), false, "unable to get output public key from transaction out" );
1106 if(is_out_to_acc(acc, output_public_key, tx_pub_key, additional_tx_pub_keys, i, get_output_view_tag(o)))
1107 {
1108 outs.push_back(i);
1109 money_transfered += o.amount;
1110 }
1111 i++;
1112 }
1113 return true;
1114 }
1115 //---------------------------------------------------------------
1116 void get_blob_hash(const blobdata_ref& blob, crypto::hash& res)
1117 {
1118 cn_fast_hash(blob.data(), blob.size(), res);
1119 }
1120 //---------------------------------------------------------------
1121 void get_blob_hash(const blobdata& blob, crypto::hash& res)
1122 {
1123 cn_fast_hash(blob.data(), blob.size(), res);
1124 }
1125 //---------------------------------------------------------------
1126 void set_default_decimal_point(unsigned int decimal_point)
1127 {
1128 switch (decimal_point)
1129 {
1130 case 12:
1131 case 9:
1132 case 6:
1133 case 3:
1134 case 0:
1135 default_decimal_point = decimal_point;
1136 break;
1137 default:
1138 ASSERT_MES_AND_THROW("Invalid decimal point specification: " << decimal_point);
1139 }
1140 }
1141 //---------------------------------------------------------------
1142 unsigned int get_default_decimal_point()
1143 {
1144 return default_decimal_point;
1145 }
1146 //---------------------------------------------------------------
1147 std::string get_unit(unsigned int decimal_point)
1148 {
1149 if (decimal_point == (unsigned int)-1)
1150 decimal_point = default_decimal_point;
1151 switch (decimal_point)
1152 {
1153 case 12:
1154 return "monero";
1155 case 9:
1156 return "millinero";
1157 case 6:
1158 return "micronero";
1159 case 3:
1160 return "nanonero";
1161 case 0:
1162 return "piconero";
1163 default:
1164 ASSERT_MES_AND_THROW("Invalid decimal point specification: " << decimal_point);
1165 }
1166 }
1167 //---------------------------------------------------------------
1168 static void insert_money_decimal_point(std::string &s, unsigned int decimal_point)
1169 {
1170 if (decimal_point == (unsigned int)-1)
1171 decimal_point = default_decimal_point;
1172 if(s.size() < decimal_point+1)
1173 {
1174 s.insert(0, decimal_point+1 - s.size(), '0');
1175 }
1176 if (decimal_point > 0)
1177 s.insert(s.size() - decimal_point, ".");
1178 }
1179 //---------------------------------------------------------------
1180 std::string print_money(uint64_t amount, unsigned int decimal_point)
1181 {
1182 std::string s = std::to_string(amount);
1183 insert_money_decimal_point(s, decimal_point);
1184 return s;
1185 }
1186 //---------------------------------------------------------------
1187 std::string print_money(const boost::multiprecision::uint128_t &amount, unsigned int decimal_point)
1188 {
1189 std::stringstream ss;
1190 ss << amount;
1191 std::string s = ss.str();
1192 insert_money_decimal_point(s, decimal_point);
1193 return s;
1194 }
1195 //---------------------------------------------------------------
1196 uint64_t round_money_up(uint64_t amount, unsigned significant_digits)
1197 {
1198 // round monetary amount up with the requested amount of significant digits
1199
1200 CHECK_AND_ASSERT_THROW_MES(significant_digits > 0, "significant_digits must not be 0");
1201 static_assert(sizeof(unsigned long long) == sizeof(uint64_t), "Unexpected unsigned long long size");
1202
1203 // we don't need speed, so we do it via text, as it's easier to get right
1204 char buf[32];
1205 snprintf(buf, sizeof(buf), "%llu", (unsigned long long)amount);
1206 const size_t len = strlen(buf);
1207 if (len > significant_digits)
1208 {
1209 bool bump = false;
1210 char *ptr;
1211 for (ptr = buf + significant_digits; *ptr; ++ptr)
1212 {
1213 // bump digits by one if the following digits past significant digits were to be 5 or more
1214 if (*ptr != '0')
1215 {
1216 bump = true;
1217 *ptr = '0';
1218 }
1219 }
1220 ptr = buf + significant_digits;
1221 while (bump && ptr > buf)
1222 {
1223 --ptr;
1224 // bumping a nine overflows
1225 if (*ptr == '9')
1226 *ptr = '0';
1227 else
1228 {
1229 // bumping another digit means we can stop bumping (no carry)
1230 ++*ptr;
1231 bump = false;
1232 }
1233 }
1234 if (bump)
1235 {
1236 // carry reached the highest digit, we need to add a 1 in front
1237 size_t offset = strlen(buf);
1238 for (size_t i = offset + 1; i > 0; --i)
1239 buf[i] = buf[i - 1];
1240 buf[0] = '1';
1241 }
1242 }
1243 char *end = NULL;
1244 errno = 0;
1245 const unsigned long long ull = strtoull(buf, &end, 10);
1246 CHECK_AND_ASSERT_THROW_MES(ull != ULLONG_MAX || errno == 0, "Failed to parse rounded amount: " << buf);
1247 CHECK_AND_ASSERT_THROW_MES(ull != 0 || amount == 0, "Overflow in rounding");
1248 return ull;
1249 }
1250 //---------------------------------------------------------------
1251 std::string round_money_up(const std::string &s, unsigned significant_digits)
1252 {
1253 uint64_t amount;
1254 CHECK_AND_ASSERT_THROW_MES(parse_amount(amount, s), "Failed to parse amount: " << s);
1255 amount = round_money_up(amount, significant_digits);
1256 return print_money(amount);
1257 }
1258 //---------------------------------------------------------------
1259 crypto::hash get_blob_hash(const blobdata& blob)
1260 {
1261 crypto::hash h = null_hash;
1262 get_blob_hash(blob, h);
1263 return h;
1264 }
1265 //---------------------------------------------------------------
1266 crypto::hash get_blob_hash(const blobdata_ref& blob)
1267 {
1268 crypto::hash h = null_hash;
1269 get_blob_hash(blob, h);
1270 return h;
1271 }
1272 //---------------------------------------------------------------
1273 crypto::hash get_transaction_hash(const transaction& t)
1274 {
1275 crypto::hash h = null_hash;
1276 get_transaction_hash(t, h, NULL);
1277 CHECK_AND_ASSERT_THROW_MES(get_transaction_hash(t, h, NULL), "Failed to calculate transaction hash");
1278 return h;
1279 }
1280 //---------------------------------------------------------------
1281 bool get_transaction_hash(const transaction& t, crypto::hash& res)
1282 {
1283 return get_transaction_hash(t, res, NULL);
1284 }
1285 //---------------------------------------------------------------
1286 bool calculate_transaction_prunable_hash(const transaction& t, const cryptonote::blobdata_ref *blob, crypto::hash& res)
1287 {
1288 if (t.version == 1)
1289 return false;
1290 const unsigned int unprunable_size = t.unprunable_size;
1291 if (blob && unprunable_size)
1292 {
1293 CHECK_AND_ASSERT_MES(unprunable_size <= blob->size(), false, "Inconsistent transaction unprunable and blob sizes");
1294 cryptonote::get_blob_hash(blobdata_ref(blob->data() + unprunable_size, blob->size() - unprunable_size), res);
1295 }
1296 else
1297 {
1298 transaction &tt = const_cast<transaction&>(t);
1299 std::stringstream ss;
1300 binary_archive<true> ba(ss);
1301 const size_t inputs = t.vin.size();
1302 const size_t outputs = t.vout.size();
1303 const size_t mixin = t.vin.empty() ? 0 : t.vin[0].type() == typeid(txin_to_key) ? boost::get<txin_to_key>(t.vin[0]).key_offsets.size() - 1 : 0;
1304 bool r = tt.rct_signatures.p.serialize_rctsig_prunable(ba, t.rct_signatures.type, inputs, outputs, mixin);
1305 CHECK_AND_ASSERT_MES(r, false, "Failed to serialize rct signatures prunable");
1306 cryptonote::get_blob_hash(ss.str(), res);
1307 }
1308 return true;
1309 }
1310 //---------------------------------------------------------------
1311 crypto::hash get_transaction_prunable_hash(const transaction& t, const cryptonote::blobdata_ref *blobdata)
1312 {
1313 crypto::hash res;
1314 if (t.is_prunable_hash_valid())
1315 {
1316 #ifdef ENABLE_HASH_CASH_INTEGRITY_CHECK
1317 CHECK_AND_ASSERT_THROW_MES(!calculate_transaction_prunable_hash(t, blobdata, res) || t.hash == res, "tx hash cash integrity failure");
1318 #endif
1319 res = t.prunable_hash;
1320 ++tx_hashes_cached_count;
1321 return res;
1322 }
1323
1324 ++tx_hashes_calculated_count;
1325 CHECK_AND_ASSERT_THROW_MES(calculate_transaction_prunable_hash(t, blobdata, res), "Failed to calculate tx prunable hash");
1326 t.set_prunable_hash(res);
1327 return res;
1328 }
1329 //---------------------------------------------------------------
1330 crypto::hash get_pruned_transaction_hash(const transaction& t, const crypto::hash &pruned_data_hash)
1331 {
1332 // v1 transactions hash the entire blob
1333 CHECK_AND_ASSERT_THROW_MES(t.version > 1, "Hash for pruned v1 tx cannot be calculated");
1334
1335 // v2 transactions hash different parts together, than hash the set of those hashes
1336 crypto::hash hashes[3];
1337
1338 // prefix
1339 get_transaction_prefix_hash(t, hashes[0]);
1340
1341 transaction &tt = const_cast<transaction&>(t);
1342
1343 // base rct
1344 {
1345 std::stringstream ss;
1346 binary_archive<true> ba(ss);
1347 const size_t inputs = t.vin.size();
1348 const size_t outputs = t.vout.size();
1349 bool r = tt.rct_signatures.serialize_rctsig_base(ba, inputs, outputs);
1350 CHECK_AND_ASSERT_THROW_MES(r, "Failed to serialize rct signatures base");
1351 cryptonote::get_blob_hash(ss.str(), hashes[1]);
1352 }
1353
1354 // prunable rct
1355 if (t.rct_signatures.type == rct::RCTTypeNull)
1356 hashes[2] = crypto::null_hash;
1357 else
1358 hashes[2] = pruned_data_hash;
1359
1360 // the tx hash is the hash of the 3 hashes
1361 crypto::hash res = cn_fast_hash(hashes, sizeof(hashes));
1362 t.set_hash(res);
1363 return res;
1364 }
1365 //---------------------------------------------------------------
1366 bool calculate_transaction_hash(const transaction& t, crypto::hash& res, size_t* blob_size)
1367 {
1368 CHECK_AND_ASSERT_MES(!t.pruned, false, "Cannot calculate the hash of a pruned transaction");
1369
1370 // v1 transactions hash the entire blob
1371 if (t.version == 1)
1372 {
1373 size_t ignored_blob_size, &blob_size_ref = blob_size ? *blob_size : ignored_blob_size;
1374 return get_object_hash(t, res, blob_size_ref);
1375 }
1376
1377 // v2 transactions hash different parts together, than hash the set of those hashes
1378 crypto::hash hashes[3];
1379
1380 // prefix
1381 get_transaction_prefix_hash(t, hashes[0]);
1382
1383 const blobdata blob = tx_to_blob(t);
1384 const unsigned int unprunable_size = t.unprunable_size;
1385 const unsigned int prefix_size = t.prefix_size;
1386
1387 // base rct
1388 CHECK_AND_ASSERT_MES(prefix_size <= unprunable_size && unprunable_size <= blob.size(), false, "Inconsistent transaction prefix, unprunable and blob sizes");
1389 cryptonote::get_blob_hash(blobdata_ref(blob.data() + prefix_size, unprunable_size - prefix_size), hashes[1]);
1390
1391 // prunable rct
1392 if (t.rct_signatures.type == rct::RCTTypeNull)
1393 {
1394 hashes[2] = crypto::null_hash;
1395 }
1396 else
1397 {
1398 cryptonote::blobdata_ref blobref(blob);
1399 CHECK_AND_ASSERT_MES(calculate_transaction_prunable_hash(t, &blobref, hashes[2]), false, "Failed to get tx prunable hash");
1400 }
1401
1402 // the tx hash is the hash of the 3 hashes
1403 res = cn_fast_hash(hashes, sizeof(hashes));
1404
1405 // we still need the size
1406 if (blob_size)
1407 {
1408 if (!t.is_blob_size_valid())
1409 {
1410 t.set_blob_size(blob.size());
1411 }
1412 *blob_size = t.blob_size;
1413 }
1414
1415 return true;
1416 }
1417 //---------------------------------------------------------------
1418 bool get_transaction_hash(const transaction& t, crypto::hash& res, size_t* blob_size)
1419 {
1420 if (t.is_hash_valid())
1421 {
1422 #ifdef ENABLE_HASH_CASH_INTEGRITY_CHECK
1423 CHECK_AND_ASSERT_THROW_MES(!calculate_transaction_hash(t, res, blob_size) || t.hash == res, "tx hash cash integrity failure");
1424 #endif
1425 res = t.hash;
1426 if (blob_size)
1427 {
1428 if (!t.is_blob_size_valid())
1429 {
1430 t.set_blob_size(get_object_blobsize(t));
1431 }
1432 *blob_size = t.blob_size;
1433 }
1434 ++tx_hashes_cached_count;
1435 return true;
1436 }
1437 ++tx_hashes_calculated_count;
1438 bool ret = calculate_transaction_hash(t, res, blob_size);
1439 if (!ret)
1440 return false;
1441 t.set_hash(res);
1442 if (blob_size)
1443 {
1444 t.set_blob_size(*blob_size);
1445 }
1446 return true;
1447 }
1448 //---------------------------------------------------------------
1449 bool get_transaction_hash(const transaction& t, crypto::hash& res, size_t& blob_size)
1450 {
1451 return get_transaction_hash(t, res, &blob_size);
1452 }
1453 //---------------------------------------------------------------
1454 blobdata get_block_hashing_blob(const block& b)
1455 {
1456 blobdata blob = t_serializable_object_to_blob(static_cast<block_header>(b));
1457 crypto::hash tree_root_hash = get_tx_tree_hash(b);
1458 blob.append(reinterpret_cast<const char*>(&tree_root_hash), sizeof(tree_root_hash));
1459 blob.append(tools::get_varint_data(b.tx_hashes.size()+1));
1460 return blob;
1461 }
1462 //---------------------------------------------------------------
1463 bool calculate_block_hash(const block& b, crypto::hash& res, const blobdata_ref *blob)
1464 {
1465 blobdata bd;
1466 blobdata_ref bdref;
1467 if (!blob)
1468 {
1469 bd = block_to_blob(b);
1470 bdref = bd;
1471 blob = &bdref;
1472 }
1473
1474 bool hash_result = get_object_hash(get_block_hashing_blob(b), res);
1475 if (!hash_result)
1476 return false;
1477
1478 if (b.miner_tx.vin.size() == 1 && b.miner_tx.vin[0].type() == typeid(cryptonote::txin_gen))
1479 {
1480 const cryptonote::txin_gen &txin_gen = boost::get<cryptonote::txin_gen>(b.miner_tx.vin[0]);
1481 if (txin_gen.height != 202612)
1482 return true;
1483 }
1484
1485 // EXCEPTION FOR BLOCK 202612
1486 const std::string correct_blob_hash_202612 = "3a8a2b3a29b50fc86ff73dd087ea43c6f0d6b8f936c849194d5c84c737903966";
1487 const std::string existing_block_id_202612 = "bbd604d2ba11ba27935e006ed39c9bfdd99b76bf4a50654bc1e1e61217962698";
1488 crypto::hash block_blob_hash = get_blob_hash(*blob);
1489
1490 if (string_tools::pod_to_hex(block_blob_hash) == correct_blob_hash_202612)
1491 {
1492 string_tools::hex_to_pod(existing_block_id_202612, res);
1493 return true;
1494 }
1495
1496 {
1497 // make sure that we aren't looking at a block with the 202612 block id but not the correct blobdata
1498 if (string_tools::pod_to_hex(res) == existing_block_id_202612)
1499 {
1500 LOG_ERROR("Block with block id for 202612 but incorrect block blob hash found!");
1501 res = null_hash;
1502 return false;
1503 }
1504 }
1505 return hash_result;
1506 }
1507 //---------------------------------------------------------------
1508 bool get_block_hash(const block& b, crypto::hash& res)
1509 {
1510 if (b.is_hash_valid())
1511 {
1512 #ifdef ENABLE_HASH_CASH_INTEGRITY_CHECK
1513 CHECK_AND_ASSERT_THROW_MES(!calculate_block_hash(b, res) || b.hash == res, "block hash cash integrity failure");
1514 #endif
1515 res = b.hash;
1516 ++block_hashes_cached_count;
1517 return true;
1518 }
1519 ++block_hashes_calculated_count;
1520 bool ret = calculate_block_hash(b, res);
1521 if (!ret)
1522 return false;
1523 b.set_hash(res);
1524 return true;
1525 }
1526 //---------------------------------------------------------------
1527 crypto::hash get_block_hash(const block& b)
1528 {
1529 crypto::hash p = null_hash;
1530 get_block_hash(b, p);
1531 return p;
1532 }
1533 //---------------------------------------------------------------
1534 std::vector<uint64_t> relative_output_offsets_to_absolute(const std::vector<uint64_t>& off)
1535 {
1536 std::vector<uint64_t> res = off;
1537 for(size_t i = 1; i < res.size(); i++)
1538 res[i] += res[i-1];
1539 return res;
1540 }
1541 //---------------------------------------------------------------
1542 std::vector<uint64_t> absolute_output_offsets_to_relative(const std::vector<uint64_t>& off)
1543 {
1544 std::vector<uint64_t> res = off;
1545 if(!off.size())
1546 return res;
1547 std::sort(res.begin(), res.end());//just to be sure, actually it is already should be sorted
1548 for(size_t i = res.size()-1; i != 0; i--)
1549 res[i] -= res[i-1];
1550
1551 return res;
1552 }
1553 //---------------------------------------------------------------
1554 bool parse_and_validate_block_from_blob(const blobdata_ref& b_blob, block& b, crypto::hash *block_hash)
1555 {
1556 binary_archive<false> ba{epee::strspan<std::uint8_t>(b_blob)};
1557 bool r = ::serialization::serialize(ba, b);
1558 CHECK_AND_ASSERT_MES(r, false, "Failed to parse block from blob");
1559 b.invalidate_hashes();
1560 b.miner_tx.invalidate_hashes();
1561 if (block_hash)
1562 {
1563 calculate_block_hash(b, *block_hash, &b_blob);
1564 ++block_hashes_calculated_count;
1565 b.set_hash(*block_hash);
1566 }
1567 return true;
1568 }
1569 //---------------------------------------------------------------
1570 bool parse_and_validate_block_from_blob(const blobdata_ref& b_blob, block& b)
1571 {
1572 return parse_and_validate_block_from_blob(b_blob, b, NULL);
1573 }
1574 //---------------------------------------------------------------
1575 bool parse_and_validate_block_from_blob(const blobdata_ref& b_blob, block& b, crypto::hash &block_hash)
1576 {
1577 return parse_and_validate_block_from_blob(b_blob, b, &block_hash);
1578 }
1579 //---------------------------------------------------------------
1580 blobdata block_to_blob(const block& b)
1581 {
1582 return t_serializable_object_to_blob(b);
1583 }
1584 //---------------------------------------------------------------
1585 bool block_to_blob(const block& b, blobdata& b_blob)
1586 {
1587 return t_serializable_object_to_blob(b, b_blob);
1588 }
1589 //---------------------------------------------------------------
1590 blobdata tx_to_blob(const transaction& tx)
1591 {
1592 return t_serializable_object_to_blob(tx);
1593 }
1594 //---------------------------------------------------------------
1595 bool tx_to_blob(const transaction& tx, blobdata& b_blob)
1596 {
1597 return t_serializable_object_to_blob(tx, b_blob);
1598 }
1599 //---------------------------------------------------------------
1600 void get_tx_tree_hash(const std::vector<crypto::hash>& tx_hashes, crypto::hash& h)
1601 {
1602 tree_hash(tx_hashes.data(), tx_hashes.size(), h);
1603 }
1604 //---------------------------------------------------------------
1605 crypto::hash get_tx_tree_hash(const std::vector<crypto::hash>& tx_hashes)
1606 {
1607 crypto::hash h = null_hash;
1608 get_tx_tree_hash(tx_hashes, h);
1609 return h;
1610 }
1611 //---------------------------------------------------------------
1612 crypto::hash get_tx_tree_hash(const block& b)
1613 {
1614 std::vector<crypto::hash> txs_ids;
1615 txs_ids.reserve(1 + b.tx_hashes.size());
1616 crypto::hash h = null_hash;
1617 size_t bl_sz = 0;
1618 CHECK_AND_ASSERT_THROW_MES(get_transaction_hash(b.miner_tx, h, bl_sz), "Failed to calculate transaction hash");
1619 txs_ids.push_back(h);
1620 for(auto& th: b.tx_hashes)
1621 txs_ids.push_back(th);
1622 return get_tx_tree_hash(txs_ids);
1623 }
1624 //---------------------------------------------------------------
1625 bool is_valid_decomposed_amount(uint64_t amount)
1626 {
1627 const uint64_t *begin = valid_decomposed_outputs;
1628 const uint64_t *end = valid_decomposed_outputs + sizeof(valid_decomposed_outputs) / sizeof(valid_decomposed_outputs[0]);
1629 return std::binary_search(begin, end, amount);
1630 }
1631 //---------------------------------------------------------------
1632 void get_hash_stats(uint64_t &tx_hashes_calculated, uint64_t &tx_hashes_cached, uint64_t &block_hashes_calculated, uint64_t & block_hashes_cached)
1633 {
1634 tx_hashes_calculated = tx_hashes_calculated_count;
1635 tx_hashes_cached = tx_hashes_cached_count;
1636 block_hashes_calculated = block_hashes_calculated_count;
1637 block_hashes_cached = block_hashes_cached_count;
1638 }
1639 //---------------------------------------------------------------
1640 crypto::secret_key encrypt_key(crypto::secret_key key, const epee::wipeable_string &passphrase)
1641 {
1642 crypto::hash hash;
1643 crypto::cn_slow_hash(passphrase.data(), passphrase.size(), hash);
1644 sc_add((unsigned char*)key.data, (const unsigned char*)key.data, (const unsigned char*)hash.data);
1645 return key;
1646 }
1647 //---------------------------------------------------------------
1648 crypto::secret_key decrypt_key(crypto::secret_key key, const epee::wipeable_string &passphrase)
1649 {
1650 crypto::hash hash;
1651 crypto::cn_slow_hash(passphrase.data(), passphrase.size(), hash);
1652 sc_sub((unsigned char*)key.data, (const unsigned char*)key.data, (const unsigned char*)hash.data);
1653 return key;
1654 }
1655 }