-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathhttp.rs
846 lines (797 loc) · 32.5 KB
/
http.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
//! HTTP implementation of the Comms trait.
use std::{
collections::{BTreeMap, HashMap, HashSet},
error::Error,
io::{BufRead, Write},
marker::PhantomData,
time::Duration,
vec,
};
use async_trait::async_trait;
use eyre::{eyre, OptionExt};
use frost_core::{
keys::dkg::{round1, round2},
Ciphersuite, Identifier,
};
use frostd::{Msg, PublicKey, Uuid};
use participant::comms::http::Noise;
use rand::thread_rng;
use xeddsa::{xed25519, Sign as _};
use super::Comms;
use crate::args::ProcessedArgs;
/// The current state of a session.
///
/// This can be used by a DKG Participant to help maintain state and handle
/// messages from the other Participants.
#[derive(Debug)]
pub enum SessionState<C: Ciphersuite> {
/// Waiting for participants to send their commitments.
WaitingForRound1Packages {
/// Pubkey -> Identifier mapping. This is set during the
/// get_identifier() call of HTTPComms.
pubkeys: HashMap<PublicKey, Identifier<C>>,
/// Round 1 Packages sent by participants so far.
round1_packages: BTreeMap<Identifier<C>, round1::Package<C>>,
},
/// Waiting for participants to send their broadcasts of other participant's
/// commitments. See documentation of [`handle_round1_package_broadcast()`]
/// for details.
WaitingForRound1PackagesBroadcast {
/// Pubkey -> Identifier mapping.
pubkeys: HashMap<PublicKey, Identifier<C>>,
/// Original Round 1 Packages sent by the other participants.
round1_packages: BTreeMap<Identifier<C>, round1::Package<C>>,
/// Broadcasted Round 1 Packages sent by the other participants,
/// keyed by original sender, then by the sender of the broadcast.
round1_broadcasted_packages:
BTreeMap<Identifier<C>, BTreeMap<Identifier<C>, round1::Package<C>>>,
},
/// Round 1 Packages have been sent by all other participants. Round 2
/// Package can be created sent to other participants. Waiting for other
/// participants to send their Round 2 Packages.
WaitingForRound2Packages {
/// Pubkey -> Identifier mapping.
pubkeys: HashMap<PublicKey, Identifier<C>>,
/// Round 1 Packages sent by participants.
round1_packages: BTreeMap<Identifier<C>, round1::Package<C>>,
/// Round 2 Packages sent by participants so far
round2_packages: BTreeMap<Identifier<C>, round2::Package<C>>,
},
/// Round 2 Packages have been sent by all other participants; ready to be
/// fetched by this participant.
Round2PackagesReady {
/// Pubkey -> Identifier mapping.
pubkeys: HashMap<PublicKey, Identifier<C>>,
/// Round 2 Packages sent by participants so far
round2_packages: BTreeMap<Identifier<C>, round2::Package<C>>,
},
}
impl<C: Ciphersuite> Default for SessionState<C> {
fn default() -> Self {
Self::WaitingForRound1Packages {
pubkeys: Default::default(),
round1_packages: Default::default(),
}
}
}
impl<C: Ciphersuite> SessionState<C> {
/// Handle a Msg received from a participant.
///
/// This should be called for new Msgs until [`are_commitments_ready()`]
/// returns true, and after the SigningPackage is sent to the participants,
/// it should be called for new Msgs until [`are_signature_shares_ready()`]
/// returns true.
pub fn recv(&mut self, msg: Msg, self_identifier: Identifier<C>) -> Result<(), Box<dyn Error>> {
match self {
SessionState::WaitingForRound1Packages { .. } => {
let round1_package: round1::Package<C> = serde_json::from_slice(&msg.msg)?;
self.handle_round1_package(msg.sender, round1_package)?;
}
SessionState::WaitingForRound1PackagesBroadcast { .. } => {
let (identifier, round1_package): (Identifier<C>, round1::Package<C>) =
serde_json::from_slice(&msg.msg)?;
self.handle_round1_package_broadcast(
msg.sender,
self_identifier,
identifier,
round1_package,
)?;
}
SessionState::WaitingForRound2Packages { .. } => {
let round2_package: round2::Package<C> = serde_json::from_slice(&msg.msg)?;
self.handle_round2_package(msg.sender, round2_package)?;
}
_ => return Err(eyre!("received message during wrong state").into()),
}
Ok(())
}
/// Handle commitments sent by a participant.
fn handle_round1_package(
&mut self,
pubkey: PublicKey,
round1_package: round1::Package<C>,
) -> Result<(), Box<dyn Error>> {
if let SessionState::WaitingForRound1Packages {
pubkeys,
round1_packages,
} = self
{
let identifier = *pubkeys.get(&pubkey).ok_or(eyre!("unknown participant"))?;
// Add Round 1 Package to map.
// Currently ignores the possibility of overwriting previous values
// (it seems better to ignore overwrites, which could be caused by
// poor networking connectivity leading to retries)
round1_packages.insert(identifier, round1_package);
// If complete, advance to next state
if round1_packages.len() == pubkeys.len() - 1 {
if pubkeys.len() > 2 {
*self = SessionState::WaitingForRound1PackagesBroadcast {
pubkeys: pubkeys.clone(),
round1_packages: round1_packages.clone(),
round1_broadcasted_packages: Default::default(),
}
} else {
// if pubkeys.len() == 2 then the echo broadcast protocol
// degenerates into a simple broadcast, so we can just skip
// the echo broadcast round.
*self = SessionState::WaitingForRound2Packages {
pubkeys: pubkeys.clone(),
round1_packages: round1_packages.clone(),
round2_packages: Default::default(),
}
}
}
Ok(())
} else {
panic!("wrong state");
}
}
/// Handle broadcast package sent from another participant.
///
/// This implements Goldwasser-Lindell echo-broadcast protocol (Protocol 1
/// from [1]). We use the following terminology in the comments of this
/// function.
///
/// - The original sender is the participant that wants to broadcast their
/// package. The `round1_package` will thus contain the package sent by
/// each original sender.
/// - The broadcaster sender is the participant that, after receiving the
/// original sender package, broadcasts it to all other participants
/// (excluding themselves, and the original sender).
/// - After all that is done, each echo-broadcast session is validated. It
/// is valid if every broadcast package is equal to the original package
/// sent by the original sender.
///
/// Note that here we are keeping track of n-1 echo-broadcasts in parallel,
/// one for each original sender. In each of the n-1 echo-broadcast
/// sessions, we should receive n-2 broadcast packages (since we are
/// excluding the original sender and ourselves).
///
/// [1]: https://eprint.iacr.org/2002/040.pdf
fn handle_round1_package_broadcast(
&mut self,
sender_pubkey: PublicKey,
self_identifier: Identifier<C>,
original_identifier: Identifier<C>,
round1_package: round1::Package<C>,
) -> Result<(), Box<dyn Error>> {
if let SessionState::WaitingForRound1PackagesBroadcast {
pubkeys,
round1_packages,
round1_broadcasted_packages,
} = self
{
let sender_identifier = *pubkeys
.get(&sender_pubkey)
.ok_or(eyre!("unknown participant"))?;
// The `original_identifier` is not authenticated; we need to check
// if it is truly part of the DKG session.
if !pubkeys.values().any(|&id| id == original_identifier) {
return Err(eyre!("unknown participant"))?;
}
// Make sure nothing strange is going on.
if original_identifier == self_identifier {
return Err(eyre!("received own broadcast Round 1 Package").into());
}
if original_identifier == sender_identifier {
return Err(eyre!("received redundant broadcast Round 1 Package").into());
}
// Check if broadcast package is equal to the original package.
if round1_packages
.get(&original_identifier)
.ok_or_eyre("Round 1 Package not found")?
!= &round1_package
{
return Err(eyre!("broadcast mismatch").into());
}
// Add broadcast Round 1 Package to the original sender's map.
if round1_broadcasted_packages
.entry(original_identifier)
.or_insert_with(BTreeMap::new)
.insert(sender_identifier, round1_package)
.is_some()
{
return Err(eyre!("duplicated broadcast Round 1 Package").into());
}
// Set of all other participants' identifiers
let other_identifiers = round1_packages.keys().cloned().collect::<HashSet<_>>();
// If complete, advance to next state. First, check if we have
// package maps for all other participants (original senders).
if round1_broadcasted_packages
.keys()
.cloned()
.collect::<HashSet<_>>()
== other_identifiers
// Then, validate each original sender's map.
&& round1_broadcasted_packages
.iter()
.all(|(original_identifier, map)| {
let mut map_identifiers = map.keys().cloned().collect::<HashSet<_>>();
map_identifiers.insert(*original_identifier);
// Check if the map has all the other participants'
// identifiers, excluding the original sender. (Or
// alternatively, if the `other_identifiers` is equal to
// `map_identifiers` when the original sender is added
// to it.)
map_identifiers == other_identifiers
// And finally, check if the broadcasted packages are
// all equal to the package received from the original
// sender in the previous round. Since we have already
// checked them above before inserting them in
// `round1_broadcasted_packages` this should always be
// true; but it's safer to double check.
&& map.values().all(|package| {
Some(package)
== round1_packages
.get(original_identifier)
})
})
{
*self = SessionState::WaitingForRound2Packages {
pubkeys: pubkeys.clone(),
round1_packages: round1_packages.clone(),
round2_packages: Default::default(),
}
}
Ok(())
} else {
panic!("wrong state");
}
}
/// Returns if all participants sent their Round 1 Packages.
/// When this returns `true`, [`round1_packages()`] can be called, but
/// its contents have not been checked via echo broadcast.
pub fn has_round1_packages(&self) -> bool {
matches!(
self,
SessionState::WaitingForRound1PackagesBroadcast { .. }
| SessionState::WaitingForRound2Packages { .. }
)
}
/// Returns a map linking a participant identifier and the Round 1 Package
/// they have sent.
#[allow(clippy::type_complexity)]
pub fn round1_packages(
&mut self,
) -> Result<BTreeMap<Identifier<C>, round1::Package<C>>, Box<dyn Error>> {
match self {
SessionState::WaitingForRound2Packages {
round1_packages, ..
}
| SessionState::WaitingForRound1PackagesBroadcast {
round1_packages, ..
} => Ok(round1_packages.clone()),
_ => panic!("wrong state"),
}
}
/// Returns if all participants sent their broadcast Round 1 Packages,
/// or if the echo broadcast round should be skipped.
///
/// When this returns `true`, [`round1_packages()`] can be called,
/// and its contents are ensured to be checked via echo broadcast.
pub fn has_round1_broadcast_packages(&self) -> bool {
matches!(self, SessionState::WaitingForRound2Packages { .. })
}
/// Returns if all participants sent their Round 2 Packages.
/// When this returns `true`, [`round2_packages()`] can be called.
pub fn has_round2_packages(&self) -> bool {
matches!(self, SessionState::Round2PackagesReady { .. })
}
/// Handle signature share sent by a participant.
fn handle_round2_package(
&mut self,
pubkey: PublicKey,
round2_package: round2::Package<C>,
) -> Result<(), Box<dyn Error>> {
if let SessionState::WaitingForRound2Packages {
pubkeys,
round1_packages,
round2_packages,
} = self
{
let identifier = pubkeys.get(&pubkey).ok_or(eyre!("unknown participant"))?;
if !round1_packages.contains_key(identifier) {
return Err(eyre!("unkown participant").into());
}
// Currently ignoring the possibility of overwriting previous values
// (it seems better to ignore overwrites, which could be caused by
// poor networking connectivity leading to retries)
round2_packages.insert(*identifier, round2_package);
// If complete, advance to next state
if round2_packages.keys().cloned().collect::<HashSet<_>>()
== round1_packages.keys().cloned().collect::<HashSet<_>>()
{
*self = SessionState::Round2PackagesReady {
pubkeys: pubkeys.clone(),
round2_packages: round2_packages.clone(),
}
}
Ok(())
} else {
panic!("wrong state");
}
}
/// Returns a map linking a participant identifier and the Round 2 Package
/// they have sent.
#[allow(clippy::type_complexity)]
pub fn round2_packages(
&mut self,
) -> Result<BTreeMap<Identifier<C>, round2::Package<C>>, Box<dyn Error>> {
if let SessionState::Round2PackagesReady {
round2_packages, ..
} = self
{
Ok(round2_packages.clone())
} else {
panic!("wrong state");
}
}
}
pub struct HTTPComms<C: Ciphersuite> {
client: reqwest::Client,
host_port: String,
session_id: Option<Uuid>,
access_token: Option<String>,
args: ProcessedArgs<C>,
state: SessionState<C>,
identifier: Option<Identifier<C>>,
pubkeys: HashMap<PublicKey, Identifier<C>>,
// The "send" Noise objects by pubkey of recipients.
send_noise: Option<HashMap<PublicKey, Noise>>,
// The "receive" Noise objects by pubkey of senders.
recv_noise: Option<HashMap<PublicKey, Noise>>,
_phantom: PhantomData<C>,
}
impl<C: Ciphersuite> HTTPComms<C> {
pub fn new(args: &ProcessedArgs<C>) -> Result<Self, Box<dyn Error>> {
let client = reqwest::Client::new();
Ok(Self {
client,
host_port: format!("https://{}:{}", args.ip, args.port),
session_id: None,
access_token: None,
args: args.clone(),
state: SessionState::default(),
identifier: None,
pubkeys: Default::default(),
send_noise: None,
recv_noise: None,
_phantom: Default::default(),
})
}
// Encrypts a message for a given recipient.
fn encrypt(&mut self, recipient: &PublicKey, msg: Vec<u8>) -> Result<Vec<u8>, Box<dyn Error>> {
let noise_map = self
.send_noise
.as_mut()
.expect("send_noise must have been set previously");
let noise = noise_map
.get_mut(recipient)
.ok_or_eyre("unknown recipient")?;
let mut encrypted = vec![0; 65535];
let len = noise.write_message(&msg, &mut encrypted)?;
encrypted.truncate(len);
Ok(encrypted)
}
// Decrypts a message.
// Note that this authenticates the `sender` in the `Msg` struct; if the
// sender is tampered with, the message would fail to decrypt.
fn decrypt(&mut self, msg: Msg) -> Result<Msg, Box<dyn Error>> {
let noise_map = self
.recv_noise
.as_mut()
.expect("recv_noise must have been set previously");
let noise = noise_map
.get_mut(&msg.sender)
.ok_or_eyre("unknown sender")?;
let mut decrypted = vec![0; 65535];
decrypted.resize(65535, 0);
let len = noise.read_message(&msg.msg, &mut decrypted)?;
decrypted.truncate(len);
Ok(Msg {
sender: msg.sender,
msg: decrypted,
})
}
}
#[async_trait(?Send)]
impl<C: Ciphersuite + 'static> Comms<C> for HTTPComms<C> {
async fn get_identifier_and_max_signers(
&mut self,
_input: &mut dyn BufRead,
_output: &mut dyn Write,
) -> Result<(Identifier<C>, u16), Box<dyn Error>> {
let mut rng = thread_rng();
eprintln!("Logging in...");
let challenge = self
.client
.post(format!("{}/challenge", self.host_port))
.json(&frostd::ChallengeArgs {})
.send()
.await?
.json::<frostd::ChallengeOutput>()
.await?
.challenge;
let privkey = xed25519::PrivateKey::from(
&TryInto::<[u8; 32]>::try_into(
self.args
.comm_privkey
.clone()
.ok_or_eyre("comm_privkey must be specified")?,
)
.map_err(|_| eyre!("invalid comm_privkey"))?,
);
let signature: [u8; 64] = privkey.sign(challenge.as_bytes(), &mut rng);
let comm_pubkey = self
.args
.comm_pubkey
.clone()
.ok_or_eyre("comm_pubkey must be specified")?;
self.access_token = Some(
self.client
.post(format!("{}/login", self.host_port))
.json(&frostd::KeyLoginArgs {
challenge,
pubkey: comm_pubkey.clone(),
signature: signature.to_vec(),
})
.send()
.await?
.json::<frostd::LoginOutput>()
.await?
.access_token
.to_string(),
);
let session_id = if !self.args.participants.is_empty() {
eprintln!("Creating DKG session...");
let r = self
.client
.post(format!("{}/create_new_session", self.host_port))
.bearer_auth(self.access_token.as_ref().expect("was just set"))
.json(&frostd::CreateNewSessionArgs {
pubkeys: self.args.participants.clone(),
message_count: 1,
})
.send()
.await?
.json::<frostd::CreateNewSessionOutput>()
.await?;
r.session_id
} else {
eprintln!("Joining DKG session...");
match self.session_id {
Some(s) => s,
None => {
// Get session ID from server
let r = self
.client
.post(format!("{}/list_sessions", self.host_port))
.bearer_auth(self.access_token.as_ref().expect("was just set"))
.send()
.await?
.json::<frostd::ListSessionsOutput>()
.await?;
if r.session_ids.len() > 1 {
return Err(eyre!("user has more than one FROST session active; use `frost-client sessions` to list them and specify the session ID with `-S`").into());
} else if r.session_ids.is_empty() {
return Err(eyre!("User has no current sessions active").into());
}
r.session_ids[0]
}
}
};
self.session_id = Some(session_id);
eprintln!("Getting session info...");
// Get all participants' public keys, and derive their identifiers
// from them.
let session_info = self
.client
.post(format!("{}/get_session_info", self.host_port))
.json(&frostd::GetSessionInfoArgs { session_id })
.bearer_auth(self.access_token.as_ref().expect("was just set"))
.send()
.await?
.json::<frostd::GetSessionInfoOutput>()
.await?;
self.pubkeys = session_info
.pubkeys
.iter()
.map(|p| {
Ok((
p.clone(),
Identifier::<C>::derive(&[session_id.as_bytes(), &p.0[..]].concat())?,
))
})
.collect::<Result<_, frost_core::Error<C>>>()?;
if self.pubkeys.len() < 2 {
return Err(eyre!("DKG session must have at least 2 participants").into());
}
// Copy the pubkeys into the state.
match self.state {
SessionState::WaitingForRound1Packages {
ref mut pubkeys, ..
} => {
*pubkeys = self.pubkeys.clone();
}
_ => unreachable!("wrong state"),
}
// Compute this user's identifier by deriving it from the concatenation
// of the session ID and the communication public key.
// This ensures the identifier is unique and that participants can
// derive each other's identifiers.
let input = [session_id.as_bytes(), &comm_pubkey.0[..]].concat();
let identifier = Identifier::<C>::derive(&input)?;
self.identifier = Some(identifier);
Ok((identifier, self.pubkeys.len() as u16))
}
async fn get_round1_packages(
&mut self,
_input: &mut dyn BufRead,
_output: &mut dyn Write,
round1_package: round1::Package<C>,
) -> Result<BTreeMap<Identifier<C>, round1::Package<C>>, Box<dyn Error>> {
let (Some(comm_privkey), Some(comm_participant_pubkey_getter)) = (
&self.args.comm_privkey,
&self.args.comm_participant_pubkey_getter,
) else {
return Err(
eyre!("comm_privkey and comm_participant_pubkey_getter must be specified").into(),
);
};
let mut send_noise_map = HashMap::new();
let mut recv_noise_map = HashMap::new();
for pubkey in self.pubkeys.keys() {
let comm_participant_pubkey = comm_participant_pubkey_getter(pubkey).ok_or_eyre("A participant in specified FROST session is not registered in the user's address book")?;
let builder = snow::Builder::new(
"Noise_K_25519_ChaChaPoly_BLAKE2s"
.parse()
.expect("should be a valid cipher"),
);
let send_noise = Noise::new(
builder
.local_private_key(comm_privkey)
.remote_public_key(&comm_participant_pubkey.0)
.build_initiator()?,
);
let builder = snow::Builder::new(
"Noise_K_25519_ChaChaPoly_BLAKE2s"
.parse()
.expect("should be a valid cipher"),
);
let recv_noise = Noise::new(
builder
.local_private_key(comm_privkey)
.remote_public_key(&comm_participant_pubkey.0)
.build_responder()?,
);
send_noise_map.insert(pubkey.clone(), send_noise);
recv_noise_map.insert(pubkey.clone(), recv_noise);
}
self.send_noise = Some(send_noise_map);
self.recv_noise = Some(recv_noise_map);
// Send Round 1 Package to all other participants
for pubkey in self.pubkeys.clone().keys() {
if Some(pubkey) == self.args.comm_pubkey.as_ref() {
continue;
}
let msg = self.encrypt(pubkey, serde_json::to_vec(&round1_package)?)?;
self.client
.post(format!("{}/send", self.host_port))
.bearer_auth(self.access_token.as_ref().expect("was just set"))
.json(&frostd::SendArgs {
session_id: self.session_id.expect("set before"),
recipients: vec![pubkey.clone()],
msg,
})
.send()
.await?;
}
eprint!("Waiting for other participants to send their Round 1 Packages...");
loop {
let r = self
.client
.post(format!("{}/receive", self.host_port))
.bearer_auth(
self.access_token
.as_ref()
.expect("must have been set before"),
)
.json(&frostd::ReceiveArgs {
session_id: self.session_id.unwrap(),
as_coordinator: false,
})
.send()
.await?
.json::<frostd::ReceiveOutput>()
.await?;
for msg in r.msgs {
let msg = self.decrypt(msg)?;
self.state
.recv(msg, self.identifier.expect("must have been set"))?;
}
tokio::time::sleep(Duration::from_secs(2)).await;
eprint!(".");
if self.state.has_round1_packages() {
break;
}
}
eprintln!();
// We might need to skip the echo broadcast if its not needed (e.g.
// only 2 participants)
if !self.state.has_round1_broadcast_packages() {
// Broadcast received Round 1 Packages to all other participants
for (recipient_pubkey, recipient_identifier) in self.pubkeys.clone().iter() {
// No need to broadcast to oneself
if Some(recipient_pubkey) == self.args.comm_pubkey.as_ref() {
continue;
}
for (sender_identifier, package) in self.state.round1_packages()?.iter() {
// No need to broadcast back to the sender
if *sender_identifier == *recipient_identifier {
continue;
}
let msg = self.encrypt(
recipient_pubkey,
serde_json::to_vec(&(*sender_identifier, package))?,
)?;
self.client
.post(format!("{}/send", self.host_port))
.bearer_auth(self.access_token.as_ref().expect("was just set"))
.json(&frostd::SendArgs {
session_id: self.session_id.expect("set before"),
recipients: vec![recipient_pubkey.clone()],
msg,
})
.send()
.await?;
}
}
eprint!("Waiting for other participants to send their broadcasted Round 1 Packages...");
loop {
let r = self
.client
.post(format!("{}/receive", self.host_port))
.bearer_auth(
self.access_token
.as_ref()
.expect("must have been set before"),
)
.json(&frostd::ReceiveArgs {
session_id: self.session_id.unwrap(),
as_coordinator: false,
})
.send()
.await?
.json::<frostd::ReceiveOutput>()
.await?;
for msg in r.msgs {
let msg = self.decrypt(msg)?;
self.state
.recv(msg, self.identifier.expect("must have been set"))?;
}
tokio::time::sleep(Duration::from_secs(2)).await;
eprint!(".");
if self.state.has_round1_broadcast_packages() {
break;
}
}
eprintln!();
}
self.state.round1_packages()
}
async fn get_round2_packages(
&mut self,
_input: &mut dyn BufRead,
_output: &mut dyn Write,
round2_packages: BTreeMap<Identifier<C>, round2::Package<C>>,
) -> Result<BTreeMap<Identifier<C>, round2::Package<C>>, Box<dyn Error>> {
// Send Round 2 Packages to all other participants
for (pubkey, identifier) in self.pubkeys.clone().into_iter() {
if Some(&pubkey) == self.args.comm_pubkey.as_ref() {
continue;
}
let msg = self.encrypt(
&pubkey,
serde_json::to_vec(
&round2_packages
.get(&identifier)
.ok_or_eyre("must have Round 2 Package for the given identifier")?,
)?,
)?;
self.client
.post(format!("{}/send", self.host_port))
.bearer_auth(self.access_token.as_ref().expect("was just set"))
.json(&frostd::SendArgs {
session_id: self.session_id.expect("set before"),
recipients: vec![pubkey.clone()],
msg,
})
.send()
.await?;
}
eprint!("Waiting for other participants to send their Round 2 Packages...");
loop {
let r = self
.client
.post(format!("{}/receive", self.host_port))
.bearer_auth(
self.access_token
.as_ref()
.expect("must have been set before"),
)
.json(&frostd::ReceiveArgs {
session_id: self.session_id.unwrap(),
as_coordinator: false,
})
.send()
.await?
.json::<frostd::ReceiveOutput>()
.await?;
for msg in r.msgs {
let msg = self.decrypt(msg)?;
self.state
.recv(msg, self.identifier.expect("must have been set"))?;
}
tokio::time::sleep(Duration::from_secs(2)).await;
eprint!(".");
if self.state.has_round2_packages() {
break;
}
}
eprintln!();
if !self.args.participants.is_empty() {
let _r = self
.client
.post(format!("{}/close_session", self.host_port))
.bearer_auth(
self.access_token
.as_ref()
.expect("must have been set before"),
)
.json(&frostd::CloseSessionArgs {
session_id: self.session_id.unwrap(),
})
.send()
.await?;
}
let _r = self
.client
.post(format!("{}/logout", self.host_port))
.bearer_auth(
self.access_token
.as_ref()
.expect("must have been set before"),
)
.send()
.await?;
self.state.round2_packages()
}
fn get_pubkey_identifier_map(
&self,
) -> Result<HashMap<PublicKey, Identifier<C>>, Box<dyn Error>> {
match &self.state {
SessionState::Round2PackagesReady { pubkeys, .. } => Ok(pubkeys.clone()),
_ => Err(eyre!("wrong state").into()),
}
}
}