Debian Codegraph @

src/wallet/message_store.cpp

raw symbols SCIP
1 // Copyright (c) 2018-2022, The Monero Project
2
3 //
4 // All rights reserved.
5 //
6 // Redistribution and use in source and binary forms, with or without modification, are
7 // permitted provided that the following conditions are met:
8 //
9 // 1. Redistributions of source code must retain the above copyright notice, this list of
10 // conditions and the following disclaimer.
11 //
12 // 2. Redistributions in binary form must reproduce the above copyright notice, this list
13 // of conditions and the following disclaimer in the documentation and/or other
14 // materials provided with the distribution.
15 //
16 // 3. Neither the name of the copyright holder nor the names of its contributors may be
17 // used to endorse or promote products derived from this software without specific
18 // prior written permission.
19 //
20 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
21 // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
22 // MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
23 // THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
24 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
25 // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
26 // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
27 // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
28 // THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29
30 #include "message_store.h"
31 #include <boost/archive/portable_binary_iarchive.hpp>
32 #include <boost/format.hpp>
33 #include <boost/algorithm/string.hpp>
34 #include <boost/system/error_code.hpp>
35 #include <boost/filesystem.hpp>
36 #include <fstream>
37 #include <sstream>
38 #include "file_io_utils.h"
39 #include "storages/http_abstract_invoke.h"
40 #include "wallet_errors.h"
41 #include "serialization/binary_utils.h"
42 #include "common/base58.h"
43 #include "common/util.h"
44 #include "common/utf8.h"
45 #include "string_tools.h"
46
47
48 #undef MONERO_DEFAULT_LOG_CATEGORY
49 #define MONERO_DEFAULT_LOG_CATEGORY "wallet.mms"
50
51 namespace mms
52 {
53
54 message_store::message_store(std::unique_ptr<epee::net_utils::http::abstract_http_client> http_client) : m_transporter(std::move(http_client))
55 {
56 m_active = false;
57 m_auto_send = false;
58 m_next_message_id = 1;
59 m_num_authorized_signers = 0;
60 m_num_required_signers = 0;
61 m_nettype = cryptonote::network_type::UNDEFINED;
62 m_run = true;
63 }
64
65 namespace
66 {
67 // MMS options handling mirrors what "wallet2" is doing for its options, on-demand init and all
68 // It's not very clean to initialize Bitmessage-specific options here, but going one level further
69 // down still into "message_transporter" for that is a little bit too much
70 struct options
71 {
72 const command_line::arg_descriptor<std::string> bitmessage_address = {"bitmessage-address", mms::message_store::tr("Use PyBitmessage instance at URL <arg>"), "http://localhost:8442/"};
73 const command_line::arg_descriptor<std::string> bitmessage_login = {"bitmessage-login", mms::message_store::tr("Specify <arg> as username:password for PyBitmessage API"), "username:password"};
74 };
75 }
76
77 void message_store::init_options(boost::program_options::options_description& desc_params)
78 {
79 const options opts{};
80 command_line::add_arg(desc_params, opts.bitmessage_address);
81 command_line::add_arg(desc_params, opts.bitmessage_login);
82 }
83
84 void message_store::init(const multisig_wallet_state &state, const std::string &own_label,
85 const std::string &own_transport_address, uint32_t num_authorized_signers, uint32_t num_required_signers)
86 {
87 m_num_authorized_signers = num_authorized_signers;
88 m_num_required_signers = num_required_signers;
89 m_signers.clear();
90 m_messages.clear();
91 m_next_message_id = 1;
92
93 // The vector "m_signers" gets here once the required number of elements, one for each authorized signer,
94 // and is never changed again. The rest of the code relies on "size(m_signers) == m_num_authorized_signers"
95 // without further checks.
96 authorized_signer signer;
97 for (uint32_t i = 0; i < m_num_authorized_signers; ++i)
98 {
99 signer.me = signer.index == 0; // Strict convention: The very first signer is fixed as / must be "me"
100 m_signers.push_back(signer);
101 signer.index++;
102 }
103
104 set_signer(state, 0, own_label, own_transport_address, state.address);
105
106 m_nettype = state.nettype;
107 set_active(true);
108 m_filename = state.mms_file;
109 save(state);
110 }
111
112 void message_store::set_options(const boost::program_options::variables_map& vm)
113 {
114 const options opts{};
115 std::string bitmessage_address = command_line::get_arg(vm, opts.bitmessage_address);
116 epee::wipeable_string bitmessage_login = command_line::get_arg(vm, opts.bitmessage_login);
117 set_options(bitmessage_address, bitmessage_login);
118 }
119
120 void message_store::set_options(const std::string &bitmessage_address, const epee::wipeable_string &bitmessage_login)
121 {
122 m_transporter.set_options(bitmessage_address, bitmessage_login);
123 }
124
125 void message_store::set_signer(const multisig_wallet_state &state,
126 uint32_t index,
127 const boost::optional<std::string> &label,
128 const boost::optional<std::string> &transport_address,
129 const boost::optional<cryptonote::account_public_address> monero_address)
130 {
131 THROW_WALLET_EXCEPTION_IF(index >= m_num_authorized_signers, tools::error::wallet_internal_error, "Invalid signer index " + std::to_string(index));
132 authorized_signer &m = m_signers[index];
133 if (label)
134 {
135 m.label = get_sanitized_text(label.get(), 50);
136 }
137 if (transport_address)
138 {
139 m.transport_address = get_sanitized_text(transport_address.get(), 200);
140 }
141 if (monero_address)
142 {
143 m.monero_address_known = true;
144 m.monero_address = monero_address.get();
145 }
146 // Save to minimize the chance to loose that info
147 save(state);
148 }
149
150 const authorized_signer &message_store::get_signer(uint32_t index) const
151 {
152 THROW_WALLET_EXCEPTION_IF(index >= m_num_authorized_signers, tools::error::wallet_internal_error, "Invalid signer index " + std::to_string(index));
153 return m_signers[index];
154 }
155
156 bool message_store::signer_config_complete() const
157 {
158 for (uint32_t i = 0; i < m_num_authorized_signers; ++i)
159 {
160 const authorized_signer &m = m_signers[i];
161 if (m.label.empty() || m.transport_address.empty() || !m.monero_address_known)
162 {
163 return false;
164 }
165 }
166 return true;
167 }
168
169 // Check if all signers have a label set (as it's a requirement for starting auto-config
170 // by the "manager")
171 bool message_store::signer_labels_complete() const
172 {
173 for (uint32_t i = 0; i < m_num_authorized_signers; ++i)
174 {
175 const authorized_signer &m = m_signers[i];
176 if (m.label.empty())
177 {
178 return false;
179 }
180 }
181 return true;
182 }
183
184 void message_store::get_signer_config(std::string &signer_config)
185 {
186 std::stringstream oss;
187 binary_archive<true> ar(oss);
188 THROW_WALLET_EXCEPTION_IF(!::serialization::serialize(ar, m_signers), tools::error::wallet_internal_error, "Failed to serialize signer config");
189 signer_config = oss.str();
190 }
191
192 void message_store::unpack_signer_config(const multisig_wallet_state &state, const std::string &signer_config,
193 std::vector<authorized_signer> &signers)
194 {
195 try
196 {
197 binary_archive<false> ar{epee::strspan<std::uint8_t>(signer_config)};
198 THROW_WALLET_EXCEPTION_IF(!::serialization::serialize(ar, signers), tools::error::wallet_internal_error, "Failed to serialize signer config");
199 }
200 catch (...)
201 {
202 THROW_WALLET_EXCEPTION_IF(true, tools::error::wallet_internal_error, "Invalid structure of signer config");
203 }
204 uint32_t num_signers = (uint32_t)signers.size();
205 THROW_WALLET_EXCEPTION_IF(num_signers != m_num_authorized_signers, tools::error::wallet_internal_error, "Wrong number of signers in config: " + std::to_string(num_signers));
206 for (uint32_t i = 0; i < num_signers; ++i)
207 {
208 authorized_signer &m = signers[i];
209 m.label = get_sanitized_text(m.label, 50);
210 m.transport_address = get_sanitized_text(m.transport_address, 200);
211 m.auto_config_token = get_sanitized_text(m.auto_config_token, 20);
212 }
213 }
214
215 void message_store::process_signer_config(const multisig_wallet_state &state, const std::string &signer_config)
216 {
217 // The signers in "signer_config" and the resident wallet signers are matched not by label, but
218 // by Monero address, and ALL labels will be set from "signer_config", even the "me" label.
219 // In the auto-config process as implemented now the auto-config manager is responsible for defining
220 // the labels, and right at the end of the process ALL wallets use the SAME labels. The idea behind this
221 // is preventing problems like duplicate labels and confusion (Bob choosing a label "IamAliceHonest").
222 // (Of course signers are free to re-define any labels they don't like AFTER auto-config.)
223 //
224 // Usually this method will be called with only the "me" signer defined in the wallet, and may
225 // produce unexpected behaviour if that wallet contains additional signers that have nothing to do with
226 // those arriving in "signer_config".
227 std::vector<authorized_signer> signers;
228 unpack_signer_config(state, signer_config, signers);
229
230 uint32_t new_index = 1;
231 for (uint32_t i = 0; i < m_num_authorized_signers; ++i)
232 {
233 const authorized_signer &m = signers[i];
234 uint32_t index;
235 uint32_t take_index;
236 bool found = get_signer_index_by_monero_address(m.monero_address, index);
237 if (found)
238 {
239 // Redefine existing (probably "me", under usual circumstances)
240 take_index = index;
241 }
242 else
243 {
244 // Add new; neglect that we may erroneously overwrite already defined signers
245 // (but protect "me")
246 take_index = new_index;
247 if ((new_index + 1) < m_num_authorized_signers)
248 {
249 new_index++;
250 }
251 }
252 authorized_signer &modify = m_signers[take_index];
253 modify.label = get_sanitized_text(m.label, 50); // ALWAYS set label, see comments above
254 if (!modify.me)
255 {
256 modify.transport_address = get_sanitized_text(m.transport_address, 200);
257 modify.monero_address_known = m.monero_address_known;
258 if (m.monero_address_known)
259 {
260 modify.monero_address = m.monero_address;
261 }
262 }
263 }
264 save(state);
265 }
266
267 void message_store::start_auto_config(const multisig_wallet_state &state)
268 {
269 for (uint32_t i = 0; i < m_num_authorized_signers; ++i)
270 {
271 authorized_signer &m = m_signers[i];
272 if (!m.me)
273 {
274 setup_signer_for_auto_config(i, create_auto_config_token(), true);
275 }
276 m.auto_config_running = true;
277 }
278 save(state);
279 }
280
281 // Check auto-config token string and convert to standardized form;
282 // Try to make it as foolproof as possible, with built-in tolerance to make up for
283 // errors in transmission that still leave the token recognizable.
284 bool message_store::check_auto_config_token(const std::string &raw_token,
285 std::string &adjusted_token) const
286 {
287 std::string prefix(AUTO_CONFIG_TOKEN_PREFIX);
288 uint32_t num_hex_digits = (AUTO_CONFIG_TOKEN_BYTES + 1) * 2;
289 uint32_t full_length = num_hex_digits + prefix.length();
290 uint32_t raw_length = raw_token.length();
291 std::string hex_digits;
292
293 if (raw_length == full_length)
294 {
295 // Prefix must be there; accept it in any casing
296 std::string raw_prefix(raw_token.substr(0, 3));
297 boost::algorithm::to_lower(raw_prefix);
298 if (raw_prefix != prefix)
299 {
300 return false;
301 }
302 hex_digits = raw_token.substr(3);
303 }
304 else if (raw_length == num_hex_digits)
305 {
306 // Accept the token without the prefix if it's otherwise ok
307 hex_digits = raw_token;
308 }
309 else
310 {
311 return false;
312 }
313
314 // Convert to strict lowercase and correct any common misspellings
315 boost::algorithm::to_lower(hex_digits);
316 std::replace(hex_digits.begin(), hex_digits.end(), 'o', '0');
317 std::replace(hex_digits.begin(), hex_digits.end(), 'i', '1');
318 std::replace(hex_digits.begin(), hex_digits.end(), 'l', '1');
319
320 // Now it must be correct hex with correct checksum, no further tolerance possible
321 std::string token_bytes;
322 if (!epee::string_tools::parse_hexstr_to_binbuff(hex_digits, token_bytes))
323 {
324 return false;
325 }
326 const crypto::hash &hash = crypto::cn_fast_hash(token_bytes.data(), token_bytes.size() - 1);
327 if (token_bytes[AUTO_CONFIG_TOKEN_BYTES] != hash.data[0])
328 {
329 return false;
330 }
331 adjusted_token = prefix + hex_digits;
332 return true;
333 }
334
335 // Create a new auto-config token with prefix, random 8-hex digits plus 2 checksum digits
336 std::string message_store::create_auto_config_token()
337 {
338 unsigned char random[AUTO_CONFIG_TOKEN_BYTES];
339 crypto::rand(AUTO_CONFIG_TOKEN_BYTES, random);
340 std::string token_bytes;
341 token_bytes.append((char *)random, AUTO_CONFIG_TOKEN_BYTES);
342
343 // Add a checksum because technically ANY four bytes are a valid token, and without a checksum we would send
344 // auto-config messages "to nowhere" after the slightest typo without knowing it
345 const crypto::hash &hash = crypto::cn_fast_hash(token_bytes.data(), token_bytes.size());
346 token_bytes += hash.data[0];
347 std::string prefix(AUTO_CONFIG_TOKEN_PREFIX);
348 return prefix + epee::string_tools::buff_to_hex_nodelimer(token_bytes);
349 }
350
351 // Add a message for sending "me" address data to the auto-config transport address
352 // that can be derived from the token and activate auto-config
353 size_t message_store::add_auto_config_data_message(const multisig_wallet_state &state,
354 const std::string &auto_config_token)
355 {
356 authorized_signer &me = m_signers[0];
357 me.auto_config_token = auto_config_token;
358 setup_signer_for_auto_config(0, auto_config_token, false);
359 me.auto_config_running = true;
360
361 auto_config_data data;
362 data.label = me.label;
363 data.transport_address = me.transport_address;
364 data.monero_address = me.monero_address;
365
366 std::stringstream oss;
367 binary_archive<true> ar(oss);
368 THROW_WALLET_EXCEPTION_IF(!::serialization::serialize(ar, data), tools::error::wallet_internal_error, "Failed to serialize auto config data");
369
370 return add_message(state, 0, message_type::auto_config_data, message_direction::out, oss.str());
371 }
372
373 // Process a single message with auto-config data, destined for "message.signer_index"
374 void message_store::process_auto_config_data_message(uint32_t id)
375 {
376 // "auto_config_data" contains the label that the auto-config data sender uses for "me", but that's
377 // more for completeness' sake, and right now it's not used. In general, the auto-config manager
378 // decides/defines the labels, and right after completing auto-config ALL wallets use the SAME labels.
379
380 const message &m = get_message_ref_by_id(id);
381
382 auto_config_data data;
383 try
384 {
385 binary_archive<false> ar{epee::strspan<std::uint8_t>(m.content)};
386 THROW_WALLET_EXCEPTION_IF(!::serialization::serialize(ar, data), tools::error::wallet_internal_error, "Failed to serialize auto config data");
387 }
388 catch (...)
389 {
390 THROW_WALLET_EXCEPTION_IF(true, tools::error::wallet_internal_error, "Invalid structure of auto config data");
391 }
392
393 authorized_signer &signer = m_signers[m.signer_index];
394 // "signer.label" does NOT change, see comment above
395 signer.transport_address = data.transport_address;
396 signer.monero_address_known = true;
397 signer.monero_address = data.monero_address;
398 signer.auto_config_running = false;
399 }
400
401 void add_hash(crypto::hash &sum, const crypto::hash &summand)
402 {
403 for (uint32_t i = 0; i < crypto::HASH_SIZE; ++i)
404 {
405 uint32_t x = (uint32_t)sum.data[i];
406 uint32_t y = (uint32_t)summand.data[i];
407 sum.data[i] = (char)((x + y) % 256);
408 }
409 }
410
411 // Calculate a checksum that allows signers to make sure they work with an identical signer config
412 // by exchanging and comparing checksums out-of-band i.e. not using the MMS;
413 // Because different signers have a different order of signers in the config work with "adding"
414 // individual hashes because that operation is commutative
415 std::string message_store::get_config_checksum() const
416 {
417 crypto::hash sum = crypto::null_hash;
418 uint32_t num = SWAP32LE(m_num_authorized_signers);
419 add_hash(sum, crypto::cn_fast_hash(&num, sizeof(num)));
420 num = SWAP32LE(m_num_required_signers);
421 add_hash(sum, crypto::cn_fast_hash(&num, sizeof(num)));
422 for (uint32_t i = 0; i < m_num_authorized_signers; ++i)
423 {
424 const authorized_signer &m = m_signers[i];
425 add_hash(sum, crypto::cn_fast_hash(m.transport_address.data(), m.transport_address.size()));
426 if (m.monero_address_known)
427 {
428 add_hash(sum, crypto::cn_fast_hash(&m.monero_address.m_spend_public_key, sizeof(m.monero_address.m_spend_public_key)));
429 add_hash(sum, crypto::cn_fast_hash(&m.monero_address.m_view_public_key, sizeof(m.monero_address.m_view_public_key)));
430 }
431 }
432 std::string checksum_bytes;
433 checksum_bytes += sum.data[0];
434 checksum_bytes += sum.data[1];
435 checksum_bytes += sum.data[2];
436 checksum_bytes += sum.data[3];
437 return epee::string_tools::buff_to_hex_nodelimer(checksum_bytes);
438 }
439
440 void message_store::stop_auto_config()
441 {
442 for (uint32_t i = 0; i < m_num_authorized_signers; ++i)
443 {
444 authorized_signer &m = m_signers[i];
445 if (!m.auto_config_transport_address.empty())
446 {
447 // Try to delete the chan that was used for auto-config
448 m_transporter.delete_transport_address(m.auto_config_transport_address);
449 }
450 m.auto_config_token.clear();
451 m.auto_config_public_key = crypto::null_pkey;
452 m.auto_config_secret_key = crypto::null_skey;
453 m.auto_config_transport_address.clear();
454 m.auto_config_running = false;
455 }
456 }
457
458 void message_store::setup_signer_for_auto_config(uint32_t index, const std::string token, bool receiving)
459 {
460 // It may be a little strange to hash the textual hex digits of the auto config token into
461 // 32 bytes and turn that into a Monero public/secret key pair, instead of doing something
462 // much less complicated like directly using the underlying random 40 bits as key for a
463 // symmetric cipher, but everything is there already for encrypting and decrypting messages
464 // with such key pairs, and furthermore it would be trivial to use tokens with a different
465 // number of bytes.
466 //
467 // In the wallet of the auto-config manager each signer except "me" gets set its own
468 // auto-config parameters. In the wallet of somebody using the token to send auto-config
469 // data the auto-config parameters are stored in the "me" signer and taken from there
470 // to send that data.
471 THROW_WALLET_EXCEPTION_IF(index >= m_num_authorized_signers, tools::error::wallet_internal_error, "Invalid signer index " + std::to_string(index));
472 authorized_signer &m = m_signers[index];
473 m.auto_config_token = token;
474 crypto::hash_to_scalar(token.data(), token.size(), m.auto_config_secret_key);
475 crypto::secret_key_to_public_key(m.auto_config_secret_key, m.auto_config_public_key);
476 m.auto_config_transport_address = m_transporter.derive_transport_address(m.auto_config_token);
477 }
478
479 bool message_store::get_signer_index_by_monero_address(const cryptonote::account_public_address &monero_address, uint32_t &index) const
480 {
481 for (uint32_t i = 0; i < m_num_authorized_signers; ++i)
482 {
483 const authorized_signer &m = m_signers[i];
484 if (m.monero_address == monero_address)
485 {
486 index = m.index;
487 return true;
488 }
489 }
490 MWARNING("No authorized signer with Monero address " << account_address_to_string(monero_address));
491 return false;
492 }
493
494 bool message_store::get_signer_index_by_label(const std::string label, uint32_t &index) const
495 {
496 for (uint32_t i = 0; i < m_num_authorized_signers; ++i)
497 {
498 const authorized_signer &m = m_signers[i];
499 if (m.label == label)
500 {
501 index = m.index;
502 return true;
503 }
504 }
505 MWARNING("No authorized signer with label " << label);
506 return false;
507 }
508
509 void message_store::process_wallet_created_data(const multisig_wallet_state &state, message_type type, const std::string &content)
510 {
511 switch(type)
512 {
513 case message_type::key_set:
514 // Result of a "prepare_multisig" command in the wallet
515 // Send the key set to all other signers
516 case message_type::additional_key_set:
517 // Result of a "make_multisig" command or a "exchange_multisig_keys" in the wallet in case of M/N multisig
518 // Send the additional key set to all other signers
519 case message_type::multisig_sync_data:
520 // Result of a "export_multisig_info" command in the wallet
521 // Send the sync data to all other signers
522 for (uint32_t i = 1; i < m_num_authorized_signers; ++i)
523 {
524 add_message(state, i, type, message_direction::out, content);
525 }
526 break;
527
528 case message_type::partially_signed_tx:
529 // Result of a "transfer" command in the wallet, or a "sign_multisig" command
530 // that did not yet result in the minimum number of signatures required
531 // Create a message "from me to me" as a container for the tx data
532 if (m_num_required_signers == 1)
533 {
534 // Probably rare, but possible: The 1 signature is already enough, correct the type
535 // Easier to correct here than asking all callers to detect this rare special case
536 type = message_type::fully_signed_tx;
537 }
538 add_message(state, 0, type, message_direction::in, content);
539 break;
540
541 case message_type::fully_signed_tx:
542 add_message(state, 0, type, message_direction::in, content);
543 break;
544
545 default:
546 THROW_WALLET_EXCEPTION(tools::error::wallet_internal_error, "Illegal message type " + std::to_string((uint32_t)type));
547 break;
548 }
549 }
550
551 size_t message_store::add_message(const multisig_wallet_state &state,
552 uint32_t signer_index, message_type type, message_direction direction,
553 const std::string &content)
554 {
555 message m;
556 m.id = m_next_message_id++;
557 m.type = type;
558 m.direction = direction;
559 m.content = content;
560 m.created = (uint64_t)time(NULL);
561 m.modified = m.created;
562 m.sent = 0;
563 m.signer_index = signer_index;
564 if (direction == message_direction::out)
565 {
566 m.state = message_state::ready_to_send;
567 }
568 else
569 {
570 m.state = message_state::waiting;
571 };
572 m.wallet_height = (uint32_t)state.num_transfer_details;
573 if (m.type == message_type::additional_key_set)
574 {
575 m.round = state.multisig_rounds_passed;
576 }
577 else
578 {
579 m.round = 0;
580 }
581 m.signature_count = 0; // Future expansion for signature counting when signing txs
582 m.hash = crypto::null_hash;
583 m_messages.push_back(m);
584
585 // Save for every new message right away (at least while in beta)
586 save(state);
587
588 MINFO(boost::format("Added %s message %s for signer %s of type %s")
589 % message_direction_to_string(direction) % m.id % signer_index % message_type_to_string(type));
590 return m_messages.size() - 1;
591 }
592
593 // Get the index of the message with id "id", return false if not found
594 bool message_store::get_message_index_by_id(uint32_t id, size_t &index) const
595 {
596 for (size_t i = 0; i < m_messages.size(); ++i)
597 {
598 if (m_messages[i].id == id)
599 {
600 index = i;
601 return true;
602 }
603 }
604 MWARNING("No message found with an id of " << id);
605 return false;
606 }
607
608 // Get the index of the message with id "id" that must exist
609 size_t message_store::get_message_index_by_id(uint32_t id) const
610 {
611 size_t index;
612 bool found = get_message_index_by_id(id, index);
613 THROW_WALLET_EXCEPTION_IF(!found, tools::error::wallet_internal_error, "Invalid message id " + std::to_string(id));
614 return index;
615 }
616
617 // Get the modifiable message with id "id" that must exist; private/internal use!
618 message& message_store::get_message_ref_by_id(uint32_t id)
619 {
620 return m_messages[get_message_index_by_id(id)];
621 }
622
623 // Get the message with id "id", return false if not found
624 // This version of the method allows to check whether id is valid without triggering an error
625 bool message_store::get_message_by_id(uint32_t id, message &m) const
626 {
627 size_t index;
628 bool found = get_message_index_by_id(id, index);
629 if (found)
630 {
631 m = m_messages[index];
632 }
633 return found;
634 }
635
636 // Get the message with id "id" that must exist
637 message message_store::get_message_by_id(uint32_t id) const
638 {
639 message m;
640 bool found = get_message_by_id(id, m);
641 THROW_WALLET_EXCEPTION_IF(!found, tools::error::wallet_internal_error, "Invalid message id " + std::to_string(id));
642 return m;
643 }
644
645 bool message_store::any_message_of_type(message_type type, message_direction direction) const
646 {
647 for (size_t i = 0; i < m_messages.size(); ++i)
648 {
649 if ((m_messages[i].type == type) && (m_messages[i].direction == direction))
650 {
651 return true;
652 }
653 }
654 return false;
655 }
656
657 bool message_store::any_message_with_hash(const crypto::hash &hash) const
658 {
659 for (size_t i = 0; i < m_messages.size(); ++i)
660 {
661 if (m_messages[i].hash == hash)
662 {
663 return true;
664 }
665 }
666 return false;
667 }
668
669 // Count the ids in the vector that are set i.e. not 0, while ignoring index 0
670 // Mostly used to check whether we have a message for each authorized signer except me,
671 // with the signer index used as index into 'ids'; the element at index 0, for me,
672 // is ignored, to make constant subtractions of 1 for indices when filling the
673 // vector unnecessary
674 size_t message_store::get_other_signers_id_count(const std::vector<uint32_t> &ids) const
675 {
676 size_t count = 0;
677 for (size_t i = 1 /* and not 0 */; i < ids.size(); ++i)
678 {
679 if (ids[i] != 0)
680 {
681 count++;
682 }
683 }
684 return count;
685 }
686
687 // Is in every element of vector 'ids' (except at index 0) a message id i.e. not 0?
688 bool message_store::message_ids_complete(const std::vector<uint32_t> &ids) const
689 {
690 return get_other_signers_id_count(ids) == (ids.size() - 1);
691 }
692
693 void message_store::delete_message(uint32_t id)
694 {
695 delete_transport_message(id);
696 size_t index = get_message_index_by_id(id);
697 m_messages.erase(m_messages.begin() + index);
698 }
699
700 void message_store::delete_all_messages()
701 {
702 for (size_t i = 0; i < m_messages.size(); ++i)
703 {
704 delete_transport_message(m_messages[i].id);
705 }
706 m_messages.clear();
707 }
708
709 // Make a text, which is "attacker controlled data", reasonably safe to display
710 // This is mostly geared towards the safe display of notes sent by "mms note" with a "mms show" command
711 std::string message_store::get_sanitized_text(const std::string &text, size_t max_length)
712 {
713 // Restrict the size to fend of DOS-style attacks with heaps of data
714 size_t length = std::min(text.length(), max_length);
715 std::string sanitized_text = text.substr(0, length);
716
717 try
718 {
719 sanitized_text = tools::utf8canonical(sanitized_text, [](wint_t c)
720 {
721 if ((c < 0x20) || (c == 0x7f) || (c >= 0x80 && c <= 0x9f))
722 {
723 // Strip out any controls, especially ESC for getting rid of potentially dangerous
724 // ANSI escape sequences that a console window might interpret
725 c = '?';
726 }
727 else if ((c == '<') || (c == '>'))
728 {
729 // Make XML or HTML impossible that e.g. might contain scripts that Qt might execute
730 // when displayed in the GUI wallet
731 c = '?';
732 }
733 return c;
734 });
735 }
736 catch (const std::exception &e)
737 {
738 sanitized_text = "(Illegal UTF-8 string)";
739 }
740 return sanitized_text;
741 }
742
743 void message_store::write_to_file(const multisig_wallet_state &state, const std::string &filename)
744 {
745 std::stringstream oss;
746 binary_archive<true> ar(oss);
747 THROW_WALLET_EXCEPTION_IF(!::serialization::serialize(ar, *this), tools::error::wallet_internal_error, "Failed to serialize MMS state");
748 std::string buf = oss.str();
749
750 crypto::chacha_key key;
751 crypto::generate_chacha_key(&state.view_secret_key, sizeof(crypto::secret_key), key, 1);
752
753 file_data write_file_data = {};
754 write_file_data.magic_string = "MMS";
755 write_file_data.file_version = 0;
756 write_file_data.iv = crypto::rand<crypto::chacha_iv>();
757 std::string encrypted_data;
758 encrypted_data.resize(buf.size());
759 crypto::chacha20(buf.data(), buf.size(), key, write_file_data.iv, &encrypted_data[0]);
760 write_file_data.encrypted_data = encrypted_data;
761
762 std::stringstream file_oss;
763 binary_archive<true> file_ar(file_oss);
764 THROW_WALLET_EXCEPTION_IF(!::serialization::serialize(file_ar, write_file_data), tools::error::wallet_internal_error, "Failed to serialize MMS state");
765
766 bool success = epee::file_io_utils::save_string_to_file(filename, file_oss.str());
767 THROW_WALLET_EXCEPTION_IF(!success, tools::error::file_save_error, filename);
768 }
769
770 void message_store::read_from_file(const multisig_wallet_state &state, const std::string &filename, bool load_deprecated_formats)
771 {
772 boost::system::error_code ignored_ec;
773 bool file_exists = boost::filesystem::exists(filename, ignored_ec);
774 if (!file_exists)
775 {
776 // Simply do nothing if the file is not there; allows e.g. easy recovery
777 // from problems with the MMS by deleting the file
778 MINFO("No message store file found: " << filename);
779 return;
780 }
781
782 std::string buf;
783 bool success = epee::file_io_utils::load_file_to_string(filename, buf);
784 THROW_WALLET_EXCEPTION_IF(!success, tools::error::file_read_error, filename);
785
786 bool loaded = false;
787 file_data read_file_data;
788 try
789 {
790 binary_archive<false> ar{epee::strspan<std::uint8_t>(buf)};
791 if (::serialization::serialize(ar, read_file_data))
792 if (::serialization::check_stream_state(ar))
793 loaded = true;
794 }
795 catch (...) {}
796 if (!loaded && load_deprecated_formats)
797 {
798 try
799 {
800 std::stringstream iss;
801 iss << buf;
802 boost::archive::portable_binary_iarchive ar(iss);
803 ar >> read_file_data;
804 loaded = true;
805 }
806 catch (const std::exception &e)
807 {
808 MERROR("MMS file " << filename << " has bad structure <iv,encrypted_data>: " << e.what());
809 THROW_WALLET_EXCEPTION_IF(true, tools::error::file_read_error, filename);
810 }
811 }
812 if (!loaded)
813 {
814 MERROR("MMS file " << filename << " has bad structure <iv,encrypted_data>");
815 THROW_WALLET_EXCEPTION_IF(true, tools::error::file_read_error, filename);
816 }
817
818 crypto::chacha_key key;
819 crypto::generate_chacha_key(&state.view_secret_key, sizeof(crypto::secret_key), key, 1);
820 std::string decrypted_data;
821 decrypted_data.resize(read_file_data.encrypted_data.size());
822 crypto::chacha20(read_file_data.encrypted_data.data(), read_file_data.encrypted_data.size(), key, read_file_data.iv, &decrypted_data[0]);
823
824 loaded = false;
825 try
826 {
827 binary_archive<false> ar{epee::strspan<std::uint8_t>(decrypted_data)};
828 if (::serialization::serialize(ar, *this))
829 if (::serialization::check_stream_state(ar))
830 loaded = true;
831 }
832 catch(...) {}
833 if (!loaded && load_deprecated_formats)
834 {
835 try
836 {
837 std::stringstream iss;
838 iss << decrypted_data;
839 boost::archive::portable_binary_iarchive ar(iss);
840 ar >> *this;
841 loaded = true;
842 }
843 catch (const std::exception &e)
844 {
845 MERROR("MMS file " << filename << " has bad structure: " << e.what());
846 THROW_WALLET_EXCEPTION_IF(true, tools::error::file_read_error, filename);
847 }
848 }
849 if (!loaded)
850 {
851 MERROR("MMS file " << filename << " has bad structure");
852 THROW_WALLET_EXCEPTION_IF(true, tools::error::file_read_error, filename);
853 }
854
855 m_filename = filename;
856 }
857
858 // Save to the same file this message store was loaded from
859 // Called after changes deemed "important", to make it less probable to lose messages in case of
860 // a crash; a better and long-term solution would of course be to use LMDB ...
861 void message_store::save(const multisig_wallet_state &state)
862 {
863 if (!m_filename.empty())
864 {
865 write_to_file(state, m_filename);
866 }
867 }
868
869 bool message_store::get_processable_messages(const multisig_wallet_state &state,
870 bool force_sync, std::vector<processing_data> &data_list, std::string &wait_reason)
871 {
872 uint32_t wallet_height = (uint32_t)state.num_transfer_details;
873 data_list.clear();
874 wait_reason.clear();
875 // In all scans over all messages looking for complete sets (1 message for each signer),
876 // if there are duplicates, the OLDEST of them is taken. This may not play a role with
877 // any of the current message types, but may with future ones, and it's probably a good
878 // idea to have a clear and somewhat defensive strategy.
879
880 std::vector<uint32_t> auto_config_messages(m_num_authorized_signers, 0);
881 bool any_auto_config = false;
882
883 for (size_t i = 0; i < m_messages.size(); ++i)
884 {
885 message &m = m_messages[i];
886 if ((m.type == message_type::auto_config_data) && (m.state == message_state::waiting))
887 {
888 if (auto_config_messages[m.signer_index] == 0)
889 {
890 auto_config_messages[m.signer_index] = m.id;
891 any_auto_config = true;
892 }
893 // else duplicate auto config data, ignore
894 }
895 }
896
897 if (any_auto_config)
898 {
899 bool auto_config_complete = message_ids_complete(auto_config_messages);
900 if (auto_config_complete)
901 {
902 processing_data data;
903 data.processing = message_processing::process_auto_config_data;
904 data.message_ids = auto_config_messages;
905 data.message_ids.erase(data.message_ids.begin());
906 data_list.push_back(data);
907 return true;
908 }
909 else
910 {
911 wait_reason = tr("Auto-config cannot proceed because auto config data from other signers is not complete");
912 return false;
913 // With ANY auto config data present but not complete refuse to check for any
914 // other processing. Manually delete those messages to abort such an auto config
915 // phase if needed.
916 }
917 }
918
919 // Any signer config that arrived will be processed right away, regardless of other things that may wait
920 for (size_t i = 0; i < m_messages.size(); ++i)
921 {
922 message &m = m_messages[i];
923 if ((m.type == message_type::signer_config) && (m.state == message_state::waiting))
924 {
925 processing_data data;
926 data.processing = message_processing::process_signer_config;
927 data.message_ids.push_back(m.id);
928 data_list.push_back(data);
929 return true;
930 }
931 }
932
933 // ALL of the following processings depend on the signer info being complete
934 if (!signer_config_complete())
935 {
936 wait_reason = tr("The signer config is not complete.");
937 return false;
938 }
939
940 if (!state.multisig)
941 {
942
943 if (!any_message_of_type(message_type::key_set, message_direction::out))
944 {
945 // With the own key set not yet ready we must do "prepare_multisig" first;
946 // Key sets from other signers may be here already, but if we process them now
947 // the wallet will go multisig too early: we can't produce our own key set any more!
948 processing_data data;
949 data.processing = message_processing::prepare_multisig;
950 data_list.push_back(data);
951 return true;
952 }
953
954 // Ids of key set messages per signer index, to check completeness
955 // Naturally, does not care about the order of the messages and is trivial to secure against
956 // key sets that were received more than once
957 // With full M/N multisig now possible consider only key sets of the right round, i.e.
958 // with not yet multisig the only possible round 0
959 std::vector<uint32_t> key_set_messages(m_num_authorized_signers, 0);
960
961 for (size_t i = 0; i < m_messages.size(); ++i)
962 {
963 message &m = m_messages[i];
964 if ((m.type == message_type::key_set) && (m.state == message_state::waiting)
965 && (m.round == 0))
966 {
967 if (key_set_messages[m.signer_index] == 0)
968 {
969 key_set_messages[m.signer_index] = m.id;
970 }
971 // else duplicate key set, ignore
972 }
973 }
974
975 bool key_sets_complete = message_ids_complete(key_set_messages);
976 if (key_sets_complete)
977 {
978 // Nothing else can be ready to process earlier than this, ignore everything else and give back
979 processing_data data;
980 data.processing = message_processing::make_multisig;
981 data.message_ids = key_set_messages;
982 data.message_ids.erase(data.message_ids.begin());
983 data_list.push_back(data);
984 return true;
985 }
986 else
987 {
988 wait_reason = tr("Wallet can't go multisig because key sets from other signers are missing or not complete.");
989 return false;
990 }
991 }
992
993 if (state.multisig && !state.multisig_is_ready)
994 {
995 // In the case of M/N multisig the call 'wallet2::multisig' returns already true
996 // after "make_multisig" but with calls to "exchange_multisig_keys" still needed, and
997 // sets the parameter 'ready' to false to document this particular "in-between" state.
998 // So what may be possible here, with all necessary messages present, is a call to
999 // "exchange_multisig_keys".
1000 // Consider only messages belonging to the next round to do, which has the number
1001 // "state.multisig_rounds_passed".
1002 std::vector<uint32_t> additional_key_set_messages(m_num_authorized_signers, 0);
1003
1004 for (size_t i = 0; i < m_messages.size(); ++i)
1005 {
1006 message &m = m_messages[i];
1007 if ((m.type == message_type::additional_key_set) && (m.state == message_state::waiting)
1008 && (m.round == state.multisig_rounds_passed))
1009 {
1010 if (additional_key_set_messages[m.signer_index] == 0)
1011 {
1012 additional_key_set_messages[m.signer_index] = m.id;
1013 }
1014 // else duplicate key set, ignore
1015 }
1016 }
1017
1018 bool key_sets_complete = message_ids_complete(additional_key_set_messages);
1019 if (key_sets_complete)
1020 {
1021 processing_data data;
1022 data.processing = message_processing::exchange_multisig_keys;
1023 data.message_ids = additional_key_set_messages;
1024 data.message_ids.erase(data.message_ids.begin());
1025 data_list.push_back(data);
1026 return true;
1027 }
1028 else
1029 {
1030 wait_reason = tr("Wallet can't start another key exchange round because key sets from other signers are missing or not complete.");
1031 return false;
1032 }
1033 }
1034
1035 // Properly exchanging multisig sync data is easiest and most transparent
1036 // for the user if a wallet sends its own data first and processes any received
1037 // sync data afterwards so that's the order that the MMS enforces here.
1038 // (Technically, it seems to work also the other way round.)
1039 //
1040 // To check whether a NEW round of syncing is necessary the MMS works with a
1041 // "wallet state": new state means new syncing needed.
1042 //
1043 // The MMS monitors the "wallet state" by recording "wallet heights" as
1044 // numbers of transfers present in a wallet at the time of message creation. While
1045 // not watertight, this quite simple scheme should already suffice to trigger
1046 // and orchestrate a sensible exchange of sync data.
1047 if (state.has_multisig_partial_key_images || force_sync)
1048 {
1049 // Sync is necessary and not yet completed: Processing of transactions
1050 // will only be possible again once properly synced
1051 // Check first whether we generated already OUR sync info; take note of
1052 // any processable sync info from other signers on the way in case we need it
1053 bool own_sync_data_created = false;
1054 std::vector<uint32_t> sync_messages(m_num_authorized_signers, 0);
1055 for (size_t i = 0; i < m_messages.size(); ++i)
1056 {
1057 message &m = m_messages[i];
1058 if ((m.type == message_type::multisig_sync_data) && (force_sync || (m.wallet_height == wallet_height)))
1059 // It's data for the same "round" of syncing, on the same "wallet height", therefore relevant
1060 // With "force_sync" take ANY waiting sync data, maybe it will work out
1061 {
1062 if (m.direction == message_direction::out)
1063 {
1064 own_sync_data_created = true;
1065 // Ignore whether sent already or not, and assume as complete if several other signers there
1066 }
1067 else if ((m.direction == message_direction::in) && (m.state == message_state::waiting))
1068 {
1069 if (sync_messages[m.signer_index] == 0)
1070 {
1071 sync_messages[m.signer_index] = m.id;
1072 }
1073 // else duplicate sync message, ignore
1074 }
1075 }
1076 }
1077 if (!own_sync_data_created)
1078 {
1079 // As explained above, creating sync data BEFORE processing such data from
1080 // other signers reliably works, so insist on that here
1081 processing_data data;
1082 data.processing = message_processing::create_sync_data;
1083 data_list.push_back(data);
1084 return true;
1085 }
1086 uint32_t id_count = (uint32_t)get_other_signers_id_count(sync_messages);
1087 // Do we have sync data from ALL other signers?
1088 bool all_sync_data = id_count == (m_num_authorized_signers - 1);
1089 // Do we have just ENOUGH sync data to have a minimal viable sync set?
1090 // In cases like 2/3 multisig we don't need messages from ALL other signers, only
1091 // from enough of them i.e. num_required_signers minus 1 messages
1092 bool enough_sync_data = id_count >= (m_num_required_signers - 1);
1093 bool sync = false;
1094 wait_reason = tr("Syncing not done because multisig sync data from other signers are missing or not complete.");
1095 if (all_sync_data)
1096 {
1097 sync = true;
1098 }
1099 else if (enough_sync_data)
1100 {
1101 if (force_sync)
1102 {
1103 sync = true;
1104 }
1105 else
1106 {
1107 // Don't sync, but give a hint how this minimal set COULD be synced if really wanted
1108 wait_reason += (boost::format("\nUse \"mms next sync\" if you want to sync with just %s out of %s authorized signers and transact just with them")
1109 % (m_num_required_signers - 1) % (m_num_authorized_signers - 1)).str();
1110 }
1111 }
1112 if (sync)
1113 {
1114 processing_data data;
1115 data.processing = message_processing::process_sync_data;
1116 for (size_t i = 0; i < sync_messages.size(); ++i)
1117 {
1118 uint32_t id = sync_messages[i];
1119 if (id != 0)
1120 {
1121 data.message_ids.push_back(id);
1122 }
1123 }
1124 data_list.push_back(data);
1125 return true;
1126 }
1127 else
1128 {
1129 // We can't proceed to any transactions until we have synced; "wait_reason" already set above
1130 return false;
1131 }
1132 }
1133
1134 bool waiting_found = false;
1135 bool note_found = false;
1136 bool sync_data_found = false;
1137 for (size_t i = 0; i < m_messages.size(); ++i)
1138 {
1139 message &m = m_messages[i];
1140 if (m.state == message_state::waiting)
1141 {
1142 waiting_found = true;
1143 switch (m.type)
1144 {
1145 case message_type::fully_signed_tx:
1146 {
1147 // We can either submit it ourselves, or send it to any other signer for submission
1148 processing_data data;
1149 data.processing = message_processing::submit_tx;
1150 data.message_ids.push_back(m.id);
1151 data_list.push_back(data);
1152
1153 data.processing = message_processing::send_tx;
1154 for (uint32_t j = 1; j < m_num_authorized_signers; ++j)
1155 {
1156 data.receiving_signer_index = j;
1157 data_list.push_back(data);
1158 }
1159 return true;
1160 }
1161
1162 case message_type::partially_signed_tx:
1163 {
1164 if (m.signer_index == 0)
1165 {
1166 // We started this ourselves, or signed it but with still signatures missing:
1167 // We can send it to any other signer for signing / further signing
1168 // In principle it does not make sense to send it back to somebody who
1169 // already signed, but the MMS does not / not yet keep track of that,
1170 // because that would be somewhat complicated.
1171 processing_data data;
1172 data.processing = message_processing::send_tx;
1173 data.message_ids.push_back(m.id);
1174 for (uint32_t j = 1; j < m_num_authorized_signers; ++j)
1175 {
1176 data.receiving_signer_index = j;
1177 data_list.push_back(data);
1178 }
1179 return true;
1180 }
1181 else
1182 {
1183 // Somebody else sent this to us: We can sign it
1184 // It would be possible to just pass it on, but that's not directly supported here
1185 processing_data data;
1186 data.processing = message_processing::sign_tx;
1187 data.message_ids.push_back(m.id);
1188 data_list.push_back(data);
1189 return true;
1190 }
1191 }
1192
1193 case message_type::note:
1194 note_found = true;
1195 break;
1196
1197 case message_type::multisig_sync_data:
1198 sync_data_found = true;
1199 break;
1200
1201 default:
1202 break;
1203 }
1204 }
1205 }
1206 if (waiting_found)
1207 {
1208 wait_reason = tr("There are waiting messages, but nothing is ready to process under normal circumstances");
1209 if (sync_data_found)
1210 {
1211 wait_reason += tr("\nUse \"mms next sync\" if you want to force processing of the waiting sync data");
1212 }
1213 if (note_found)
1214 {
1215 wait_reason += tr("\nUse \"mms note\" to display the waiting notes");
1216 }
1217 }
1218 else
1219 {
1220 wait_reason = tr("There are no messages waiting to be processed.");
1221 }
1222
1223 return false;
1224 }
1225
1226 void message_store::set_messages_processed(const processing_data &data)
1227 {
1228 for (size_t i = 0; i < data.message_ids.size(); ++i)
1229 {
1230 set_message_processed_or_sent(data.message_ids[i]);
1231 }
1232 }
1233
1234 void message_store::set_message_processed_or_sent(uint32_t id)
1235 {
1236 message &m = get_message_ref_by_id(id);
1237 if (m.state == message_state::waiting)
1238 {
1239 // So far a fairly cautious and conservative strategy: Only delete from Bitmessage
1240 // when fully processed (and e.g. not already after reception and writing into
1241 // the message store file)
1242 delete_transport_message(id);
1243 m.state = message_state::processed;
1244 }
1245 else if (m.state == message_state::ready_to_send)
1246 {
1247 m.state = message_state::sent;
1248 }
1249 m.modified = (uint64_t)time(NULL);
1250 }
1251
1252 void message_store::encrypt(crypto::public_key public_key, const std::string &plaintext,
1253 std::string &ciphertext, crypto::public_key &encryption_public_key, crypto::chacha_iv &iv)
1254 {
1255 crypto::secret_key encryption_secret_key;
1256 crypto::generate_keys(encryption_public_key, encryption_secret_key);
1257
1258 crypto::key_derivation derivation;
1259 bool success = crypto::generate_key_derivation(public_key, encryption_secret_key, derivation);
1260 THROW_WALLET_EXCEPTION_IF(!success, tools::error::wallet_internal_error, "Failed to generate key derivation for message encryption");
1261
1262 crypto::chacha_key chacha_key;
1263 crypto::generate_chacha_key(&derivation, sizeof(derivation), chacha_key, 1);
1264 iv = crypto::rand<crypto::chacha_iv>();
1265 ciphertext.resize(plaintext.size());
1266 crypto::chacha20(plaintext.data(), plaintext.size(), chacha_key, iv, &ciphertext[0]);
1267 }
1268
1269 void message_store::decrypt(const std::string &ciphertext, const crypto::public_key &encryption_public_key, const crypto::chacha_iv &iv,
1270 const crypto::secret_key &view_secret_key, std::string &plaintext)
1271 {
1272 crypto::key_derivation derivation;
1273 bool success = crypto::generate_key_derivation(encryption_public_key, view_secret_key, derivation);
1274 THROW_WALLET_EXCEPTION_IF(!success, tools::error::wallet_internal_error, "Failed to generate key derivation for message decryption");
1275 crypto::chacha_key chacha_key;
1276 crypto::generate_chacha_key(&derivation, sizeof(derivation), chacha_key, 1);
1277 plaintext.resize(ciphertext.size());
1278 crypto::chacha20(ciphertext.data(), ciphertext.size(), chacha_key, iv, &plaintext[0]);
1279 }
1280
1281 void message_store::send_message(const multisig_wallet_state &state, uint32_t id)
1282 {
1283 message &m = get_message_ref_by_id(id);
1284 const authorized_signer &me = m_signers[0];
1285 const authorized_signer &receiver = m_signers[m.signer_index];
1286 transport_message dm;
1287 crypto::public_key public_key;
1288
1289 dm.timestamp = (uint64_t)time(NULL);
1290 dm.subject = "MMS V0 " + tools::get_human_readable_timestamp(dm.timestamp);
1291 dm.source_transport_address = me.transport_address;
1292 dm.source_monero_address = me.monero_address;
1293 if (m.type == message_type::auto_config_data)
1294 {
1295 // Encrypt with the public key derived from the auto-config token, and send to the
1296 // transport address likewise derived from that token
1297 public_key = me.auto_config_public_key;
1298 dm.destination_transport_address = me.auto_config_transport_address;
1299 // The destination Monero address is not yet known
1300 memset(&dm.destination_monero_address, 0, sizeof(cryptonote::account_public_address));
1301 }
1302 else
1303 {
1304 // Encrypt with the receiver's view public key
1305 public_key = receiver.monero_address.m_view_public_key;
1306 const authorized_signer &receiver = m_signers[m.signer_index];
1307 dm.destination_monero_address = receiver.monero_address;
1308 dm.destination_transport_address = receiver.transport_address;
1309 }
1310 encrypt(public_key, m.content, dm.content, dm.encryption_public_key, dm.iv);
1311 dm.type = (uint32_t)m.type;
1312 dm.hash = crypto::cn_fast_hash(dm.content.data(), dm.content.size());
1313 dm.round = m.round;
1314
1315 crypto::generate_signature(dm.hash, me.monero_address.m_view_public_key, state.view_secret_key, dm.signature);
1316
1317 m_transporter.send_message(dm);
1318
1319 m.state=message_state::sent;
1320 m.sent= (uint64_t)time(NULL);
1321 }
1322
1323 bool message_store::check_for_messages(const multisig_wallet_state &state, std::vector<message> &messages)
1324 {
1325 m_run.store(true, std::memory_order_relaxed);
1326 const authorized_signer &me = m_signers[0];
1327 std::vector<std::string> destinations;
1328 destinations.push_back(me.transport_address);
1329 for (uint32_t i = 1; i < m_num_authorized_signers; ++i)
1330 {
1331 const authorized_signer &m = m_signers[i];
1332 if (m.auto_config_running)
1333 {
1334 destinations.push_back(m.auto_config_transport_address);
1335 }
1336 }
1337 std::vector<transport_message> transport_messages;
1338 if (!m_transporter.receive_messages(destinations, transport_messages))
1339 {
1340 return false;
1341 }
1342 if (!m_run.load(std::memory_order_relaxed))
1343 {
1344 // Stop was called, don't waste time processing the messages
1345 // (but once started processing them, don't react to stop request anymore, avoid receiving them "partially)"
1346 return false;
1347 }
1348
1349 bool new_messages = false;
1350 for (size_t i = 0; i < transport_messages.size(); ++i)
1351 {
1352 transport_message &rm = transport_messages[i];
1353 if (any_message_with_hash(rm.hash))
1354 {
1355 // Already seen, do not take again
1356 }
1357 else
1358 {
1359 uint32_t sender_index;
1360 bool take = false;
1361 message_type type = static_cast<message_type>(rm.type);
1362 crypto::secret_key decrypt_key = state.view_secret_key;
1363 if (type == message_type::auto_config_data)
1364 {
1365 // Find out which signer sent it by checking which auto config transport address
1366 // the message was sent to
1367 for (uint32_t i = 1; i < m_num_authorized_signers; ++i)
1368 {
1369 const authorized_signer &m = m_signers[i];
1370 if (m.auto_config_transport_address == rm.destination_transport_address)
1371 {
1372 take = true;
1373 sender_index = i;
1374 decrypt_key = m.auto_config_secret_key;
1375 break;
1376 }
1377 }
1378 }
1379 else if (type == message_type::signer_config)
1380 {
1381 // Typically we can't check yet whether we know the sender, so take from any
1382 // and pretend it's from "me" because we might have nothing else yet
1383 take = true;
1384 sender_index = 0;
1385 }
1386 else
1387 {
1388 // Only accept from senders that are known as signer here, otherwise just ignore
1389 take = get_signer_index_by_monero_address(rm.source_monero_address, sender_index);
1390 }
1391 if (take && (type != message_type::auto_config_data))
1392 {
1393 // If the destination address is known, check it as well; this additional filter
1394 // allows using the same transport address for multiple signers
1395 take = rm.destination_monero_address == me.monero_address;
1396 }
1397 if (take)
1398 {
1399 crypto::hash actual_hash = crypto::cn_fast_hash(rm.content.data(), rm.content.size());
1400 THROW_WALLET_EXCEPTION_IF(actual_hash != rm.hash, tools::error::wallet_internal_error, "Message hash mismatch");
1401
1402 bool signature_valid = crypto::check_signature(actual_hash, rm.source_monero_address.m_view_public_key, rm.signature);
1403 THROW_WALLET_EXCEPTION_IF(!signature_valid, tools::error::wallet_internal_error, "Message signature not valid");
1404
1405 std::string plaintext;
1406 decrypt(rm.content, rm.encryption_public_key, rm.iv, decrypt_key, plaintext);
1407 size_t index = add_message(state, sender_index, (message_type)rm.type, message_direction::in, plaintext);
1408 message &m = m_messages[index];
1409 m.hash = rm.hash;
1410 m.transport_id = rm.transport_id;
1411 m.sent = rm.timestamp;
1412 m.round = rm.round;
1413 m.signature_count = rm.signature_count;
1414 messages.push_back(m);
1415 new_messages = true;
1416 }
1417 }
1418 }
1419 return new_messages;
1420 }
1421
1422 void message_store::delete_transport_message(uint32_t id)
1423 {
1424 const message &m = get_message_by_id(id);
1425 if (!m.transport_id.empty())
1426 {
1427 m_transporter.delete_message(m.transport_id);
1428 }
1429 }
1430
1431 std::string message_store::account_address_to_string(const cryptonote::account_public_address &account_address) const
1432 {
1433 return get_account_address_as_str(m_nettype, false, account_address);
1434 }
1435
1436 const char* message_store::message_type_to_string(message_type type)
1437 {
1438 switch (type)
1439 {
1440 case message_type::key_set:
1441 return tr("key set");
1442 case message_type::additional_key_set:
1443 return tr("additional key set");
1444 case message_type::multisig_sync_data:
1445 return tr("multisig sync data");
1446 case message_type::partially_signed_tx:
1447 return tr("partially signed tx");
1448 case message_type::fully_signed_tx:
1449 return tr("fully signed tx");
1450 case message_type::note:
1451 return tr("note");
1452 case message_type::signer_config:
1453 return tr("signer config");
1454 case message_type::auto_config_data:
1455 return tr("auto-config data");
1456 default:
1457 return tr("unknown message type");
1458 }
1459 }
1460
1461 const char* message_store::message_direction_to_string(message_direction direction)
1462 {
1463 switch (direction)
1464 {
1465 case message_direction::in:
1466 return tr("in");
1467 case message_direction::out:
1468 return tr("out");
1469 default:
1470 return tr("unknown message direction");
1471 }
1472 }
1473
1474 const char* message_store::message_state_to_string(message_state state)
1475 {
1476 switch (state)
1477 {
1478 case message_state::ready_to_send:
1479 return tr("ready to send");
1480 case message_state::sent:
1481 return tr("sent");
1482 case message_state::waiting:
1483 return tr("waiting");
1484 case message_state::processed:
1485 return tr("processed");
1486 case message_state::cancelled:
1487 return tr("cancelled");
1488 default:
1489 return tr("unknown message state");
1490 }
1491 }
1492
1493 // Convert a signer to string suitable for a column in a list, with 'max_width'
1494 // Format: label: transport_address
1495 std::string message_store::signer_to_string(const authorized_signer &signer, uint32_t max_width)
1496 {
1497 std::string s = "";
1498 s.reserve(max_width);
1499 uint32_t avail = max_width;
1500 uint32_t label_len = signer.label.length();
1501 if (label_len > avail)
1502 {
1503 s.append(signer.label.substr(0, avail - 2));
1504 s.append("..");
1505 return s;
1506 }
1507 s.append(signer.label);
1508 avail -= label_len;
1509 uint32_t transport_addr_len = signer.transport_address.length();
1510 if ((transport_addr_len > 0) && (avail > 10))
1511 {
1512 s.append(": ");
1513 avail -= 2;
1514 if (transport_addr_len <= avail)
1515 {
1516 s.append(signer.transport_address);
1517 }
1518 else
1519 {
1520 s.append(signer.transport_address.substr(0, avail-2));
1521 s.append("..");
1522 }
1523 }
1524 return s;
1525 }
1526
1527 }