Debian Codegraph @

src/multisig/multisig_account_kex_impl.cpp

raw symbols SCIP
1 // Copyright (c) 2021-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 #include "multisig_account.h"
30
31 #include "crypto/crypto.h"
32 #include "cryptonote_config.h"
33 #include "include_base_utils.h"
34 #include "multisig.h"
35 #include "multisig_kex_msg.h"
36 #include "ringct/rctOps.h"
37
38 #include <boost/math/special_functions/binomial.hpp>
39
40 #include <algorithm>
41 #include <cmath>
42 #include <cstdint>
43 #include <limits>
44 #include <memory>
45 #include <unordered_map>
46 #include <unordered_set>
47 #include <utility>
48 #include <vector>
49
50
51 #undef MONERO_DEFAULT_LOG_CATEGORY
52 #define MONERO_DEFAULT_LOG_CATEGORY "multisig"
53
54 namespace multisig
55 {
56 //----------------------------------------------------------------------------------------------------------------------
57 /**
58 * INTERNAL
59 *
60 * brief: check_multisig_config - validate multisig configuration details
61 * param: round - the round of the message that should be produced
62 * param: threshold - threshold for multisig (M in M-of-N)
63 * param: num_signers - number of participants in multisig (N)
64 */
65 //----------------------------------------------------------------------------------------------------------------------
66 static void check_multisig_config(const std::uint32_t round,
67 const std::uint32_t threshold,
68 const std::uint32_t num_signers)
69 {
70 CHECK_AND_ASSERT_THROW_MES(num_signers > 1, "Must be at least one other multisig signer.");
71 CHECK_AND_ASSERT_THROW_MES(num_signers <= config::MULTISIG_MAX_SIGNERS,
72 "Too many multisig signers specified (limit = 16 to prevent dangerous combinatorial explosion during key exchange).");
73 CHECK_AND_ASSERT_THROW_MES(num_signers >= threshold,
74 "Multisig threshold may not be larger than number of signers.");
75 CHECK_AND_ASSERT_THROW_MES(threshold > 0, "Multisig threshold must be > 0.");
76 CHECK_AND_ASSERT_THROW_MES(round > 0, "Multisig kex round must be > 0.");
77 CHECK_AND_ASSERT_THROW_MES(round <= multisig_setup_rounds_required(num_signers, threshold),
78 "Trying to process multisig kex for an invalid round.");
79 }
80 //----------------------------------------------------------------------------------------------------------------------
81 /**
82 * INTERNAL
83 *
84 * brief: calculate_multisig_keypair_from_derivation - wrapper on calculate_multisig_keypair() for an input public key
85 * Converts an input public key into a crypto private key (type cast, does not change serialization),
86 * then passes it to get_multisig_blinded_secret_key().
87 *
88 * Result:
89 * - privkey = H(derivation)
90 * - pubkey = privkey * G
91 * param: derivation - a curve point
92 * outparam: derived_pubkey_out - public key of the resulting privkey
93 * return: multisig private key
94 */
95 //----------------------------------------------------------------------------------------------------------------------
96 static crypto::secret_key calculate_multisig_keypair_from_derivation(const crypto::public_key_memsafe &derivation,
97 crypto::public_key &derived_pubkey_out)
98 {
99 crypto::secret_key blinded_skey = get_multisig_blinded_secret_key(rct::rct2sk(rct::pk2rct(derivation)));
100 CHECK_AND_ASSERT_THROW_MES(crypto::secret_key_to_public_key(blinded_skey, derived_pubkey_out), "Failed to derive public key");
101
102 return blinded_skey;
103 }
104 //----------------------------------------------------------------------------------------------------------------------
105 /**
106 * INTERNAL
107 *
108 * brief: make_multisig_common_privkey - Create the 'common' multisig privkey, owned by all multisig participants.
109 * - common privkey = H(sorted base common privkeys)
110 * param: participant_base_common_privkeys - Base common privkeys contributed by multisig participants.
111 * outparam: common_privkey_out - result
112 */
113 //----------------------------------------------------------------------------------------------------------------------
114 static void make_multisig_common_privkey(std::vector<crypto::secret_key> participant_base_common_privkeys,
115 crypto::secret_key &common_privkey_out)
116 {
117 // sort the privkeys for consistency
118 //TODO: need a constant-time operator< for sorting secret keys
119 std::sort(participant_base_common_privkeys.begin(), participant_base_common_privkeys.end(),
120 [](const crypto::secret_key &key1, const crypto::secret_key &key2) -> bool
121 {
122 return memcmp(&key1, &key2, sizeof(crypto::secret_key)) < 0;
123 }
124 );
125
126 // privkey = H(sorted ancillary base privkeys)
127 crypto::hash_to_scalar(participant_base_common_privkeys.data(),
128 participant_base_common_privkeys.size()*sizeof(crypto::secret_key),
129 common_privkey_out);
130
131 CHECK_AND_ASSERT_THROW_MES(common_privkey_out != crypto::null_skey, "Unexpected null secret key (danger!).");
132 }
133 //----------------------------------------------------------------------------------------------------------------------
134 /**
135 * INTERNAL
136 *
137 * brief: compute_multisig_aggregation_coefficient - creates aggregation coefficient for a specific public key in a set
138 * of public keys
139 *
140 * WARNING: The coefficient will only be deterministic if...
141 * 1) input keys are pre-sorted
142 * - tested here
143 * 2) input keys are in canonical form (compressed points in the prime-order subgroup of Ed25519)
144 * - untested here for performance
145 * param: sorted_keys - set of component public keys that will be merged into a multisig public spend key
146 * param: aggregation_key - one of the component public keys
147 * return: aggregation coefficient
148 */
149 //----------------------------------------------------------------------------------------------------------------------
150 static rct::key compute_multisig_aggregation_coefficient(const std::vector<crypto::public_key> &sorted_keys,
151 const crypto::public_key &aggregation_key)
152 {
153 CHECK_AND_ASSERT_THROW_MES(std::is_sorted(sorted_keys.begin(), sorted_keys.end()),
154 "Keys for aggregation coefficient aren't sorted.");
155
156 // aggregation key must be in sorted_keys
157 CHECK_AND_ASSERT_THROW_MES(std::find(sorted_keys.begin(), sorted_keys.end(), aggregation_key) != sorted_keys.end(),
158 "Aggregation key expected to be in input keyset.");
159
160 // aggregation coefficient salt
161 rct::key salt = rct::zero();
162 static_assert(sizeof(rct::key) >= sizeof(config::HASH_KEY_MULTISIG_KEY_AGGREGATION), "Hash domain separator is too big.");
163 memcpy(salt.bytes, config::HASH_KEY_MULTISIG_KEY_AGGREGATION, sizeof(config::HASH_KEY_MULTISIG_KEY_AGGREGATION));
164
165 // coeff = H(aggregation_key, sorted_keys, domain-sep)
166 rct::keyV data;
167 data.reserve(sorted_keys.size() + 2);
168 data.push_back(rct::pk2rct(aggregation_key));
169 for (const auto &key : sorted_keys)
170 data.push_back(rct::pk2rct(key));
171 data.push_back(salt);
172
173 // note: coefficient is considered public knowledge, no need to memwipe data
174 return rct::hash_to_scalar(data);
175 }
176 //----------------------------------------------------------------------------------------------------------------------
177 /**
178 * INTERNAL
179 *
180 * brief: generate_multisig_aggregate_key - generates a multisig public spend key via key aggregation
181 * Key aggregation via aggregation coefficients prevents key cancellation attacks.
182 * See: https://www.getmonero.org/resources/research-lab/pubs/MRL-0009.pdf
183 * param: final_keys - address components (public keys) obtained from other participants (not shared with local)
184 * param: privkeys_inout - private keys of address components known by local; each key will be multiplied by an aggregation
185 * coefficient (return by reference)
186 * return: final multisig public spend key for the account
187 */
188 //----------------------------------------------------------------------------------------------------------------------
189 static crypto::public_key generate_multisig_aggregate_key(std::vector<crypto::public_key> final_keys,
190 std::vector<crypto::secret_key> &privkeys_inout)
191 {
192 // collect all public keys that will go into the spend key (these don't need to be memsafe)
193 final_keys.reserve(final_keys.size() + privkeys_inout.size());
194
195 // 1. convert local multisig private keys to pub keys
196 // 2. insert to final keyset if not there yet
197 // 3. save the corresponding index of input priv key set for later reference
198 std::unordered_map<crypto::public_key, std::size_t> own_keys_mapping;
199
200 for (std::size_t multisig_keys_index{0}; multisig_keys_index < privkeys_inout.size(); ++multisig_keys_index)
201 {
202 crypto::public_key pubkey;
203 CHECK_AND_ASSERT_THROW_MES(crypto::secret_key_to_public_key(privkeys_inout[multisig_keys_index], pubkey),
204 "Failed to derive public key");
205
206 own_keys_mapping[pubkey] = multisig_keys_index;
207
208 final_keys.push_back(pubkey);
209 }
210
211 // sort input final keys for computing aggregation coefficients (lowest to highest)
212 // note: input should be sanitized (no duplicates)
213 std::sort(final_keys.begin(), final_keys.end());
214 CHECK_AND_ASSERT_THROW_MES(std::adjacent_find(final_keys.begin(), final_keys.end()) == final_keys.end(),
215 "Unexpected duplicate found in input list.");
216
217 // key aggregation
218 rct::key aggregate_key = rct::identity();
219
220 for (const crypto::public_key &key : final_keys)
221 {
222 // get aggregation coefficient
223 rct::key coeff = compute_multisig_aggregation_coefficient(final_keys, key);
224
225 // convert private key if possible
226 // note: retain original priv key index in input list, in case order matters upstream
227 auto found_key = own_keys_mapping.find(key);
228 if (found_key != own_keys_mapping.end())
229 {
230 // k_agg = coeff*k_base
231 sc_mul((unsigned char*)&(privkeys_inout[found_key->second]),
232 coeff.bytes,
233 (const unsigned char*)&(privkeys_inout[found_key->second]));
234
235 CHECK_AND_ASSERT_THROW_MES(privkeys_inout[found_key->second] != crypto::null_skey,
236 "Multisig privkey with aggregation coefficient unexpectedly null.");
237 }
238
239 // convert public key (pre-merge operation)
240 // K_agg = coeff*K_base
241 rct::key converted_pubkey = rct::scalarmultKey(rct::pk2rct(key), coeff);
242
243 // build aggregate key (merge operation)
244 rct::addKeys(aggregate_key, aggregate_key, converted_pubkey);
245 }
246
247 return rct::rct2pk(aggregate_key);
248 }
249 //----------------------------------------------------------------------------------------------------------------------
250 /**
251 * INTERNAL
252 *
253 * brief: multisig_kex_make_round_keys - Makes a kex round's keys.
254 * - Involves DH exchanges with pubkeys provided by other participants.
255 * - Conserves mapping [pubkey -> DH derivation] : [origin keys of participants that share this secret with you].
256 * param: base_privkey - account's base private key, for performing DH exchanges and signing messages
257 * param: pubkey_origins_map - map between pubkeys to produce DH derivations with and identity keys of
258 * participants who will share each derivation with you
259 * outparam: derivation_origins_map_out - map between DH derivations (shared secrets) and identity keys
260 */
261 //----------------------------------------------------------------------------------------------------------------------
262 static void multisig_kex_make_round_keys(const crypto::secret_key &base_privkey,
263 multisig_keyset_map_memsafe_t pubkey_origins_map,
264 multisig_keyset_map_memsafe_t &derivation_origins_map_out)
265 {
266 // make shared secrets with input pubkeys
267 derivation_origins_map_out.clear();
268
269 for (auto &pubkey_and_origins : pubkey_origins_map)
270 {
271 // D = 8 * k_base * K_pubkey
272 // note: must be mul8 (cofactor), otherwise it is possible to leak to a malicious participant if the local
273 // base_privkey is a multiple of 8 or not
274 // note2: avoid making temporaries that won't be memwiped
275 rct::key derivation_rct;
276 auto a_wiper = epee::misc_utils::create_scope_leave_handler([&]{
277 memwipe(&derivation_rct, sizeof(rct::key));
278 });
279
280 rct::scalarmultKey(derivation_rct, rct::pk2rct(pubkey_and_origins.first), rct::sk2rct(base_privkey));
281 rct::scalarmultKey(derivation_rct, derivation_rct, rct::EIGHT);
282
283 // retain mapping between pubkey's origins and the DH derivation
284 // note: if working on last kex round, then caller must know how to handle these derivations properly
285 derivation_origins_map_out[rct::rct2pk(derivation_rct)] = std::move(pubkey_and_origins.second);
286 }
287 }
288 //----------------------------------------------------------------------------------------------------------------------
289 /**
290 * INTERNAL
291 *
292 * brief: check_messages_round - Check that a set of messages have an expected round number.
293 * param: expanded_msgs - set of multisig kex messages to process
294 * param: expected_round - round number the kex messages should have
295 */
296 //----------------------------------------------------------------------------------------------------------------------
297 static void check_messages_round(const std::vector<multisig_kex_msg> &expanded_msgs,
298 const std::uint32_t expected_round)
299 {
300 CHECK_AND_ASSERT_THROW_MES(expanded_msgs.size() > 0, "At least one input message expected.");
301 const std::uint32_t round{expanded_msgs[0].get_round()};
302 CHECK_AND_ASSERT_THROW_MES(round == expected_round, "Messages don't have the expected kex round number.");
303
304 for (const auto &expanded_msg : expanded_msgs)
305 CHECK_AND_ASSERT_THROW_MES(expanded_msg.get_round() == round, "All messages must have the same kex round number.");
306 }
307 //----------------------------------------------------------------------------------------------------------------------
308 /**
309 * INTERNAL
310 *
311 * brief: multisig_kex_msgs_sanitize_pubkeys - Sanitize multisig kex messages.
312 * - Removes duplicates from msg pubkeys, ignores keys found in input 'exclusion set',
313 * constructs map of pubkey:origins.
314 * - Requires that all input msgs have the same round number.
315 *
316 * origins = all the signing pubkeys that recommended a given pubkey found in input msgs
317 *
318 * - If the messages' round numbers are all '1', then only the message signing pubkey is considered
319 * 'recommended'. Furthermore, the 'exclusion set' is ignored.
320 * param: expanded_msgs - set of multisig kex messages to process
321 * param: exclude_pubkeys - pubkeys to exclude from output set
322 * outparam: sanitized_pubkeys_out - processed pubkeys obtained from msgs, mapped to their origins
323 * return: round number shared by all input msgs
324 */
325 //----------------------------------------------------------------------------------------------------------------------
326 static std::uint32_t multisig_kex_msgs_sanitize_pubkeys(const std::vector<multisig_kex_msg> &expanded_msgs,
327 const std::vector<crypto::public_key> &exclude_pubkeys,
328 multisig_keyset_map_memsafe_t &sanitized_pubkeys_out)
329 {
330 // all messages should have the same round (redundant sanity check)
331 CHECK_AND_ASSERT_THROW_MES(expanded_msgs.size() > 0, "At least one input message expected.");
332 const std::uint32_t round{expanded_msgs[0].get_round()};
333 check_messages_round(expanded_msgs, round);
334
335 sanitized_pubkeys_out.clear();
336
337 // get all pubkeys from input messages, add them to pubkey:origins map
338 // - origins = all the signing pubkeys that recommended a given msg pubkey
339 for (const auto &expanded_msg : expanded_msgs)
340 {
341 // in round 1, only the signing pubkey is treated as a msg pubkey
342 if (round == 1)
343 {
344 // note: ignores duplicates
345 sanitized_pubkeys_out[expanded_msg.get_signing_pubkey()].insert(expanded_msg.get_signing_pubkey());
346 }
347 // in other rounds, only the msg pubkeys are treated as msg pubkeys
348 else
349 {
350 // copy all pubkeys from message into list
351 for (const auto &pubkey : expanded_msg.get_msg_pubkeys())
352 {
353 // ignore pubkeys in 'ignore' set
354 if (std::find(exclude_pubkeys.begin(), exclude_pubkeys.end(), pubkey) != exclude_pubkeys.end())
355 continue;
356
357 // note: ignores duplicates
358 sanitized_pubkeys_out[pubkey].insert(expanded_msg.get_signing_pubkey());
359 }
360 }
361 }
362
363 return round;
364 }
365 //----------------------------------------------------------------------------------------------------------------------
366 /**
367 * INTERNAL
368 *
369 * brief: remove_key_from_mapped_sets - Remove a specified key from the mapped sets in a multisig keyset map.
370 * param: key_to_remove - specified key to remove
371 * inoutparam: keyset_inout - keyset to update
372 */
373 //----------------------------------------------------------------------------------------------------------------------
374 static void remove_key_from_mapped_sets(const crypto::public_key &key_to_remove,
375 multisig_keyset_map_memsafe_t &keyset_inout)
376 {
377 // remove specified key from each mapped set
378 for (auto keyset_it = keyset_inout.begin(); keyset_it != keyset_inout.end();)
379 {
380 // remove specified key from this set
381 keyset_it->second.erase(key_to_remove);
382
383 // remove empty keyset positions or increment iterator
384 if (keyset_it->second.size() == 0)
385 keyset_it = keyset_inout.erase(keyset_it);
386 else
387 ++keyset_it;
388 }
389 }
390 //----------------------------------------------------------------------------------------------------------------------
391 /**
392 * INTERNAL
393 *
394 * brief: evaluate_multisig_kex_round_msgs - Evaluate pubkeys from a kex round in order to prepare for the next round.
395 * - Sanitizes input msgs.
396 * - Require uniqueness in: 'exclude_pubkeys'.
397 * - Requires each input pubkey be recommended by 'num_recommendations = expected_round' msg signers.
398 * - For a final multisig key to be truly 'M-of-N', each of the the private key's components must be
399 * shared by (N - M + 1) signers.
400 * - Requires that msgs are signed by only keys in 'signers'.
401 * - Requires that each key in 'signers' recommends [num_signers - 2 CHOOSE (expected_round - 1)] pubkeys.
402 * - These should be derivations each signer recommends for round 'expected_round', excluding derivations shared
403 * with the local account.
404 * - Requires that 'exclude_pubkeys' has [num_signers - 1 CHOOSE (expected_round - 1)] pubkeys.
405 * - These should be derivations the local account has corresponding to round 'expected_round'.
406 * param: base_pubkey - multisig account's base public key
407 * param: expected_round - expected kex round of input messages
408 * param: signers - expected participants in multisig kex
409 * param: expanded_msgs - set of multisig kex messages to process
410 * param: exclude_pubkeys - derivations held by the local account corresponding to round 'expected_round'
411 * param: incomplete_signer_set - only require the minimum number of signers to complete this round
412 * minimum = num_signers - (round num - 1) (including local signer)
413 * return: fully sanitized and validated pubkey:origins map for building the account's next kex round message
414 */
415 //----------------------------------------------------------------------------------------------------------------------
416 static multisig_keyset_map_memsafe_t evaluate_multisig_kex_round_msgs(
417 const crypto::public_key &base_pubkey,
418 const std::uint32_t expected_round,
419 const std::vector<crypto::public_key> &signers,
420 const std::vector<multisig_kex_msg> &expanded_msgs,
421 const std::vector<crypto::public_key> &exclude_pubkeys,
422 const bool incomplete_signer_set)
423 {
424 // exclude_pubkeys should all be unique
425 for (auto it = exclude_pubkeys.begin(); it != exclude_pubkeys.end(); ++it)
426 {
427 CHECK_AND_ASSERT_THROW_MES(std::find(exclude_pubkeys.begin(), it, *it) == it,
428 "Found duplicate pubkeys for exclusion unexpectedly.");
429 }
430
431 // sanitize input messages
432 multisig_keyset_map_memsafe_t pubkey_origins_map; //map: [pubkey : [origins]]
433 const std::uint32_t round = multisig_kex_msgs_sanitize_pubkeys(expanded_msgs, exclude_pubkeys, pubkey_origins_map);
434 CHECK_AND_ASSERT_THROW_MES(round == expected_round,
435 "Kex messages were for round [" << round << "], but expected round is [" << expected_round << "]");
436
437 // remove the local signer from each origins set in the sanitized pubkey map
438 // note: intermediate kex rounds only need keys from other signers to make progress (keys from self are useless)
439 remove_key_from_mapped_sets(base_pubkey, pubkey_origins_map);
440
441 // evaluate pubkeys collected
442 std::unordered_map<crypto::public_key, std::unordered_set<crypto::public_key>> origin_pubkeys_map; //map: [origin: [pubkeys]]
443
444 // 1. each pubkey should be recommended by a precise number of signers
445 const std::size_t num_recommendations_per_pubkey_required{
446 incomplete_signer_set
447 ? 1
448 : round
449 };
450
451 for (const auto &pubkey_and_origins : pubkey_origins_map)
452 {
453 // expected amount = round_num
454 // With each successive round, pubkeys are shared by incrementally larger groups,
455 // starting at 1 in round 1 (i.e. the local multisig key to start kex with).
456 CHECK_AND_ASSERT_THROW_MES(pubkey_and_origins.second.size() >= num_recommendations_per_pubkey_required,
457 "A pubkey recommended by multisig kex messages had an unexpected number of recommendations.");
458
459 // map (sanitized) pubkeys back to origins
460 for (const auto &origin : pubkey_and_origins.second)
461 origin_pubkeys_map[origin].insert(pubkey_and_origins.first);
462 }
463
464 // 2. the number of unique signers recommending pubkeys should equal the number of signers passed in (minus the local signer)
465 // - if an incomplete set is allowed, then we need at least one signer to represent each subgroup in this round that
466 // doesn't include the local signer
467 const std::size_t num_signers_required{
468 incomplete_signer_set
469 ? signers.size() - 1 - (round - 1)
470 : signers.size() - 1
471 };
472
473 CHECK_AND_ASSERT_THROW_MES(origin_pubkeys_map.size() >= num_signers_required,
474 "Number of unique other signers recommending pubkeys does not equal number of required other signers "
475 "(kex round: " << round << ", num signers found: " << origin_pubkeys_map.size() << ", num signers required: " <<
476 num_signers_required << ").");
477
478 // 3. each origin should recommend a precise number of pubkeys
479
480 // TODO: move to a 'math' library, with unit tests
481 auto n_choose_k_f =
482 [](const std::uint32_t n, const std::uint32_t k) -> std::uint32_t
483 {
484 static_assert(std::numeric_limits<std::int32_t>::digits <= std::numeric_limits<double>::digits,
485 "n_choose_k requires no rounding issues when converting between int32 <-> double.");
486
487 if (n < k)
488 return 0;
489
490 double fp_result = boost::math::binomial_coefficient<double>(n, k);
491
492 if (fp_result < 0)
493 return 0;
494
495 if (fp_result > std::numeric_limits<std::int32_t>::max()) // note: std::round() returns std::int32_t
496 return 0;
497
498 return static_cast<std::uint32_t>(std::round(fp_result));
499 };
500
501 // other signers: (N - 2) choose (msg_round_num - 1)
502 // - Each signer recommends keys they share with other signers.
503 // - In each round, every group of size 'round num' will have a key. From a single signer's perspective,
504 // they will share a key with every group of size 'round num - 1' of other signers.
505 // - Since 'origins pubkey map' excludes keys shared with the local account, only keys shared with participants
506 // 'other than local and self' will be in the map (e.g. N - 2 signers).
507 // - Other signers will recommend (N - 2) choose (msg_round_num - 1) pubkeys (after removing keys shared with local).
508 // Note: Keys shared with local are filtered out to facilitate kex round boosting, where one or more signers may
509 // have boosted the local signer (implying they didn't have access to the local signer's previous round msg).
510 const std::uint32_t expected_recommendations_others = n_choose_k_f(signers.size() - 2, round - 1);
511
512 // local: (N - 1) choose (msg_round_num - 1)
513 const std::uint32_t expected_recommendations_self = n_choose_k_f(signers.size() - 1, round - 1);
514
515 // note: expected_recommendations_others would be 0 in the last round of 1-of-N, but we don't call this function for
516 // that case
517 CHECK_AND_ASSERT_THROW_MES(expected_recommendations_self > 0 && expected_recommendations_others > 0,
518 "Bad num signers or round num (possibly numerical limits exceeded).");
519
520 // check that local account recommends expected number of keys
521 CHECK_AND_ASSERT_THROW_MES(exclude_pubkeys.size() == expected_recommendations_self,
522 "Local account did not recommend expected number of multisig keys.");
523
524 // check that other signers recommend expected number of keys
525 for (const auto &origin_and_pubkeys : origin_pubkeys_map)
526 {
527 CHECK_AND_ASSERT_THROW_MES(origin_and_pubkeys.second.size() == expected_recommendations_others,
528 "A multisig signer recommended an unexpected number of pubkeys.");
529
530 // 2 (continued). only expected signers should be recommending keys
531 CHECK_AND_ASSERT_THROW_MES(std::find(signers.begin(), signers.end(), origin_and_pubkeys.first) != signers.end(),
532 "Multisig kex message with unexpected signer encountered.");
533 }
534
535 // note: above tests implicitly detect if the total number of recommended keys is correct or not
536 return pubkey_origins_map;
537 }
538 //----------------------------------------------------------------------------------------------------------------------
539 /**
540 * INTERNAL
541 *
542 * brief: evaluate_multisig_post_kex_round_msgs - Evaluate messages for the post-kex verification round.
543 * - Sanitizes input msgs.
544 * - Requires that only one pubkey is recommended.
545 * - Requires that all signers (other than self) recommend that one pubkey.
546 * param: base_pubkey - multisig account's base public key
547 * param: expected_round - expected kex round of input messages
548 * param: signers - expected participants in multisig kex
549 * param: expanded_msgs - set of multisig kex messages to process
550 * param: incomplete_signer_set - only require the minimum amount of messages to complete this round (1 message)
551 * return: sanitized and validated pubkey:origins map
552 */
553 //----------------------------------------------------------------------------------------------------------------------
554 static multisig_keyset_map_memsafe_t evaluate_multisig_post_kex_round_msgs(
555 const crypto::public_key &base_pubkey,
556 const std::uint32_t expected_round,
557 const std::vector<crypto::public_key> &signers,
558 const std::vector<multisig_kex_msg> &expanded_msgs,
559 const bool incomplete_signer_set)
560 {
561 // sanitize input messages
562 const std::vector<crypto::public_key> dummy;
563 multisig_keyset_map_memsafe_t pubkey_origins_map; //map: [pubkey : [origins]]
564 const std::uint32_t round = multisig_kex_msgs_sanitize_pubkeys(expanded_msgs, dummy, pubkey_origins_map);
565 CHECK_AND_ASSERT_THROW_MES(round == expected_round,
566 "Kex messages were for round [" << round << "], but expected round is [" << expected_round << "]");
567
568 // note: do NOT remove the local signer from the pubkey origins map, since the post-kex round can be force-updated with
569 // just the local signer's post-kex message (if the local signer were removed, then the post-kex message's pubkeys
570 // would be completely lost)
571
572 // evaluate pubkeys collected
573
574 // 1) there should only be two pubkeys
575 CHECK_AND_ASSERT_THROW_MES(pubkey_origins_map.size() == 2,
576 "Multisig post-kex round messages from other signers did not all contain two pubkeys.");
577
578 // 2) both keys should be recommended by the same set of signers
579 CHECK_AND_ASSERT_THROW_MES(pubkey_origins_map.begin()->second == (++(pubkey_origins_map.begin()))->second,
580 "Multisig post-kex round messages from other signers did not all recommend the same pubkey pair.");
581
582 // 3) all signers should be present in the recommendation list (unless an incomplete list is permitted)
583 auto origins = pubkey_origins_map.begin()->second;
584 origins.insert(base_pubkey); //add self if missing
585
586 const std::size_t num_signers_required{
587 incomplete_signer_set
588 ? 1
589 : signers.size()
590 };
591
592 CHECK_AND_ASSERT_THROW_MES(origins.size() >= num_signers_required,
593 "Multisig post-kex round message origins don't line up with multisig signer set "
594 "(num signers found: " << origins.size() << ", num signers required: " << num_signers_required << ").");
595
596 for (const crypto::public_key &origin : origins)
597 {
598 // note: if num_signers_required == signers.size(), then this test will ensure all signers are present in 'origins',
599 // which contains only unique pubkeys
600 CHECK_AND_ASSERT_THROW_MES(std::find(signers.begin(), signers.end(), origin) != signers.end(),
601 "An unknown origin recommended a multisig post-kex verification messsage.");
602 }
603
604 return pubkey_origins_map;
605 }
606 //----------------------------------------------------------------------------------------------------------------------
607 /**
608 * INTERNAL
609 *
610 * brief: multisig_kex_process_round_msgs - Process kex messages for the active kex round.
611 * - A wrapper around evaluate_multisig_kex_round_msgs() -> multisig_kex_make_next_msg().
612 * - In other words, evaluate the input messages and try to make a message for the next round.
613 * - Note: Must be called on the final round's msgs to evaluate the final key components
614 * recommended by other participants.
615 * param: base_privkey - multisig account's base private key
616 * param: current_round - round of kex the input messages should be designed for
617 * param: threshold - threshold for multisig (M in M-of-N)
618 * param: signers - expected participants in multisig kex
619 * param: expanded_msgs - set of multisig kex messages to process
620 * param: exclude_pubkeys - keys held by the local account corresponding to round 'current_round'
621 * - If 'current_round' is the final round, these are the local account's shares of the final aggregate key.
622 * param: incomplete_signer_set - allow messages from an incomplete signer set
623 * outparam: keys_to_origins_map_out - map between round keys and identity keys
624 * - If in the final round, these are key shares recommended by other signers for the final aggregate key.
625 * - Otherwise, these are the local account's DH derivations for the next round.
626 * - See multisig_kex_make_next_msg() for an explanation.
627 * return: multisig kex message for next round, or empty message if 'current_round' is the final round
628 */
629 //----------------------------------------------------------------------------------------------------------------------
630 static void multisig_kex_process_round_msgs(const crypto::secret_key &base_privkey,
631 const crypto::public_key &base_pubkey,
632 const std::uint32_t current_round,
633 const std::uint32_t threshold,
634 const std::vector<crypto::public_key> &signers,
635 const std::vector<multisig_kex_msg> &expanded_msgs,
636 const std::vector<crypto::public_key> &exclude_pubkeys,
637 const bool incomplete_signer_set,
638 multisig_keyset_map_memsafe_t &keys_to_origins_map_out)
639 {
640 check_multisig_config(current_round, threshold, signers.size());
641 const std::uint32_t kex_rounds_required{multisig_kex_rounds_required(signers.size(), threshold)};
642
643 // process messages into a [pubkey : {origins}] map
644 multisig_keyset_map_memsafe_t evaluated_pubkeys;
645
646 if (threshold == 1 && current_round == kex_rounds_required)
647 {
648 // in the last main kex round of 1-of-N, all signers share a key so the local signer doesn't care about evaluating
649 // recommendations from other signers
650 }
651 else if (current_round <= kex_rounds_required)
652 {
653 // for normal kex rounds, fully evaluate kex round messages
654 evaluated_pubkeys = evaluate_multisig_kex_round_msgs(base_pubkey,
655 current_round,
656 signers,
657 expanded_msgs,
658 exclude_pubkeys,
659 incomplete_signer_set);
660 }
661 else //(current_round == kex_rounds_required + 1)
662 {
663 // for the post-kex verification round, validate the last kex round's messages
664 evaluated_pubkeys = evaluate_multisig_post_kex_round_msgs(base_pubkey,
665 current_round,
666 signers,
667 expanded_msgs,
668 incomplete_signer_set);
669 }
670
671 // prepare keys-to-origins map for updating the multisig account
672 if (current_round < kex_rounds_required)
673 {
674 // normal kex round: make new keys
675 multisig_kex_make_round_keys(base_privkey, std::move(evaluated_pubkeys), keys_to_origins_map_out);
676 }
677 else if (current_round >= kex_rounds_required)
678 {
679 // last kex round: collect the key shares recommended by other signers for the final aggregate key
680 // post-kex verification round: save the keys found in input messages
681 keys_to_origins_map_out = std::move(evaluated_pubkeys);
682 }
683 }
684 //----------------------------------------------------------------------------------------------------------------------
685 // multisig_account: INTERNAL
686 //----------------------------------------------------------------------------------------------------------------------
687 void multisig_account::initialize_kex_update(const std::vector<multisig_kex_msg> &expanded_msgs,
688 const std::uint32_t kex_rounds_required,
689 std::vector<crypto::public_key> &exclude_pubkeys_out)
690 {
691 if (m_kex_rounds_complete == 0)
692 {
693 // the first round of kex msgs will contain each participant's base pubkeys and ancillary privkeys
694
695 // collect participants' base common privkey shares
696 // note: duplicate privkeys are acceptable, and duplicates due to duplicate signers
697 // will be blocked by duplicate-signer errors after this function is called
698 std::vector<crypto::secret_key> participant_base_common_privkeys;
699 participant_base_common_privkeys.reserve(expanded_msgs.size() + 1);
700
701 // add local ancillary base privkey
702 participant_base_common_privkeys.emplace_back(m_base_common_privkey);
703
704 // add other signers' base common privkeys
705 for (const auto &expanded_msg : expanded_msgs)
706 {
707 if (expanded_msg.get_signing_pubkey() != m_base_pubkey)
708 {
709 participant_base_common_privkeys.emplace_back(expanded_msg.get_msg_privkey());
710 }
711 }
712
713 // make common privkey
714 make_multisig_common_privkey(std::move(participant_base_common_privkeys), m_common_privkey);
715
716 // set common pubkey
717 CHECK_AND_ASSERT_THROW_MES(crypto::secret_key_to_public_key(m_common_privkey, m_common_pubkey),
718 "Failed to derive public key");
719
720 // if N-of-N, then the base privkey will be used directly to make the account's share of the final key
721 if (kex_rounds_required == 1)
722 {
723 m_multisig_privkeys.clear();
724 m_multisig_privkeys.emplace_back(m_base_privkey);
725 }
726
727 // exclude all keys the local account recommends
728 // - in the first round, only the local pubkey is recommended by the local signer
729 exclude_pubkeys_out.emplace_back(m_base_pubkey);
730 }
731 else
732 {
733 // in other rounds, kex msgs will contain participants' shared keys
734
735 // ignore shared keys the account helped create for this round
736 for (const auto &shared_key_with_origins : m_kex_keys_to_origins_map)
737 {
738 exclude_pubkeys_out.emplace_back(shared_key_with_origins.first);
739 }
740 }
741 }
742 //----------------------------------------------------------------------------------------------------------------------
743 // multisig_account: INTERNAL
744 //----------------------------------------------------------------------------------------------------------------------
745 void multisig_account::finalize_kex_update(const std::uint32_t kex_rounds_required,
746 multisig_keyset_map_memsafe_t result_keys_to_origins_map)
747 {
748 std::vector<crypto::public_key> next_msg_keys;
749
750 // prepare for next round (or complete the multisig account fully)
751 if (m_kex_rounds_complete == kex_rounds_required)
752 {
753 // post-kex verification round: check that the multisig pubkey and common pubkey were recommended by other signers
754 CHECK_AND_ASSERT_THROW_MES(result_keys_to_origins_map.count(m_multisig_pubkey) > 0,
755 "Multisig post-kex round: expected multisig pubkey wasn't found in input messages.");
756 CHECK_AND_ASSERT_THROW_MES(result_keys_to_origins_map.count(m_common_pubkey) > 0,
757 "Multisig post-kex round: expected common pubkey wasn't found in input messages.");
758
759 // save keys that should be recommended to other signers
760 // - for convenience, re-recommend the post-kex verification message once an account is complete
761 next_msg_keys.reserve(2);
762 next_msg_keys.push_back(m_multisig_pubkey);
763 next_msg_keys.push_back(m_common_pubkey);
764 }
765 else if (m_kex_rounds_complete + 1 == kex_rounds_required)
766 {
767 // finished with main kex rounds (have set of msgs to complete address)
768
769 // when 'completing the final round', result keys are other signers' shares of the final key
770 std::vector<crypto::public_key> result_keys;
771 result_keys.reserve(result_keys_to_origins_map.size());
772
773 for (const auto &result_key_and_origins : result_keys_to_origins_map)
774 {
775 result_keys.emplace_back(result_key_and_origins.first);
776 }
777
778 // compute final aggregate key, update local multisig privkeys with aggregation coefficients applied
779 m_multisig_pubkey = generate_multisig_aggregate_key(std::move(result_keys), m_multisig_privkeys);
780
781 // no longer need the account's pubkeys saved for this round (they were only used to build exclude_pubkeys)
782 // TODO: record [pre-aggregation pubkeys : origins] map for aggregation-style signing
783 m_kex_keys_to_origins_map.clear();
784
785 // save keys that should be recommended to other signers
786 // - for post-kex verification, recommend the multisig pubkeys to notify other signers that the local signer is done
787 next_msg_keys.reserve(2);
788 next_msg_keys.push_back(m_multisig_pubkey);
789 next_msg_keys.push_back(m_common_pubkey);
790 }
791 else if (m_kex_rounds_complete + 2 == kex_rounds_required)
792 {
793 // one more round (must send/receive one more set of kex msgs)
794 // - at this point, have local signer's pre-aggregation private key shares of the final address
795
796 // result keys are the local signer's DH derivations for the next round
797
798 // derivations are shared secrets between each group of N - M + 1 signers of which the local account is a member
799 // - convert them to private keys: multisig_key = H(derivation)
800 // - note: shared key = multisig_key[i]*G is recorded in the kex msg for sending to other participants
801 // instead of the original 'derivation' value (which MUST be kept secret!)
802 m_multisig_privkeys.clear();
803 m_multisig_privkeys.reserve(result_keys_to_origins_map.size());
804
805 m_kex_keys_to_origins_map.clear();
806 next_msg_keys.reserve(result_keys_to_origins_map.size());
807
808 for (const auto &derivation_and_origins : result_keys_to_origins_map)
809 {
810 // multisig_privkey = H(derivation)
811 // derived pubkey = multisig_key * G
812 crypto::public_key_memsafe derived_pubkey;
813 m_multisig_privkeys.push_back(
814 calculate_multisig_keypair_from_derivation(derivation_and_origins.first, derived_pubkey));
815
816 // save the account's kex key mappings for this round [derived pubkey : other signers who will have the same key]
817 m_kex_keys_to_origins_map[derived_pubkey] = std::move(derivation_and_origins.second);
818
819 // save keys that should be recommended to other signers
820 // - The keys multisig_key*G are sent to other participants in the message, so they can be used to produce the final
821 // multisig key via generate_multisig_spend_public_key().
822 next_msg_keys.push_back(derived_pubkey);
823 }
824 }
825 else //(m_kex_rounds_complete + 3 <= kex_rounds_required)
826 {
827 // next round is an 'intermediate' key exchange round, so there is nothing special to do here
828
829 // save keys that should be recommended to other signers
830 // - Send this round's DH derivations to other participants, who will make more DH derivations for the following round.
831 next_msg_keys.reserve(result_keys_to_origins_map.size());
832
833 for (const auto &derivation_and_origins : result_keys_to_origins_map)
834 next_msg_keys.push_back(derivation_and_origins.first);
835
836 // save the account's kex keys for this round [DH derivation : other signers who should have the same derivation]
837 m_kex_keys_to_origins_map = std::move(result_keys_to_origins_map);
838 }
839
840 // a full set of msgs has been collected and processed, so the 'round is complete'
841 ++m_kex_rounds_complete;
842
843 // make next round's message (or reproduce the post-kex verification round if kex is complete)
844 m_next_round_kex_message = multisig_kex_msg{
845 (m_kex_rounds_complete > kex_rounds_required ? kex_rounds_required : m_kex_rounds_complete) + 1,
846 m_base_privkey,
847 std::move(next_msg_keys)}.get_msg();
848 }
849 //----------------------------------------------------------------------------------------------------------------------
850 // multisig_account: INTERNAL
851 //----------------------------------------------------------------------------------------------------------------------
852 void multisig_account::kex_update_impl(const std::vector<multisig_kex_msg> &expanded_msgs,
853 const bool incomplete_signer_set)
854 {
855 // check messages are for the expected kex round
856 check_messages_round(expanded_msgs, m_kex_rounds_complete + 1);
857
858 // check kex round count
859 const std::uint32_t kex_rounds_required{multisig_kex_rounds_required(m_signers.size(), m_threshold)};
860
861 CHECK_AND_ASSERT_THROW_MES(kex_rounds_required > 0, "Multisig kex rounds required unexpectedly 0.");
862 CHECK_AND_ASSERT_THROW_MES(m_kex_rounds_complete < kex_rounds_required + 1,
863 "Multisig kex has already completed all required rounds (including post-kex verification).");
864
865 // initialize account update
866 std::vector<crypto::public_key> exclude_pubkeys;
867 initialize_kex_update(expanded_msgs, kex_rounds_required, exclude_pubkeys);
868
869 // process messages into a [pubkey : {origins}] map
870 multisig_keyset_map_memsafe_t result_keys_to_origins_map;
871 multisig_kex_process_round_msgs(
872 m_base_privkey,
873 m_base_pubkey,
874 m_kex_rounds_complete + 1,
875 m_threshold,
876 m_signers,
877 expanded_msgs,
878 exclude_pubkeys,
879 incomplete_signer_set,
880 result_keys_to_origins_map);
881
882 // finish account update
883 finalize_kex_update(kex_rounds_required, std::move(result_keys_to_origins_map));
884 }
885 //----------------------------------------------------------------------------------------------------------------------
886 } //namespace multisig