Debian Codegraph @

monero/src/cryptonote_core/cryptonote_tx_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 <unordered_set>
32 #include <random>
33 #include "include_base_utils.h"
34 #include "string_tools.h"
35 using namespace epee;
36
37 #include "common/apply_permutation.h"
38 #include "cryptonote_tx_utils.h"
39 #include "cryptonote_config.h"
40 #include "blockchain.h"
41 #include "cryptonote_basic/miner.h"
42 #include "cryptonote_basic/tx_extra.h"
43 #include "crypto/crypto.h"
44 #include "crypto/hash.h"
45 #include "ringct/rctSigs.h"
46
47 using namespace crypto;
48
49 namespace cryptonote
50 {
51 //---------------------------------------------------------------
52 void classify_addresses(const std::vector<tx_destination_entry> &destinations, const boost::optional<cryptonote::account_public_address>& change_addr, size_t &num_stdaddresses, size_t &num_subaddresses, account_public_address &single_dest_subaddress)
53 {
54 num_stdaddresses = 0;
55 num_subaddresses = 0;
56 std::unordered_set<cryptonote::account_public_address> unique_dst_addresses;
57 for(const tx_destination_entry& dst_entr: destinations)
58 {
59 if (change_addr && dst_entr.addr == change_addr)
60 continue;
61 if (unique_dst_addresses.count(dst_entr.addr) == 0)
62 {
63 unique_dst_addresses.insert(dst_entr.addr);
64 if (dst_entr.is_subaddress)
65 {
66 ++num_subaddresses;
67 single_dest_subaddress = dst_entr.addr;
68 }
69 else
70 {
71 ++num_stdaddresses;
72 }
73 }
74 }
75 LOG_PRINT_L2("destinations include " << num_stdaddresses << " standard addresses and " << num_subaddresses << " subaddresses");
76 }
77 //---------------------------------------------------------------
78 bool construct_miner_tx(size_t height, size_t median_weight, uint64_t already_generated_coins, size_t current_block_weight, uint64_t fee, const account_public_address &miner_address, transaction& tx, const blobdata& extra_nonce, size_t max_outs, uint8_t hard_fork_version) {
79 tx.vin.clear();
80 tx.vout.clear();
81 tx.extra.clear();
82
83 keypair txkey = keypair::generate(hw::get_device("default"));
84 add_tx_pub_key_to_extra(tx, txkey.pub);
85 if(!extra_nonce.empty())
86 if(!add_extra_nonce_to_tx_extra(tx.extra, extra_nonce))
87 return false;
88 if (!sort_tx_extra(tx.extra, tx.extra))
89 return false;
90
91 txin_gen in;
92 in.height = height;
93
94 uint64_t block_reward;
95 if(!get_block_reward(median_weight, current_block_weight, already_generated_coins, block_reward, hard_fork_version))
96 {
97 LOG_PRINT_L0("Block is too big");
98 return false;
99 }
100
101 #if defined(DEBUG_CREATE_BLOCK_TEMPLATE)
102 LOG_PRINT_L1("Creating block template: reward " << block_reward <<
103 ", fee " << fee);
104 #endif
105 block_reward += fee;
106
107 // from hard fork 2, we cut out the low significant digits. This makes the tx smaller, and
108 // keeps the paid amount almost the same. The unpaid remainder gets pushed back to the
109 // emission schedule
110 // from hard fork 4, we use a single "dusty" output. This makes the tx even smaller,
111 // and avoids the quantization. These outputs will be added as rct outputs with identity
112 // masks, to they can be used as rct inputs.
113 if (hard_fork_version >= 2 && hard_fork_version < 4) {
114 block_reward = block_reward - block_reward % ::config::BASE_REWARD_CLAMP_THRESHOLD;
115 }
116
117 std::vector<uint64_t> out_amounts;
118 decompose_amount_into_digits(block_reward, hard_fork_version >= 2 ? 0 : ::config::DEFAULT_DUST_THRESHOLD,
119 [&out_amounts](uint64_t a_chunk) { out_amounts.push_back(a_chunk); },
120 [&out_amounts](uint64_t a_dust) { out_amounts.push_back(a_dust); });
121
122 CHECK_AND_ASSERT_MES(1 <= max_outs, false, "max_out must be non-zero");
123 if (height == 0 || hard_fork_version >= 4)
124 {
125 // the genesis block was not decomposed, for unknown reasons
126 while (max_outs < out_amounts.size())
127 {
128 //out_amounts[out_amounts.size() - 2] += out_amounts.back();
129 //out_amounts.resize(out_amounts.size() - 1);
130 out_amounts[1] += out_amounts[0];
131 for (size_t n = 1; n < out_amounts.size(); ++n)
132 out_amounts[n - 1] = out_amounts[n];
133 out_amounts.pop_back();
134 }
135 }
136 else
137 {
138 CHECK_AND_ASSERT_MES(max_outs >= out_amounts.size(), false, "max_out exceeded");
139 }
140
141 uint64_t summary_amounts = 0;
142 for (size_t no = 0; no < out_amounts.size(); no++)
143 {
144 crypto::key_derivation derivation = AUTO_VAL_INIT(derivation);
145 crypto::public_key out_eph_public_key = AUTO_VAL_INIT(out_eph_public_key);
146 bool r = crypto::generate_key_derivation(miner_address.m_view_public_key, txkey.sec, derivation);
147 CHECK_AND_ASSERT_MES(r, false, "while creating outs: failed to generate_key_derivation(" << miner_address.m_view_public_key << ", " << crypto::secret_key_explicit_print_ref{txkey.sec} << ")");
148
149 r = crypto::derive_public_key(derivation, no, miner_address.m_spend_public_key, out_eph_public_key);
150 CHECK_AND_ASSERT_MES(r, false, "while creating outs: failed to derive_public_key(" << derivation << ", " << no << ", "<< miner_address.m_spend_public_key << ")");
151
152 uint64_t amount = out_amounts[no];
153 summary_amounts += amount;
154
155 bool use_view_tags = hard_fork_version >= HF_VERSION_VIEW_TAGS;
156 crypto::view_tag view_tag;
157 if (use_view_tags)
158 crypto::derive_view_tag(derivation, no, view_tag);
159
160 tx_out out;
161 cryptonote::set_tx_out(amount, out_eph_public_key, use_view_tags, view_tag, out);
162
163 tx.vout.push_back(out);
164 }
165
166 CHECK_AND_ASSERT_MES(summary_amounts == block_reward, false, "Failed to construct miner tx, summary_amounts = " << summary_amounts << " not equal block_reward = " << block_reward);
167
168 if (hard_fork_version >= 4)
169 tx.version = 2;
170 else
171 tx.version = 1;
172
173 //lock
174 tx.unlock_time = height + CRYPTONOTE_MINED_MONEY_UNLOCK_WINDOW;
175 tx.vin.push_back(in);
176
177 tx.invalidate_hashes();
178
179 //LOG_PRINT("MINER_TX generated ok, block_reward=" << print_money(block_reward) << "(" << print_money(block_reward - fee) << "+" << print_money(fee)
180 // << "), current_block_size=" << current_block_size << ", already_generated_coins=" << already_generated_coins << ", tx_id=" << get_transaction_hash(tx), LOG_LEVEL_2);
181 return true;
182 }
183 //---------------------------------------------------------------
184 crypto::public_key get_destination_view_key_pub(const std::vector<tx_destination_entry> &destinations, const boost::optional<cryptonote::account_public_address>& change_addr)
185 {
186 account_public_address addr = {null_pkey, null_pkey};
187 size_t count = 0;
188 for (const auto &i : destinations)
189 {
190 if (i.amount == 0)
191 continue;
192 if (change_addr && i.addr == *change_addr)
193 continue;
194 if (i.addr == addr)
195 continue;
196 if (count > 0)
197 return null_pkey;
198 addr = i.addr;
199 ++count;
200 }
201 if (count == 0 && change_addr)
202 return change_addr->m_view_public_key;
203 return addr.m_view_public_key;
204 }
205 //---------------------------------------------------------------
206 bool construct_tx_with_tx_key(const account_keys& sender_account_keys, const std::unordered_map<crypto::public_key, subaddress_index>& subaddresses, std::vector<tx_source_entry>& sources, std::vector<tx_destination_entry>& destinations, const boost::optional<cryptonote::account_public_address>& change_addr, const std::vector<uint8_t> &extra, transaction& tx, const crypto::secret_key &tx_key, const std::vector<crypto::secret_key> &additional_tx_keys, bool rct, const rct::RCTConfig &rct_config, bool shuffle_outs, bool use_view_tags)
207 {
208 hw::device &hwdev = sender_account_keys.get_device();
209
210 if (sources.empty())
211 {
212 LOG_ERROR("Empty sources");
213 return false;
214 }
215
216 std::vector<rct::key> amount_keys;
217 tx.set_null();
218 amount_keys.clear();
219
220 tx.version = rct ? 2 : 1;
221 tx.unlock_time = 0;
222
223 tx.extra = extra;
224 crypto::public_key txkey_pub;
225
226 // if we have a stealth payment id, find it and encrypt it with the tx key now
227 std::vector<tx_extra_field> tx_extra_fields;
228 if (parse_tx_extra(tx.extra, tx_extra_fields))
229 {
230 bool add_dummy_payment_id = true;
231 tx_extra_nonce extra_nonce;
232 if (find_tx_extra_field_by_type(tx_extra_fields, extra_nonce))
233 {
234 crypto::hash payment_id = null_hash;
235 crypto::hash8 payment_id8 = null_hash8;
236 if (get_encrypted_payment_id_from_tx_extra_nonce(extra_nonce.nonce, payment_id8))
237 {
238 LOG_PRINT_L2("Encrypting payment id " << payment_id8);
239 crypto::public_key view_key_pub = get_destination_view_key_pub(destinations, change_addr);
240 if (view_key_pub == null_pkey)
241 {
242 LOG_ERROR("Destinations have to have exactly one output to support encrypted payment ids");
243 return false;
244 }
245
246 if (!hwdev.encrypt_payment_id(payment_id8, view_key_pub, tx_key))
247 {
248 LOG_ERROR("Failed to encrypt payment id");
249 return false;
250 }
251
252 std::string extra_nonce;
253 set_encrypted_payment_id_to_tx_extra_nonce(extra_nonce, payment_id8);
254 remove_field_from_tx_extra(tx.extra, typeid(tx_extra_nonce));
255 if (!add_extra_nonce_to_tx_extra(tx.extra, extra_nonce))
256 {
257 LOG_ERROR("Failed to add encrypted payment id to tx extra");
258 return false;
259 }
260 LOG_PRINT_L1("Encrypted payment ID: " << payment_id8);
261 add_dummy_payment_id = false;
262 }
263 else if (get_payment_id_from_tx_extra_nonce(extra_nonce.nonce, payment_id))
264 {
265 add_dummy_payment_id = false;
266 }
267 }
268
269 // we don't add one if we've got more than the usual 1 destination plus change
270 if (destinations.size() > 2)
271 add_dummy_payment_id = false;
272
273 if (add_dummy_payment_id)
274 {
275 // if we have neither long nor short payment id, add a dummy short one,
276 // this should end up being the vast majority of txes as time goes on
277 std::string extra_nonce;
278 crypto::hash8 payment_id8 = null_hash8;
279 crypto::public_key view_key_pub = get_destination_view_key_pub(destinations, change_addr);
280 if (view_key_pub == null_pkey)
281 {
282 LOG_ERROR("Failed to get key to encrypt dummy payment id with");
283 }
284 else
285 {
286 hwdev.encrypt_payment_id(payment_id8, view_key_pub, tx_key);
287 set_encrypted_payment_id_to_tx_extra_nonce(extra_nonce, payment_id8);
288 if (!add_extra_nonce_to_tx_extra(tx.extra, extra_nonce))
289 {
290 LOG_ERROR("Failed to add dummy encrypted payment id to tx extra");
291 // continue anyway
292 }
293 }
294 }
295 }
296 else
297 {
298 MWARNING("Failed to parse tx extra");
299 tx_extra_fields.clear();
300 }
301
302 struct input_generation_context_data
303 {
304 keypair in_ephemeral;
305 };
306 std::vector<input_generation_context_data> in_contexts;
307
308 uint64_t summary_inputs_money = 0;
309 //fill inputs
310 int idx = -1;
311 for(const tx_source_entry& src_entr: sources)
312 {
313 ++idx;
314 if(src_entr.real_output >= src_entr.outputs.size())
315 {
316 LOG_ERROR("real_output index (" << src_entr.real_output << ")bigger than output_keys.size()=" << src_entr.outputs.size());
317 return false;
318 }
319 summary_inputs_money += src_entr.amount;
320
321 //key_derivation recv_derivation;
322 in_contexts.push_back(input_generation_context_data());
323 keypair& in_ephemeral = in_contexts.back().in_ephemeral;
324 crypto::key_image img;
325 const auto& out_key = reinterpret_cast<const crypto::public_key&>(src_entr.outputs[src_entr.real_output].second.dest);
326 if(!generate_key_image_helper(sender_account_keys, subaddresses, out_key, src_entr.real_out_tx_key, src_entr.real_out_additional_tx_keys, src_entr.real_output_in_tx_index, in_ephemeral,img, hwdev))
327 {
328 LOG_ERROR("Key image generation failed!");
329 return false;
330 }
331
332 //check that derivated key is equal with real output key
333 if(!(in_ephemeral.pub == src_entr.outputs[src_entr.real_output].second.dest) )
334 {
335 LOG_ERROR("derived public key mismatch with output public key at index " << idx << ", real out " << src_entr.real_output << "! "<< ENDL << "derived_key:"
336 << string_tools::pod_to_hex(in_ephemeral.pub) << ENDL << "real output_public_key:"
337 << string_tools::pod_to_hex(src_entr.outputs[src_entr.real_output].second.dest) );
338 LOG_ERROR("amount " << src_entr.amount << ", rct " << src_entr.rct);
339 LOG_ERROR("tx pubkey " << src_entr.real_out_tx_key << ", real_output_in_tx_index " << src_entr.real_output_in_tx_index);
340 return false;
341 }
342
343 //put key image into tx input
344 txin_to_key input_to_key;
345 input_to_key.amount = src_entr.amount;
346 input_to_key.k_image = img;
347
348 //fill outputs array and use relative offsets
349 for(const tx_source_entry::output_entry& out_entry: src_entr.outputs)
350 input_to_key.key_offsets.push_back(out_entry.first);
351
352 input_to_key.key_offsets = absolute_output_offsets_to_relative(input_to_key.key_offsets);
353 tx.vin.push_back(input_to_key);
354 }
355
356 if (shuffle_outs)
357 {
358 std::shuffle(destinations.begin(), destinations.end(), crypto::random_device{});
359 }
360
361 // sort ins by their key image
362 std::vector<size_t> ins_order(sources.size());
363 for (size_t n = 0; n < sources.size(); ++n)
364 ins_order[n] = n;
365 std::sort(ins_order.begin(), ins_order.end(), [&](const size_t i0, const size_t i1) {
366 const txin_to_key &tk0 = boost::get<txin_to_key>(tx.vin[i0]);
367 const txin_to_key &tk1 = boost::get<txin_to_key>(tx.vin[i1]);
368 return memcmp(&tk0.k_image, &tk1.k_image, sizeof(tk0.k_image)) > 0;
369 });
370 tools::apply_permutation(ins_order, [&] (size_t i0, size_t i1) {
371 std::swap(tx.vin[i0], tx.vin[i1]);
372 std::swap(in_contexts[i0], in_contexts[i1]);
373 std::swap(sources[i0], sources[i1]);
374 });
375
376 // figure out if we need to make additional tx pubkeys
377 size_t num_stdaddresses = 0;
378 size_t num_subaddresses = 0;
379 account_public_address single_dest_subaddress;
380 classify_addresses(destinations, change_addr, num_stdaddresses, num_subaddresses, single_dest_subaddress);
381
382 // if this is a single-destination transfer to a subaddress, we set the tx pubkey to R=s*D
383 if (num_stdaddresses == 0 && num_subaddresses == 1)
384 {
385 txkey_pub = rct::rct2pk(hwdev.scalarmultKey(rct::pk2rct(single_dest_subaddress.m_spend_public_key), rct::sk2rct(tx_key)));
386 }
387 else
388 {
389 txkey_pub = rct::rct2pk(hwdev.scalarmultBase(rct::sk2rct(tx_key)));
390 }
391 remove_field_from_tx_extra(tx.extra, typeid(tx_extra_pub_key));
392 add_tx_pub_key_to_extra(tx, txkey_pub);
393
394 std::vector<crypto::public_key> additional_tx_public_keys;
395
396 // we don't need to include additional tx keys if:
397 // - all the destinations are standard addresses
398 // - there's only one destination which is a subaddress
399 bool need_additional_txkeys = num_subaddresses > 0 && (num_stdaddresses > 0 || num_subaddresses > 1);
400 if (need_additional_txkeys)
401 CHECK_AND_ASSERT_MES(destinations.size() == additional_tx_keys.size(), false, "Wrong amount of additional tx keys");
402
403 uint64_t summary_outs_money = 0;
404 //fill outputs
405 size_t output_index = 0;
406 for(const tx_destination_entry& dst_entr: destinations)
407 {
408 CHECK_AND_ASSERT_MES(dst_entr.amount > 0 || tx.version > 1, false, "Destination with wrong amount: " << dst_entr.amount);
409 crypto::public_key out_eph_public_key;
410 crypto::view_tag view_tag;
411
412 hwdev.generate_output_ephemeral_keys(tx.version,sender_account_keys, txkey_pub, tx_key,
413 dst_entr, change_addr, output_index,
414 need_additional_txkeys, additional_tx_keys,
415 additional_tx_public_keys, amount_keys, out_eph_public_key,
416 use_view_tags, view_tag);
417
418 tx_out out;
419 cryptonote::set_tx_out(dst_entr.amount, out_eph_public_key, use_view_tags, view_tag, out);
420 tx.vout.push_back(out);
421 output_index++;
422 summary_outs_money += dst_entr.amount;
423 }
424 CHECK_AND_ASSERT_MES(additional_tx_public_keys.size() == additional_tx_keys.size(), false, "Internal error creating additional public keys");
425
426 remove_field_from_tx_extra(tx.extra, typeid(tx_extra_additional_pub_keys));
427
428 LOG_PRINT_L2("tx pubkey: " << txkey_pub);
429 if (need_additional_txkeys)
430 {
431 LOG_PRINT_L2("additional tx pubkeys: ");
432 for (size_t i = 0; i < additional_tx_public_keys.size(); ++i)
433 LOG_PRINT_L2(additional_tx_public_keys[i]);
434 add_additional_tx_pub_keys_to_extra(tx.extra, additional_tx_public_keys);
435 }
436
437 if (!sort_tx_extra(tx.extra, tx.extra))
438 return false;
439
440 CHECK_AND_ASSERT_MES(tx.extra.size() <= MAX_TX_EXTRA_SIZE, false, "TX extra size (" << tx.extra.size() << ") is greater than max allowed (" << MAX_TX_EXTRA_SIZE << ")");
441
442 //check money
443 if(summary_outs_money > summary_inputs_money )
444 {
445 LOG_ERROR("Transaction inputs money ("<< summary_inputs_money << ") less than outputs money (" << summary_outs_money << ")");
446 return false;
447 }
448
449 // check for watch only wallet
450 bool zero_secret_key = true;
451 for (size_t i = 0; i < sizeof(sender_account_keys.m_spend_secret_key); ++i)
452 zero_secret_key &= (sender_account_keys.m_spend_secret_key.data[i] == 0);
453 if (zero_secret_key)
454 {
455 MDEBUG("Null secret key, skipping signatures");
456 }
457
458 if (tx.version == 1)
459 {
460 //generate ring signatures
461 crypto::hash tx_prefix_hash;
462 get_transaction_prefix_hash(tx, tx_prefix_hash);
463
464 std::stringstream ss_ring_s;
465 size_t i = 0;
466 for(const tx_source_entry& src_entr: sources)
467 {
468 ss_ring_s << "pub_keys:" << ENDL;
469 std::vector<const crypto::public_key*> keys_ptrs;
470 std::vector<crypto::public_key> keys(src_entr.outputs.size());
471 size_t ii = 0;
472 for(const tx_source_entry::output_entry& o: src_entr.outputs)
473 {
474 keys[ii] = rct2pk(o.second.dest);
475 keys_ptrs.push_back(&keys[ii]);
476 ss_ring_s << o.second.dest << ENDL;
477 ++ii;
478 }
479
480 tx.signatures.push_back(std::vector<crypto::signature>());
481 std::vector<crypto::signature>& sigs = tx.signatures.back();
482 sigs.resize(src_entr.outputs.size());
483 if (!zero_secret_key)
484 crypto::generate_ring_signature(tx_prefix_hash, boost::get<txin_to_key>(tx.vin[i]).k_image, keys_ptrs, in_contexts[i].in_ephemeral.sec, src_entr.real_output, sigs.data());
485 ss_ring_s << "signatures:" << ENDL;
486 std::for_each(sigs.begin(), sigs.end(), [&](const crypto::signature& s){ss_ring_s << s << ENDL;});
487 ss_ring_s << "prefix_hash:" << tx_prefix_hash << ENDL << "in_ephemeral_key: " << crypto::secret_key_explicit_print_ref{in_contexts[i].in_ephemeral.sec} << ENDL << "real_output: " << src_entr.real_output << ENDL;
488 i++;
489 }
490
491 MCINFO("construct_tx", "transaction_created: " << get_transaction_hash(tx) << ENDL << obj_to_json_str(tx) << ENDL << ss_ring_s.str());
492 }
493 else
494 {
495 size_t n_total_outs = sources[0].outputs.size(); // only for non-simple rct
496
497 // the non-simple version is slightly smaller, but assumes all real inputs
498 // are on the same index, so can only be used if there just one ring.
499 bool use_simple_rct = sources.size() > 1 || rct_config.range_proof_type != rct::RangeProofBorromean;
500
501 if (!use_simple_rct)
502 {
503 // non simple ringct requires all real inputs to be at the same index for all inputs
504 for(const tx_source_entry& src_entr: sources)
505 {
506 if(src_entr.real_output != sources.begin()->real_output)
507 {
508 LOG_ERROR("All inputs must have the same index for non-simple ringct");
509 return false;
510 }
511 }
512
513 // enforce same mixin for all outputs
514 for (size_t i = 1; i < sources.size(); ++i) {
515 if (n_total_outs != sources[i].outputs.size()) {
516 LOG_ERROR("Non-simple ringct transaction has varying ring size");
517 return false;
518 }
519 }
520 }
521
522 uint64_t amount_in = 0, amount_out = 0;
523 rct::ctkeyV inSk;
524 inSk.reserve(sources.size());
525 // mixRing indexing is done the other way round for simple
526 rct::ctkeyM mixRing(use_simple_rct ? sources.size() : n_total_outs);
527 rct::keyV destinations;
528 std::vector<uint64_t> inamounts, outamounts;
529 std::vector<unsigned int> index;
530 for (size_t i = 0; i < sources.size(); ++i)
531 {
532 rct::ctkey ctkey;
533 amount_in += sources[i].amount;
534 inamounts.push_back(sources[i].amount);
535 index.push_back(sources[i].real_output);
536 // inSk: (secret key, mask)
537 ctkey.dest = rct::sk2rct(in_contexts[i].in_ephemeral.sec);
538 ctkey.mask = sources[i].mask;
539 inSk.push_back(ctkey);
540 memwipe(&ctkey, sizeof(rct::ctkey));
541 // inPk: (public key, commitment)
542 // will be done when filling in mixRing
543 }
544 for (size_t i = 0; i < tx.vout.size(); ++i)
545 {
546 crypto::public_key output_public_key;
547 get_output_public_key(tx.vout[i], output_public_key);
548 destinations.push_back(rct::pk2rct(output_public_key));
549 outamounts.push_back(tx.vout[i].amount);
550 amount_out += tx.vout[i].amount;
551 }
552
553 if (use_simple_rct)
554 {
555 // mixRing indexing is done the other way round for simple
556 for (size_t i = 0; i < sources.size(); ++i)
557 {
558 mixRing[i].resize(sources[i].outputs.size());
559 for (size_t n = 0; n < sources[i].outputs.size(); ++n)
560 {
561 mixRing[i][n] = sources[i].outputs[n].second;
562 }
563 }
564 }
565 else
566 {
567 for (size_t i = 0; i < n_total_outs; ++i) // same index assumption
568 {
569 mixRing[i].resize(sources.size());
570 for (size_t n = 0; n < sources.size(); ++n)
571 {
572 mixRing[i][n] = sources[n].outputs[i].second;
573 }
574 }
575 }
576
577 // fee
578 if (!use_simple_rct && amount_in > amount_out)
579 outamounts.push_back(amount_in - amount_out);
580
581 // zero out all amounts to mask rct outputs, real amounts are now encrypted
582 for (size_t i = 0; i < tx.vin.size(); ++i)
583 {
584 if (sources[i].rct)
585 boost::get<txin_to_key>(tx.vin[i]).amount = 0;
586 }
587 for (size_t i = 0; i < tx.vout.size(); ++i)
588 tx.vout[i].amount = 0;
589
590 crypto::hash tx_prefix_hash;
591 get_transaction_prefix_hash(tx, tx_prefix_hash, hwdev);
592 rct::ctkeyV outSk;
593 if (use_simple_rct)
594 tx.rct_signatures = rct::genRctSimple(rct::hash2rct(tx_prefix_hash), inSk, destinations, inamounts, outamounts, amount_in - amount_out, mixRing, amount_keys, index, outSk, rct_config, hwdev);
595 else
596 tx.rct_signatures = rct::genRct(rct::hash2rct(tx_prefix_hash), inSk, destinations, outamounts, mixRing, amount_keys, sources[0].real_output, outSk, rct_config, hwdev); // same index assumption
597 memwipe(inSk.data(), inSk.size() * sizeof(rct::ctkey));
598
599 CHECK_AND_ASSERT_MES(tx.vout.size() == outSk.size(), false, "outSk size does not match vout");
600
601 MCINFO("construct_tx", "transaction_created: " << get_transaction_hash(tx) << ENDL << obj_to_json_str(tx) << ENDL);
602 }
603
604 tx.invalidate_hashes();
605
606 return true;
607 }
608 //---------------------------------------------------------------
609 bool construct_tx_and_get_tx_key(const account_keys& sender_account_keys, const std::unordered_map<crypto::public_key, subaddress_index>& subaddresses, std::vector<tx_source_entry>& sources, std::vector<tx_destination_entry>& destinations, const boost::optional<cryptonote::account_public_address>& change_addr, const std::vector<uint8_t> &extra, transaction& tx, crypto::secret_key &tx_key, std::vector<crypto::secret_key> &additional_tx_keys, bool rct, const rct::RCTConfig &rct_config, bool use_view_tags)
610 {
611 hw::device &hwdev = sender_account_keys.get_device();
612 hwdev.open_tx(tx_key);
613 try {
614 // figure out if we need to make additional tx pubkeys
615 size_t num_stdaddresses = 0;
616 size_t num_subaddresses = 0;
617 account_public_address single_dest_subaddress;
618 classify_addresses(destinations, change_addr, num_stdaddresses, num_subaddresses, single_dest_subaddress);
619 bool need_additional_txkeys = num_subaddresses > 0 && (num_stdaddresses > 0 || num_subaddresses > 1);
620 if (need_additional_txkeys)
621 {
622 additional_tx_keys.clear();
623 for (size_t i = 0; i < destinations.size(); ++i)
624 {
625 additional_tx_keys.push_back(keypair::generate(sender_account_keys.get_device()).sec);
626 }
627 }
628
629 bool shuffle_outs = true;
630 bool r = construct_tx_with_tx_key(sender_account_keys, subaddresses, sources, destinations, change_addr, extra, tx, tx_key, additional_tx_keys, rct, rct_config, shuffle_outs, use_view_tags);
631 hwdev.close_tx();
632 return r;
633 } catch(...) {
634 hwdev.close_tx();
635 throw;
636 }
637 }
638 //---------------------------------------------------------------
639 bool construct_tx(const account_keys& sender_account_keys, std::vector<tx_source_entry>& sources, const std::vector<tx_destination_entry>& destinations, const boost::optional<cryptonote::account_public_address>& change_addr, const std::vector<uint8_t> &extra, transaction& tx)
640 {
641 std::unordered_map<crypto::public_key, cryptonote::subaddress_index> subaddresses;
642 subaddresses[sender_account_keys.m_account_address.m_spend_public_key] = {0,0};
643 crypto::secret_key tx_key;
644 std::vector<crypto::secret_key> additional_tx_keys;
645 std::vector<tx_destination_entry> destinations_copy = destinations;
646 return construct_tx_and_get_tx_key(sender_account_keys, subaddresses, sources, destinations_copy, change_addr, extra, tx, tx_key, additional_tx_keys, false, { rct::RangeProofBorromean, 0});
647 }
648 //---------------------------------------------------------------
649 bool generate_genesis_block(
650 block& bl
651 , std::string const & genesis_tx
652 , uint32_t nonce
653 )
654 {
655 //genesis block
656 bl = {};
657
658 blobdata tx_bl;
659 bool r = string_tools::parse_hexstr_to_binbuff(genesis_tx, tx_bl);
660 CHECK_AND_ASSERT_MES(r, false, "failed to parse coinbase tx from hard coded blob");
661 r = parse_and_validate_tx_from_blob(tx_bl, bl.miner_tx);
662 CHECK_AND_ASSERT_MES(r, false, "failed to parse coinbase tx from hard coded blob");
663 bl.major_version = CURRENT_BLOCK_MAJOR_VERSION;
664 bl.minor_version = CURRENT_BLOCK_MINOR_VERSION;
665 bl.timestamp = 0;
666 bl.nonce = nonce;
667 difficulty_type diffic = 1;
668 uint64_t height = 0;
669 crypto::hash *seed_hash = NULL;
670
671 for(; bl.nonce != std::numeric_limits<uint32_t>::max(); bl.nonce++) {
672 crypto::hash h;
673 blobdata bd = get_block_hashing_blob(bl);
674 crypto::cn_slow_hash(bd.data(), bd.size(), h, 0, height);
675
676 if(check_hash(h, diffic))
677 {
678 bl.invalidate_hashes();
679 break;
680 }
681 }
682
683 bl.invalidate_hashes();
684 return true;
685 }
686
687 #ifndef BUILD_GUI_DEPS
688 //---------------------------------------------------------------
689 void get_altblock_longhash(const block& b, crypto::hash& res, const crypto::hash& seed_hash)
690 {
691 blobdata bd = get_block_hashing_blob(b);
692 rx_slow_hash(seed_hash.data, bd.data(), bd.size(), res.data);
693 }
694
695 bool get_block_longhash(const Blockchain *pbc, const blobdata& bd, crypto::hash& res, const uint64_t height, const int major_version, const crypto::hash *seed_hash, const int miners)
696 {
697 // block 202612 bug workaround
698 if (height == 202612)
699 {
700 static const std::string longhash_202612 = "84f64766475d51837ac9efbef1926486e58563c95a19fef4aec3254f03000000";
701 epee::string_tools::hex_to_pod(longhash_202612, res);
702 return true;
703 }
704 if (major_version >= RX_BLOCK_VERSION)
705 {
706 crypto::hash hash;
707 if (pbc != NULL)
708 {
709 const uint64_t seed_height = rx_seedheight(height);
710 hash = seed_hash ? *seed_hash : pbc->get_pending_block_id_by_height(seed_height);
711 } else
712 {
713 memset(&hash, 0, sizeof(hash)); // only happens when generating genesis block
714 }
715 rx_slow_hash(hash.data, bd.data(), bd.size(), res.data);
716 } else {
717 const int pow_variant = major_version >= 7 ? major_version - 6 : 0;
718 crypto::cn_slow_hash(bd.data(), bd.size(), res, pow_variant, height);
719 }
720 return true;
721 }
722
723 bool get_block_longhash(const Blockchain *pbc, const block& b, crypto::hash& res, const uint64_t height, const crypto::hash *seed_hash, const int miners)
724 {
725 blobdata bd = get_block_hashing_blob(b);
726 return get_block_longhash(pbc, bd, res, height, b.major_version, seed_hash, miners);
727 }
728
729 crypto::hash get_block_longhash(const Blockchain *pbc, const block& b, const uint64_t height, const crypto::hash *seed_hash, const int miners)
730 {
731 crypto::hash p = crypto::null_hash;
732 get_block_longhash(pbc, b, p, height, seed_hash, miners);
733 return p;
734 }
735 #endif
736 }