Debian Codegraph @

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 const std::size_t len_varint_bytes = tools::get_varint_byte_size(extra_nonce.size());
745 tx_extra.resize(tx_extra.size() + 1 + len_varint_bytes + extra_nonce.size());
746 //write tag
747 tx_extra[start_pos] = TX_EXTRA_NONCE;
748 //write len
749 ++start_pos;
750 unsigned char * vp = tx_extra.data() + start_pos;
751 tools::write_varint(vp, extra_nonce.size());
752 assert(vp == tx_extra.data() + tx_extra.size() - extra_nonce.size());
753 //write data
754 start_pos += len_varint_bytes;
755 if (!extra_nonce.empty())
756 memcpy(&tx_extra[start_pos], extra_nonce.data(), extra_nonce.size());
757 return true;
758 }
759 //---------------------------------------------------------------
760 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)
761 {
762 CHECK_AND_ASSERT_MES(mm_merkle_tree_depth < 32, false, "merge mining merkle tree depth should be less than 32");
763 size_t start_pos = tx_extra.size();
764 tx_extra.resize(tx_extra.size() + 3 + 32);
765 //write tag
766 tx_extra[start_pos] = TX_EXTRA_MERGE_MINING_TAG;
767 //write data size
768 ++start_pos;
769 tx_extra[start_pos] = 33;
770 //write depth varint (always one byte here)
771 ++start_pos;
772 tx_extra[start_pos] = mm_merkle_tree_depth;
773 //write data
774 ++start_pos;
775 memcpy(&tx_extra[start_pos], &mm_merkle_root, 32);
776 return true;
777 }
778 //---------------------------------------------------------------
779 bool remove_field_from_tx_extra(std::vector<uint8_t>& tx_extra, const std::type_info &type)
780 {
781 if (tx_extra.empty())
782 return true;
783 std::string extra_str(reinterpret_cast<const char*>(tx_extra.data()), tx_extra.size());
784 binary_archive<false> ar{epee::strspan<std::uint8_t>(extra_str)};
785 std::ostringstream oss;
786 binary_archive<true> newar(oss);
787
788 do
789 {
790 tx_extra_field field;
791 bool r = ::do_serialize(ar, field);
792 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())));
793 if (field.type() != type)
794 ::do_serialize(newar, field);
795 } while (!ar.eof());
796 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())));
797 tx_extra.clear();
798 std::string s = oss.str();
799 tx_extra.reserve(s.size());
800 std::copy(s.begin(), s.end(), std::back_inserter(tx_extra));
801 return true;
802 }
803 //---------------------------------------------------------------
804 void set_payment_id_to_tx_extra_nonce(blobdata& extra_nonce, const crypto::hash& payment_id)
805 {
806 extra_nonce.clear();
807 extra_nonce.push_back(TX_EXTRA_NONCE_PAYMENT_ID);
808 const uint8_t* payment_id_ptr = reinterpret_cast<const uint8_t*>(&payment_id);
809 std::copy(payment_id_ptr, payment_id_ptr + sizeof(payment_id), std::back_inserter(extra_nonce));
810 }
811 //---------------------------------------------------------------
812 void set_encrypted_payment_id_to_tx_extra_nonce(blobdata& extra_nonce, const crypto::hash8& payment_id)
813 {
814 extra_nonce.clear();
815 extra_nonce.push_back(TX_EXTRA_NONCE_ENCRYPTED_PAYMENT_ID);
816 const uint8_t* payment_id_ptr = reinterpret_cast<const uint8_t*>(&payment_id);
817 std::copy(payment_id_ptr, payment_id_ptr + sizeof(payment_id), std::back_inserter(extra_nonce));
818 }
819 //---------------------------------------------------------------
820 bool get_payment_id_from_tx_extra_nonce(const blobdata& extra_nonce, crypto::hash& payment_id)
821 {
822 if(sizeof(crypto::hash) + 1 != extra_nonce.size())
823 return false;
824 if(TX_EXTRA_NONCE_PAYMENT_ID != extra_nonce[0])
825 return false;
826 payment_id = *reinterpret_cast<const crypto::hash*>(extra_nonce.data() + 1);
827 return true;
828 }
829 //---------------------------------------------------------------
830 bool get_encrypted_payment_id_from_tx_extra_nonce(const blobdata& extra_nonce, crypto::hash8& payment_id)
831 {
832 if(sizeof(crypto::hash8) + 1 != extra_nonce.size())
833 return false;
834 if (TX_EXTRA_NONCE_ENCRYPTED_PAYMENT_ID != extra_nonce[0])
835 return false;
836 payment_id = *reinterpret_cast<const crypto::hash8*>(extra_nonce.data() + 1);
837 return true;
838 }
839 //---------------------------------------------------------------
840 bool get_inputs_money_amount(const transaction& tx, uint64_t& money)
841 {
842 money = 0;
843 for(const auto& in: tx.vin)
844 {
845 CHECKED_GET_SPECIFIC_VARIANT(in, const txin_to_key, tokey_in, false);
846 money += tokey_in.amount;
847 }
848 return true;
849 }
850 //---------------------------------------------------------------
851 uint64_t get_block_height(const block& b)
852 {
853 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");
854 CHECKED_GET_SPECIFIC_VARIANT(b.miner_tx.vin[0], const txin_gen, coinbase_in, 0);
855 return coinbase_in.height;
856 }
857 //---------------------------------------------------------------
858 bool check_inputs_types_supported(const transaction& tx)
859 {
860 for(const auto& in: tx.vin)
861 {
862 CHECK_AND_ASSERT_MES(in.type() == typeid(txin_to_key), false, "wrong variant type: "
863 << in.type().name() << ", expected " << typeid(txin_to_key).name()
864 << ", in transaction id=" << get_transaction_hash(tx));
865
866 }
867 return true;
868 }
869 //-----------------------------------------------------------------------------------------------
870 bool check_outs_valid(const transaction& tx)
871 {
872 for(const tx_out& out: tx.vout)
873 {
874 crypto::public_key output_public_key;
875 CHECK_AND_ASSERT_MES(get_output_public_key(out, output_public_key), false, "Failed to get output public key (output type: "
876 << out.target.type().name() << "), in transaction id=" << get_transaction_hash(tx));
877
878 if (tx.version == 1)
879 {
880 CHECK_AND_NO_ASSERT_MES(0 < out.amount, false, "zero amount output in transaction id=" << get_transaction_hash(tx));
881 }
882
883 if(!check_key(output_public_key))
884 return false;
885 }
886 return true;
887 }
888 //-----------------------------------------------------------------------------------------------
889 bool check_money_overflow(const transaction& tx)
890 {
891 return check_inputs_overflow(tx) && check_outs_overflow(tx);
892 }
893 //---------------------------------------------------------------
894 bool check_inputs_overflow(const transaction& tx)
895 {
896 uint64_t money = 0;
897 for(const auto& in: tx.vin)
898 {
899 CHECKED_GET_SPECIFIC_VARIANT(in, const txin_to_key, tokey_in, false);
900 if(money > tokey_in.amount + money)
901 return false;
902 money += tokey_in.amount;
903 }
904 return true;
905 }
906 //---------------------------------------------------------------
907 bool check_outs_overflow(const transaction& tx)
908 {
909 uint64_t money = 0;
910 for(const auto& o: tx.vout)
911 {
912 if(money > o.amount + money)
913 return false;
914 money += o.amount;
915 }
916 return true;
917 }
918 //---------------------------------------------------------------
919 uint64_t get_outs_money_amount(const transaction& tx)
920 {
921 uint64_t outputs_amount = 0;
922 for(const auto& o: tx.vout)
923 outputs_amount += o.amount;
924 return outputs_amount;
925 }
926 //---------------------------------------------------------------
927 bool get_output_public_key(const cryptonote::tx_out& out, crypto::public_key& output_public_key)
928 {
929 // before HF_VERSION_VIEW_TAGS, outputs with public keys are of type txout_to_key
930 // after HF_VERSION_VIEW_TAGS, outputs with public keys are of type txout_to_tagged_key
931 if (out.target.type() == typeid(txout_to_key))
932 output_public_key = boost::get< txout_to_key >(out.target).key;
933 else if (out.target.type() == typeid(txout_to_tagged_key))
934 output_public_key = boost::get< txout_to_tagged_key >(out.target).key;
935 else
936 {
937 LOG_ERROR("Unexpected output target type found: " << out.target.type().name());
938 return false;
939 }
940
941 return true;
942 }
943 //---------------------------------------------------------------
944 boost::optional<crypto::view_tag> get_output_view_tag(const cryptonote::tx_out& out)
945 {
946 return out.target.type() == typeid(txout_to_tagged_key)
947 ? boost::optional<crypto::view_tag>(boost::get< txout_to_tagged_key >(out.target).view_tag)
948 : boost::optional<crypto::view_tag>();
949 }
950 //---------------------------------------------------------------
951 std::string short_hash_str(const crypto::hash& h)
952 {
953 std::string res = string_tools::pod_to_hex(h);
954 CHECK_AND_ASSERT_MES(res.size() == 64, res, "wrong hash256 with string_tools::pod_to_hex conversion");
955 auto erased_pos = res.erase(8, 48);
956 res.insert(8, "....");
957 return res;
958 }
959 //---------------------------------------------------------------
960 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)
961 {
962 out.amount = amount;
963 if (use_view_tags)
964 {
965 txout_to_tagged_key ttk;
966 ttk.key = output_public_key;
967 ttk.view_tag = view_tag;
968 out.target = ttk;
969 }
970 else
971 {
972 txout_to_key tk;
973 tk.key = output_public_key;
974 out.target = tk;
975 }
976 }
977 //---------------------------------------------------------------
978 bool check_output_types(const transaction& tx, const uint8_t hf_version)
979 {
980 for (const auto &o: tx.vout)
981 {
982 if (hf_version > HF_VERSION_VIEW_TAGS)
983 {
984 // from v15, require outputs have view tags
985 CHECK_AND_ASSERT_MES(o.target.type() == typeid(txout_to_tagged_key), false, "wrong variant type: "
986 << o.target.type().name() << ", expected txout_to_tagged_key in transaction id=" << get_transaction_hash(tx));
987 }
988 else if (hf_version < HF_VERSION_VIEW_TAGS)
989 {
990 // require outputs to be of type txout_to_key
991 CHECK_AND_ASSERT_MES(o.target.type() == typeid(txout_to_key), false, "wrong variant type: "
992 << o.target.type().name() << ", expected txout_to_key in transaction id=" << get_transaction_hash(tx));
993 }
994 else //(hf_version == HF_VERSION_VIEW_TAGS)
995 {
996 // require outputs be of type txout_to_key OR txout_to_tagged_key
997 // to allow grace period before requiring all to be txout_to_tagged_key
998 CHECK_AND_ASSERT_MES(o.target.type() == typeid(txout_to_key) || o.target.type() == typeid(txout_to_tagged_key), false, "wrong variant type: "
999 << o.target.type().name() << ", expected txout_to_key or txout_to_tagged_key in transaction id=" << get_transaction_hash(tx));
1000
1001 // require all outputs in a tx be of the same type
1002 CHECK_AND_ASSERT_MES(o.target.type() == tx.vout[0].target.type(), false, "non-matching variant types: "
1003 << o.target.type().name() << " and " << tx.vout[0].target.type().name() << ", "
1004 << "expected matching variant types in transaction id=" << get_transaction_hash(tx));
1005 }
1006 }
1007 return true;
1008 }
1009 //---------------------------------------------------------------
1010 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)
1011 {
1012 // If there is no view tag to check, the output can possibly belong to the account.
1013 // Will need to derive the output pub key to be certain whether or not the output belongs to the account.
1014 if (!view_tag_opt)
1015 return true;
1016
1017 crypto::view_tag view_tag = *view_tag_opt;
1018
1019 // If the output's view tag does *not* match the derived view tag, the output should not belong to the account.
1020 // Therefore can fail out early to avoid expensive crypto ops needlessly deriving output public key to
1021 // determine if output belongs to the account.
1022 crypto::view_tag derived_view_tag;
1023 if (hwdev != nullptr)
1024 {
1025 bool r = hwdev->derive_view_tag(derivation, output_index, derived_view_tag);
1026 CHECK_AND_ASSERT_MES(r, false, "Failed to derive view tag");
1027 }
1028 else
1029 {
1030 crypto::derive_view_tag(derivation, output_index, derived_view_tag);
1031 }
1032 return view_tag == derived_view_tag;
1033 }
1034 //---------------------------------------------------------------
1035 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)
1036 {
1037 crypto::key_derivation derivation;
1038 bool r = acc.get_device().generate_key_derivation(tx_pub_key, acc.m_view_secret_key, derivation);
1039 CHECK_AND_ASSERT_MES(r, false, "Failed to generate key derivation");
1040 crypto::public_key pk;
1041 if (out_can_be_to_acc(view_tag_opt, derivation, output_index, &acc.get_device()))
1042 {
1043 r = acc.get_device().derive_public_key(derivation, output_index, acc.m_account_address.m_spend_public_key, pk);
1044 CHECK_AND_ASSERT_MES(r, false, "Failed to derive public key");
1045 if (pk == output_public_key)
1046 return true;
1047 }
1048
1049 // try additional tx pubkeys if available
1050 if (!additional_tx_pub_keys.empty())
1051 {
1052 CHECK_AND_ASSERT_MES(output_index < additional_tx_pub_keys.size(), false, "wrong number of additional tx pubkeys");
1053 r = acc.get_device().generate_key_derivation(additional_tx_pub_keys[output_index], acc.m_view_secret_key, derivation);
1054 CHECK_AND_ASSERT_MES(r, false, "Failed to generate key derivation");
1055 if (out_can_be_to_acc(view_tag_opt, derivation, output_index, &acc.get_device()))
1056 {
1057 r = acc.get_device().derive_public_key(derivation, output_index, acc.m_account_address.m_spend_public_key, pk);
1058 CHECK_AND_ASSERT_MES(r, false, "Failed to derive public key");
1059 return pk == output_public_key;
1060 }
1061 }
1062 return false;
1063 }
1064 //---------------------------------------------------------------
1065 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)
1066 {
1067 // try the shared tx pubkey
1068 crypto::public_key subaddress_spendkey;
1069 if (out_can_be_to_acc(view_tag_opt, derivation, output_index, &hwdev))
1070 {
1071 CHECK_AND_ASSERT_MES(hwdev.derive_subaddress_public_key(out_key, derivation, output_index, subaddress_spendkey), boost::none, "Failed to derive subaddress public key");
1072 auto found = subaddresses.find(subaddress_spendkey);
1073 if (found != subaddresses.end())
1074 return subaddress_receive_info{ found->second, derivation };
1075 }
1076
1077 // try additional tx pubkeys if available
1078 if (!additional_derivations.empty())
1079 {
1080 CHECK_AND_ASSERT_MES(output_index < additional_derivations.size(), boost::none, "wrong number of additional derivations");
1081 if (out_can_be_to_acc(view_tag_opt, additional_derivations[output_index], output_index, &hwdev))
1082 {
1083 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");
1084 auto found = subaddresses.find(subaddress_spendkey);
1085 if (found != subaddresses.end())
1086 return subaddress_receive_info{ found->second, additional_derivations[output_index] };
1087 }
1088 }
1089 return boost::none;
1090 }
1091 //---------------------------------------------------------------
1092 bool lookup_acc_outs(const account_keys& acc, const transaction& tx, std::vector<size_t>& outs, uint64_t& money_transfered)
1093 {
1094 crypto::public_key tx_pub_key = get_tx_pub_key_from_extra(tx);
1095 if(null_pkey == tx_pub_key)
1096 return false;
1097 std::vector<crypto::public_key> additional_tx_pub_keys = get_additional_tx_pub_keys_from_extra(tx);
1098 return lookup_acc_outs(acc, tx, tx_pub_key, additional_tx_pub_keys, outs, money_transfered);
1099 }
1100 //---------------------------------------------------------------
1101 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)
1102 {
1103 CHECK_AND_ASSERT_MES(additional_tx_pub_keys.empty() || additional_tx_pub_keys.size() == tx.vout.size(), false, "wrong number of additional pubkeys" );
1104 money_transfered = 0;
1105 size_t i = 0;
1106 for(const tx_out& o: tx.vout)
1107 {
1108 crypto::public_key output_public_key;
1109 CHECK_AND_ASSERT_MES(get_output_public_key(o, output_public_key), false, "unable to get output public key from transaction out" );
1110 if(is_out_to_acc(acc, output_public_key, tx_pub_key, additional_tx_pub_keys, i, get_output_view_tag(o)))
1111 {
1112 outs.push_back(i);
1113 money_transfered += o.amount;
1114 }
1115 i++;
1116 }
1117 return true;
1118 }
1119 //---------------------------------------------------------------
1120 void get_blob_hash(const blobdata_ref& blob, crypto::hash& res)
1121 {
1122 cn_fast_hash(blob.data(), blob.size(), res);
1123 }
1124 //---------------------------------------------------------------
1125 void get_blob_hash(const blobdata& blob, crypto::hash& res)
1126 {
1127 cn_fast_hash(blob.data(), blob.size(), res);
1128 }
1129 //---------------------------------------------------------------
1130 void set_default_decimal_point(unsigned int decimal_point)
1131 {
1132 switch (decimal_point)
1133 {
1134 case 12:
1135 case 9:
1136 case 6:
1137 case 3:
1138 case 0:
1139 default_decimal_point = decimal_point;
1140 break;
1141 default:
1142 ASSERT_MES_AND_THROW("Invalid decimal point specification: " << decimal_point);
1143 }
1144 }
1145 //---------------------------------------------------------------
1146 unsigned int get_default_decimal_point()
1147 {
1148 return default_decimal_point;
1149 }
1150 //---------------------------------------------------------------
1151 std::string get_unit(unsigned int decimal_point)
1152 {
1153 if (decimal_point == (unsigned int)-1)
1154 decimal_point = default_decimal_point;
1155 switch (decimal_point)
1156 {
1157 case 12:
1158 return "monero";
1159 case 9:
1160 return "millinero";
1161 case 6:
1162 return "micronero";
1163 case 3:
1164 return "nanonero";
1165 case 0:
1166 return "piconero";
1167 default:
1168 ASSERT_MES_AND_THROW("Invalid decimal point specification: " << decimal_point);
1169 }
1170 }
1171 //---------------------------------------------------------------
1172 static void insert_money_decimal_point(std::string &s, unsigned int decimal_point)
1173 {
1174 if (decimal_point == (unsigned int)-1)
1175 decimal_point = default_decimal_point;
1176 if(s.size() < decimal_point+1)
1177 {
1178 s.insert(0, decimal_point+1 - s.size(), '0');
1179 }
1180 if (decimal_point > 0)
1181 s.insert(s.size() - decimal_point, ".");
1182 }
1183 //---------------------------------------------------------------
1184 std::string print_money(uint64_t amount, unsigned int decimal_point)
1185 {
1186 std::string s = std::to_string(amount);
1187 insert_money_decimal_point(s, decimal_point);
1188 return s;
1189 }
1190 //---------------------------------------------------------------
1191 std::string print_money(const boost::multiprecision::uint128_t &amount, unsigned int decimal_point)
1192 {
1193 std::stringstream ss;
1194 ss << amount;
1195 std::string s = ss.str();
1196 insert_money_decimal_point(s, decimal_point);
1197 return s;
1198 }
1199 //---------------------------------------------------------------
1200 uint64_t round_money_up(uint64_t amount, unsigned significant_digits)
1201 {
1202 // round monetary amount up with the requested amount of significant digits
1203
1204 CHECK_AND_ASSERT_THROW_MES(significant_digits > 0, "significant_digits must not be 0");
1205 static_assert(sizeof(unsigned long long) == sizeof(uint64_t), "Unexpected unsigned long long size");
1206
1207 // we don't need speed, so we do it via text, as it's easier to get right
1208 char buf[32];
1209 snprintf(buf, sizeof(buf), "%llu", (unsigned long long)amount);
1210 const size_t len = strlen(buf);
1211 if (len > significant_digits)
1212 {
1213 bool bump = false;
1214 char *ptr;
1215 for (ptr = buf + significant_digits; *ptr; ++ptr)
1216 {
1217 // bump digits by one if the following digits past significant digits were to be 5 or more
1218 if (*ptr != '0')
1219 {
1220 bump = true;
1221 *ptr = '0';
1222 }
1223 }
1224 ptr = buf + significant_digits;
1225 while (bump && ptr > buf)
1226 {
1227 --ptr;
1228 // bumping a nine overflows
1229 if (*ptr == '9')
1230 *ptr = '0';
1231 else
1232 {
1233 // bumping another digit means we can stop bumping (no carry)
1234 ++*ptr;
1235 bump = false;
1236 }
1237 }
1238 if (bump)
1239 {
1240 // carry reached the highest digit, we need to add a 1 in front
1241 size_t offset = strlen(buf);
1242 for (size_t i = offset + 1; i > 0; --i)
1243 buf[i] = buf[i - 1];
1244 buf[0] = '1';
1245 }
1246 }
1247 char *end = NULL;
1248 errno = 0;
1249 const unsigned long long ull = strtoull(buf, &end, 10);
1250 CHECK_AND_ASSERT_THROW_MES(ull != ULLONG_MAX || errno == 0, "Failed to parse rounded amount: " << buf);
1251 CHECK_AND_ASSERT_THROW_MES(ull != 0 || amount == 0, "Overflow in rounding");
1252 return ull;
1253 }
1254 //---------------------------------------------------------------
1255 std::string round_money_up(const std::string &s, unsigned significant_digits)
1256 {
1257 uint64_t amount;
1258 CHECK_AND_ASSERT_THROW_MES(parse_amount(amount, s), "Failed to parse amount: " << s);
1259 amount = round_money_up(amount, significant_digits);
1260 return print_money(amount);
1261 }
1262 //---------------------------------------------------------------
1263 crypto::hash get_blob_hash(const blobdata& blob)
1264 {
1265 crypto::hash h = null_hash;
1266 get_blob_hash(blob, h);
1267 return h;
1268 }
1269 //---------------------------------------------------------------
1270 crypto::hash get_blob_hash(const blobdata_ref& blob)
1271 {
1272 crypto::hash h = null_hash;
1273 get_blob_hash(blob, h);
1274 return h;
1275 }
1276 //---------------------------------------------------------------
1277 crypto::hash get_transaction_hash(const transaction& t)
1278 {
1279 crypto::hash h = null_hash;
1280 CHECK_AND_ASSERT_THROW_MES(get_transaction_hash(t, h, NULL), "Failed to calculate transaction hash");
1281 return h;
1282 }
1283 //---------------------------------------------------------------
1284 bool get_transaction_hash(const transaction& t, crypto::hash& res)
1285 {
1286 return get_transaction_hash(t, res, NULL);
1287 }
1288 //---------------------------------------------------------------
1289 bool calculate_transaction_prunable_hash(const transaction& t, const cryptonote::blobdata_ref *blob, crypto::hash& res)
1290 {
1291 if (t.version == 1)
1292 return false;
1293 const unsigned int unprunable_size = t.unprunable_size;
1294 if (blob && unprunable_size)
1295 {
1296 CHECK_AND_ASSERT_MES(unprunable_size <= blob->size(), false, "Inconsistent transaction unprunable and blob sizes");
1297 cryptonote::get_blob_hash(blobdata_ref(blob->data() + unprunable_size, blob->size() - unprunable_size), res);
1298 }
1299 else
1300 {
1301 transaction &tt = const_cast<transaction&>(t);
1302 std::stringstream ss;
1303 binary_archive<true> ba(ss);
1304 const size_t inputs = t.vin.size();
1305 const size_t outputs = t.vout.size();
1306 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;
1307 bool r = tt.rct_signatures.p.serialize_rctsig_prunable(ba, t.rct_signatures.type, inputs, outputs, mixin);
1308 CHECK_AND_ASSERT_MES(r, false, "Failed to serialize rct signatures prunable");
1309 cryptonote::get_blob_hash(ss.str(), res);
1310 }
1311 return true;
1312 }
1313 //---------------------------------------------------------------
1314 crypto::hash get_transaction_prunable_hash(const transaction& t, const cryptonote::blobdata_ref *blobdata)
1315 {
1316 crypto::hash res;
1317 if (t.is_prunable_hash_valid())
1318 {
1319 #ifdef ENABLE_HASH_CASH_INTEGRITY_CHECK
1320 CHECK_AND_ASSERT_THROW_MES(!calculate_transaction_prunable_hash(t, blobdata, res) || t.hash == res, "tx hash cash integrity failure");
1321 #endif
1322 res = t.prunable_hash;
1323 ++tx_hashes_cached_count;
1324 return res;
1325 }
1326
1327 ++tx_hashes_calculated_count;
1328 CHECK_AND_ASSERT_THROW_MES(calculate_transaction_prunable_hash(t, blobdata, res), "Failed to calculate tx prunable hash");
1329 t.set_prunable_hash(res);
1330 return res;
1331 }
1332 //---------------------------------------------------------------
1333 bool get_pruned_transaction_hash(const transaction& t, const crypto::hash &pruned_data_hash, crypto::hash &res)
1334 {
1335 // v1 transactions hash the entire blob
1336 CHECK_AND_ASSERT_MES(t.version > 1, false, "Hash for pruned v1 tx cannot be calculated");
1337
1338 // v2 transactions hash different parts together, than hash the set of those hashes
1339 crypto::hash hashes[3];
1340
1341 // prefix
1342 get_transaction_prefix_hash(t, hashes[0]);
1343
1344 transaction &tt = const_cast<transaction&>(t);
1345
1346 // base rct
1347 {
1348 std::stringstream ss;
1349 binary_archive<true> ba(ss);
1350 const size_t inputs = t.vin.size();
1351 const size_t outputs = t.vout.size();
1352 bool r = tt.rct_signatures.serialize_rctsig_base(ba, inputs, outputs);
1353 CHECK_AND_ASSERT_MES(r, false, "Failed to serialize rct signatures base");
1354 cryptonote::get_blob_hash(ss.str(), hashes[1]);
1355 }
1356
1357 // prunable rct
1358 if (t.rct_signatures.type == rct::RCTTypeNull)
1359 hashes[2] = crypto::null_hash;
1360 else
1361 hashes[2] = pruned_data_hash;
1362
1363 // the tx hash is the hash of the 3 hashes
1364 res = cn_fast_hash(hashes, sizeof(hashes));
1365 t.set_hash(res);
1366 return true;
1367 }
1368 //---------------------------------------------------------------
1369 bool calculate_transaction_hash(const transaction& t, crypto::hash& res, size_t* blob_size)
1370 {
1371 CHECK_AND_ASSERT_MES(!t.pruned, false, "Cannot calculate the hash of a pruned transaction");
1372
1373 // v1 transactions hash the entire blob
1374 if (t.version == 1)
1375 {
1376 size_t ignored_blob_size, &blob_size_ref = blob_size ? *blob_size : ignored_blob_size;
1377 return get_object_hash(t, res, blob_size_ref);
1378 }
1379
1380 // v2 transactions hash different parts together, than hash the set of those hashes
1381 crypto::hash hashes[3];
1382
1383 // prefix
1384 get_transaction_prefix_hash(t, hashes[0]);
1385
1386 const blobdata blob = tx_to_blob(t);
1387 const unsigned int unprunable_size = t.unprunable_size;
1388 const unsigned int prefix_size = t.prefix_size;
1389
1390 // base rct
1391 CHECK_AND_ASSERT_MES(prefix_size <= unprunable_size && unprunable_size <= blob.size(), false, "Inconsistent transaction prefix, unprunable and blob sizes");
1392 cryptonote::get_blob_hash(blobdata_ref(blob.data() + prefix_size, unprunable_size - prefix_size), hashes[1]);
1393
1394 // prunable rct
1395 if (t.rct_signatures.type == rct::RCTTypeNull)
1396 {
1397 hashes[2] = crypto::null_hash;
1398 }
1399 else
1400 {
1401 cryptonote::blobdata_ref blobref(blob);
1402 CHECK_AND_ASSERT_MES(calculate_transaction_prunable_hash(t, &blobref, hashes[2]), false, "Failed to get tx prunable hash");
1403 }
1404
1405 // the tx hash is the hash of the 3 hashes
1406 res = cn_fast_hash(hashes, sizeof(hashes));
1407
1408 // we still need the size
1409 if (blob_size)
1410 {
1411 if (!t.is_blob_size_valid())
1412 {
1413 t.set_blob_size(blob.size());
1414 }
1415 *blob_size = t.blob_size;
1416 }
1417
1418 return true;
1419 }
1420 //---------------------------------------------------------------
1421 bool get_transaction_hash(const transaction& t, crypto::hash& res, size_t* blob_size)
1422 {
1423 if (t.is_hash_valid())
1424 {
1425 #ifdef ENABLE_HASH_CASH_INTEGRITY_CHECK
1426 CHECK_AND_ASSERT_THROW_MES(!calculate_transaction_hash(t, res, blob_size) || t.hash == res, "tx hash cash integrity failure");
1427 #endif
1428 res = t.hash;
1429 if (blob_size)
1430 {
1431 if (!t.is_blob_size_valid())
1432 {
1433 t.set_blob_size(get_object_blobsize(t));
1434 }
1435 *blob_size = t.blob_size;
1436 }
1437 ++tx_hashes_cached_count;
1438 return true;
1439 }
1440 ++tx_hashes_calculated_count;
1441 bool ret = calculate_transaction_hash(t, res, blob_size);
1442 if (!ret)
1443 return false;
1444 t.set_hash(res);
1445 if (blob_size)
1446 {
1447 t.set_blob_size(*blob_size);
1448 }
1449 return true;
1450 }
1451 //---------------------------------------------------------------
1452 bool get_transaction_hash(const transaction& t, crypto::hash& res, size_t& blob_size)
1453 {
1454 return get_transaction_hash(t, res, &blob_size);
1455 }
1456 //---------------------------------------------------------------
1457 blobdata get_block_hashing_blob(const block& b)
1458 {
1459 blobdata blob = t_serializable_object_to_blob(static_cast<block_header>(b));
1460 crypto::hash tree_root_hash = get_tx_tree_hash(b);
1461 blob.append(reinterpret_cast<const char*>(&tree_root_hash), sizeof(tree_root_hash));
1462 blob.append(tools::get_varint_data(b.tx_hashes.size()+1));
1463 return blob;
1464 }
1465 //---------------------------------------------------------------
1466 bool calculate_block_hash(const block& b, crypto::hash& res, const blobdata_ref *blob)
1467 {
1468 blobdata bd;
1469 blobdata_ref bdref;
1470 if (!blob)
1471 {
1472 bd = block_to_blob(b);
1473 bdref = bd;
1474 blob = &bdref;
1475 }
1476
1477 bool hash_result = get_object_hash(get_block_hashing_blob(b), res);
1478 if (!hash_result)
1479 return false;
1480
1481 if (b.miner_tx.vin.size() == 1 && b.miner_tx.vin[0].type() == typeid(cryptonote::txin_gen))
1482 {
1483 const cryptonote::txin_gen &txin_gen = boost::get<cryptonote::txin_gen>(b.miner_tx.vin[0]);
1484 if (txin_gen.height != 202612)
1485 return true;
1486 }
1487
1488 // EXCEPTION FOR BLOCK 202612
1489 const std::string correct_blob_hash_202612 = "3a8a2b3a29b50fc86ff73dd087ea43c6f0d6b8f936c849194d5c84c737903966";
1490 const std::string existing_block_id_202612 = "bbd604d2ba11ba27935e006ed39c9bfdd99b76bf4a50654bc1e1e61217962698";
1491 crypto::hash block_blob_hash = get_blob_hash(*blob);
1492
1493 if (string_tools::pod_to_hex(block_blob_hash) == correct_blob_hash_202612)
1494 {
1495 string_tools::hex_to_pod(existing_block_id_202612, res);
1496 return true;
1497 }
1498
1499 {
1500 // make sure that we aren't looking at a block with the 202612 block id but not the correct blobdata
1501 if (string_tools::pod_to_hex(res) == existing_block_id_202612)
1502 {
1503 LOG_ERROR("Block with block id for 202612 but incorrect block blob hash found!");
1504 res = null_hash;
1505 return false;
1506 }
1507 }
1508 return hash_result;
1509 }
1510 //---------------------------------------------------------------
1511 bool get_block_hash(const block& b, crypto::hash& res)
1512 {
1513 if (b.is_hash_valid())
1514 {
1515 #ifdef ENABLE_HASH_CASH_INTEGRITY_CHECK
1516 CHECK_AND_ASSERT_THROW_MES(!calculate_block_hash(b, res) || b.hash == res, "block hash cash integrity failure");
1517 #endif
1518 res = b.hash;
1519 ++block_hashes_cached_count;
1520 return true;
1521 }
1522 ++block_hashes_calculated_count;
1523 bool ret = calculate_block_hash(b, res);
1524 if (!ret)
1525 return false;
1526 b.set_hash(res);
1527 return true;
1528 }
1529 //---------------------------------------------------------------
1530 crypto::hash get_block_hash(const block& b)
1531 {
1532 crypto::hash p = null_hash;
1533 get_block_hash(b, p);
1534 return p;
1535 }
1536 //---------------------------------------------------------------
1537 std::vector<uint64_t> relative_output_offsets_to_absolute(const std::vector<uint64_t>& off)
1538 {
1539 std::vector<uint64_t> res = off;
1540 for(size_t i = 1; i < res.size(); i++)
1541 res[i] += res[i-1];
1542 return res;
1543 }
1544 //---------------------------------------------------------------
1545 std::vector<uint64_t> absolute_output_offsets_to_relative(const std::vector<uint64_t>& off)
1546 {
1547 std::vector<uint64_t> res = off;
1548 if(!off.size())
1549 return res;
1550 std::sort(res.begin(), res.end());//just to be sure, actually it is already should be sorted
1551 for(size_t i = res.size()-1; i != 0; i--)
1552 res[i] -= res[i-1];
1553
1554 return res;
1555 }
1556 //---------------------------------------------------------------
1557 bool parse_and_validate_block_from_blob(const blobdata_ref& b_blob, block& b, crypto::hash *block_hash)
1558 {
1559 binary_archive<false> ba{epee::strspan<std::uint8_t>(b_blob)};
1560 bool r = ::serialization::serialize(ba, b);
1561 CHECK_AND_ASSERT_MES(r, false, "Failed to parse block from blob");
1562 b.invalidate_hashes();
1563 b.miner_tx.invalidate_hashes();
1564 if (block_hash)
1565 {
1566 calculate_block_hash(b, *block_hash, &b_blob);
1567 ++block_hashes_calculated_count;
1568 b.set_hash(*block_hash);
1569 }
1570 return true;
1571 }
1572 //---------------------------------------------------------------
1573 bool parse_and_validate_block_from_blob(const blobdata_ref& b_blob, block& b)
1574 {
1575 return parse_and_validate_block_from_blob(b_blob, b, NULL);
1576 }
1577 //---------------------------------------------------------------
1578 bool parse_and_validate_block_from_blob(const blobdata_ref& b_blob, block& b, crypto::hash &block_hash)
1579 {
1580 return parse_and_validate_block_from_blob(b_blob, b, &block_hash);
1581 }
1582 //---------------------------------------------------------------
1583 blobdata block_to_blob(const block& b)
1584 {
1585 return t_serializable_object_to_blob(b);
1586 }
1587 //---------------------------------------------------------------
1588 bool block_to_blob(const block& b, blobdata& b_blob)
1589 {
1590 return t_serializable_object_to_blob(b, b_blob);
1591 }
1592 //---------------------------------------------------------------
1593 blobdata tx_to_blob(const transaction& tx)
1594 {
1595 return t_serializable_object_to_blob(tx);
1596 }
1597 //---------------------------------------------------------------
1598 bool tx_to_blob(const transaction& tx, blobdata& b_blob)
1599 {
1600 return t_serializable_object_to_blob(tx, b_blob);
1601 }
1602 //---------------------------------------------------------------
1603 void get_tx_tree_hash(const std::vector<crypto::hash>& tx_hashes, crypto::hash& h)
1604 {
1605 tree_hash(tx_hashes.data(), tx_hashes.size(), h);
1606 }
1607 //---------------------------------------------------------------
1608 crypto::hash get_tx_tree_hash(const std::vector<crypto::hash>& tx_hashes)
1609 {
1610 crypto::hash h = null_hash;
1611 get_tx_tree_hash(tx_hashes, h);
1612 return h;
1613 }
1614 //---------------------------------------------------------------
1615 crypto::hash get_tx_tree_hash(const block& b)
1616 {
1617 std::vector<crypto::hash> txs_ids;
1618 txs_ids.reserve(1 + b.tx_hashes.size());
1619 crypto::hash h = null_hash;
1620 size_t bl_sz = 0;
1621 CHECK_AND_ASSERT_THROW_MES(get_transaction_hash(b.miner_tx, h, bl_sz), "Failed to calculate transaction hash");
1622 txs_ids.push_back(h);
1623 for(auto& th: b.tx_hashes)
1624 txs_ids.push_back(th);
1625 return get_tx_tree_hash(txs_ids);
1626 }
1627 //---------------------------------------------------------------
1628 bool is_valid_decomposed_amount(uint64_t amount)
1629 {
1630 const uint64_t *begin = valid_decomposed_outputs;
1631 const uint64_t *end = valid_decomposed_outputs + sizeof(valid_decomposed_outputs) / sizeof(valid_decomposed_outputs[0]);
1632 return std::binary_search(begin, end, amount);
1633 }
1634 //---------------------------------------------------------------
1635 void get_hash_stats(uint64_t &tx_hashes_calculated, uint64_t &tx_hashes_cached, uint64_t &block_hashes_calculated, uint64_t & block_hashes_cached)
1636 {
1637 tx_hashes_calculated = tx_hashes_calculated_count;
1638 tx_hashes_cached = tx_hashes_cached_count;
1639 block_hashes_calculated = block_hashes_calculated_count;
1640 block_hashes_cached = block_hashes_cached_count;
1641 }
1642 //---------------------------------------------------------------
1643 crypto::secret_key encrypt_key(crypto::secret_key key, const epee::wipeable_string &passphrase)
1644 {
1645 crypto::hash hash;
1646 crypto::cn_slow_hash(passphrase.data(), passphrase.size(), hash);
1647 sc_add((unsigned char*)key.data, (const unsigned char*)key.data, (const unsigned char*)hash.data);
1648 return key;
1649 }
1650 //---------------------------------------------------------------
1651 crypto::secret_key decrypt_key(crypto::secret_key key, const epee::wipeable_string &passphrase)
1652 {
1653 crypto::hash hash;
1654 crypto::cn_slow_hash(passphrase.data(), passphrase.size(), hash);
1655 sc_sub((unsigned char*)key.data, (const unsigned char*)key.data, (const unsigned char*)hash.data);
1656 return key;
1657 }
1658 }