-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.rs
1332 lines (1235 loc) · 45.9 KB
/
main.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
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
mod acss;
mod coin;
mod dkg;
mod dpss;
mod file_sss;
mod keypair;
mod local_envelope;
mod opaque;
mod oprf;
mod polynomial;
mod signature;
mod util;
mod zkp;
use acss::{ACSSDealerShare, ACSSInputs, ACSSNodeShare, ACSS};
#[allow(unused_imports)]
use chacha20poly1305::{
aead::{Aead, AeadCore, KeyInit},
ChaCha20Poly1305, Key, Nonce,
};
use curve25519_dalek::constants::RISTRETTO_BASEPOINT_POINT;
use curve25519_dalek::{RistrettoPoint, Scalar};
use dpss::DPSS;
use futures::prelude::*;
use keypair::{Keypair, PublicKey};
use libp2p::kad::{store::MemoryStore, GetRecordOk, PeerRecord};
use libp2p::swarm::{NetworkBehaviour, SwarmEvent};
use libp2p::{gossipsub, identify, kad, mdns, PeerId, Swarm};
use libp2p::{
gossipsub::{IdentTopic, Message},
kad::QueryResult,
};
use local_envelope::{LocalEncryptedEnvelope, LocalEnvelope};
use opaque::{
EncryptedEnvelope, LoginStartRequest, LoginStartResponse, P2POpaqueNode, RegFinishRequest,
RegStartRequest, RegStartResponse,
};
use polynomial::Polynomial;
use rand::rngs::OsRng;
use rand::RngCore;
use serde::{Deserialize, Serialize};
use sha3::{Digest, Sha3_256};
use std::error::Error;
use std::fs;
use std::io::Write;
use std::num::NonZeroUsize;
use std::ops::Add;
use std::path::Path;
use std::str::FromStr;
use std::sync::{Arc, Mutex};
use std::time::Duration;
use std::{
collections::{HashMap, HashSet},
time::Instant,
};
use tauri::State;
use tokio::{io, select, sync::mpsc};
use util::i32_to_scalar;
// --- state structs --- //
#[derive(Debug, Clone)]
struct NodeState {
peer_id: PeerId,
username: String,
index: i32,
opaque_keypair: Keypair,
libp2p_keypair_bytes: [u8; 64],
threshold: usize,
peer_id_to_index: HashMap<PeerId, i32>, // this node's recovery nodes' indices
broadcast_topics: HashMap<PeerId, IdentTopic>, // subscribe to these two
point_to_point_topics: HashMap<PeerId, IdentTopic>,
tx: tokio::sync::mpsc::Sender<TauriToRustCommand>,
acss_inputs: ACSSInputs,
opaque_node: P2POpaqueNode,
peer_recoveries: HashMap<PeerId, (ACSSNodeShare, i32)>, // the indices for nodes for which this node
// is a recovery node
phi_polynomials: Option<(Polynomial, Polynomial)>,
registration_received: Option<HashMap<PeerId, RegStartResponse>>,
recovery_received: Option<HashMap<PeerId, LoginStartResponse>>,
reshare_received: Option<HashMap<PeerId, (ACSSNodeShare, ACSSNodeShare)>>,
}
// --- message structs --- //
#[derive(Serialize, Deserialize, Debug)]
struct IdIndexMessage {
index: i32,
}
#[derive(Serialize, Deserialize, Debug)]
struct OPRFRegInitMessage {
inputs: ACSSInputs,
reg_start_req: RegStartRequest,
dealer_shares: HashMap<PeerId, ACSSDealerShare>,
dealer_key: PublicKey,
user_index: i32,
user_id: PeerId,
node_index: i32,
node_id: PeerId,
}
#[derive(Serialize, Deserialize, Debug)]
struct OPRFRegStartRespMessage {
reg_start_resp: RegStartResponse,
user_index: i32,
user_id: PeerId,
node_index: i32,
node_id: PeerId,
}
#[derive(Serialize, Deserialize, Debug)]
struct OPRFRegFinishReqMessage {
reg_finish_req: RegFinishRequest,
user_index: i32,
user_id: PeerId,
node_index: i32,
node_id: PeerId,
}
#[derive(Serialize, Deserialize, Debug)]
struct OPRFRecoveryStartReqMessage {
recovery_start_req: LoginStartRequest,
other_indices: HashSet<i32>,
user_index: i32,
user_id: PeerId,
node_index: i32,
node_id: PeerId,
}
#[derive(Serialize, Deserialize, Debug)]
struct OPRFRecoveryStartRespMessage {
recovery_start_resp: LoginStartResponse,
user_index: i32,
user_id: PeerId,
node_index: i32,
node_id: PeerId,
}
#[derive(Serialize, Deserialize, Debug)]
struct DPSSRefreshInitMessage {
new_recovery_addresses: HashMap<PeerId, i32>,
new_threshold: usize,
user_index: i32,
user_id: PeerId,
node_index: i32,
node_id: PeerId,
}
#[derive(Serialize, Deserialize, Debug)]
struct DPSSRefreshReshareMessage {
inputs: ACSSInputs,
dealer_shares: HashMap<PeerId, ACSSDealerShare>,
dealer_shares_hat: HashMap<PeerId, ACSSDealerShare>,
commitments: HashMap<Scalar, RistrettoPoint>,
dealer_key: PublicKey,
new_threshold: usize,
user_index: i32,
user_id: PeerId,
node_index: i32,
node_id: PeerId,
}
#[derive(Serialize, Deserialize)]
enum BroadcastMessage {
IdIndexMessage(IdIndexMessage),
OPRFRegInitMessage(OPRFRegInitMessage),
OPRFRegStartRespMessage(OPRFRegStartRespMessage),
OPRFRegFinishReqMessage(OPRFRegFinishReqMessage),
OPRFRecoveryStartReqMessage(OPRFRecoveryStartReqMessage),
OPRFRecoveryStartRespMessage(OPRFRecoveryStartRespMessage),
DPSSRefreshInitMessage(DPSSRefreshInitMessage),
DPSSRefreshReshareMessage(DPSSRefreshReshareMessage),
}
#[derive(NetworkBehaviour)]
struct P2PBehaviour {
gossipsub: gossipsub::Behaviour,
kad: kad::Behaviour<MemoryStore>,
identify: identify::Behaviour,
mdns: mdns::tokio::Behaviour,
}
enum TauriToRustCommand {
RegStart(
libp2p::identity::ed25519::Keypair,
String,
String,
HashMap<PeerId, i32>,
),
RecoveryStart(String, String, HashMap<PeerId, i32>),
RefreshStart(HashMap<PeerId, i32>, i32),
NewSwarm(libp2p::identity::ed25519::Keypair, String),
}
#[derive(serde::Serialize, serde::Deserialize)]
struct EncryptedTauriNotepad {
encrypted_contents: Vec<u8>,
nonce: [u8; 12],
}
/* // from IPFS network
const BOOTNODES: [&str; 4] = [
"QmNnooDu7bfjPFoTZYxMNLWUQJyrVwtbZg5gBMjTezGAJN",
"QmQCU2EcMqAqQPR2i9bChDtGNJchTbq5TbXJJ16u19uLTa",
"QmbLHAnMoJPWSCR5Zhtx6BHJX9KiKNN6tpvbUcqanj75Nb",
"QmcZf59bWwK5XFi76CZX8cbJ4BhTzzA3gU1ZjYZcYW3dwt",
];*/
fn new_swarm(
keypair: libp2p::identity::ed25519::Keypair,
username: String,
) -> Result<Swarm<P2PBehaviour>, Box<dyn Error>> {
let libp2p_keypair = libp2p::identity::Keypair::from(keypair);
let mut swarm = libp2p::SwarmBuilder::with_existing_identity(libp2p_keypair.clone())
.with_tokio()
.with_tcp(
libp2p::tcp::Config::default(),
libp2p::tls::Config::new,
libp2p::yamux::Config::default,
)?
.with_behaviour(|key| {
let message_id_fn = |message: &gossipsub::Message| {
let mut hasher = Sha3_256::new();
hasher.update(message.data.clone());
hasher.update(message.source.unwrap().to_bytes());
let message_hash = hasher.finalize();
gossipsub::MessageId::from(format!("{:X}", message_hash))
};
let gossipsub_config = gossipsub::ConfigBuilder::default()
.heartbeat_interval(Duration::from_secs(10))
.validation_mode(gossipsub::ValidationMode::Strict)
.message_id_fn(message_id_fn)
.build()
.map_err(|msg| io::Error::new(io::ErrorKind::Other, msg))?;
let gossipsub = gossipsub::Behaviour::new(
gossipsub::MessageAuthenticity::Signed(key.clone()),
gossipsub_config,
)?;
let kad = kad::Behaviour::new(
key.public().to_peer_id(),
kad::store::MemoryStore::new(key.public().to_peer_id()),
);
let identify = identify::Behaviour::new(identify::Config::new(
"/ipfs/id/1.0.0".to_string(),
key.public(),
));
let mdns =
mdns::tokio::Behaviour::new(mdns::Config::default(), key.public().to_peer_id())?;
Ok(P2PBehaviour {
gossipsub,
kad,
identify,
mdns,
})
})?
.with_swarm_config(|cfg| {
cfg.with_idle_connection_timeout(std::time::Duration::from_secs(u64::MAX))
})
.build();
swarm.behaviour_mut().kad.set_mode(Some(kad::Mode::Server));
if &username != "" {
swarm
.behaviour_mut()
.kad
.get_record(libp2p::kad::RecordKey::new(&Vec::from(username.as_bytes())));
}
swarm.listen_on("/ip4/0.0.0.0/tcp/0".parse()?)?;
Ok(swarm)
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
let (tx, mut rx) = mpsc::channel::<TauriToRustCommand>(32);
let state = NodeState {
peer_id: PeerId::random(), // temp
peer_id_to_index: HashMap::new(), // temp
username: "".to_string(), // temp
index: 0,
opaque_keypair: Keypair::new(),
libp2p_keypair_bytes: [0u8; 64],
broadcast_topics: HashMap::new(),
point_to_point_topics: HashMap::new(),
tx: tx.clone(),
acss_inputs: ACSSInputs {
h_point: Scalar::random(&mut OsRng) * RISTRETTO_BASEPOINT_POINT,
degree: 1,
peer_public_keys: HashMap::new(),
},
opaque_node: P2POpaqueNode::new("".to_string()),
peer_recoveries: HashMap::new(),
phi_polynomials: None,
registration_received: None,
recovery_received: None,
reshare_received: None,
threshold: 1,
};
let state_arc = Arc::new(Mutex::new(state));
let mut swarm = new_swarm(
libp2p::identity::ed25519::Keypair::generate(),
"".to_string(),
)?;
// the bootstrap nodes aren't listening on this topic, need to run own nodes
/*let bootaddr = Multiaddr::from_str("/dnsaddr/bootstrap.libp2p.io")?;
for peer in &BOOTNODES {
swarm
.behaviour_mut()
.kad
.add_address(&PeerId::from_str(peer)?, bootaddr.clone());
}
swarm.behaviour_mut().kad.bootstrap()?;*/
fn handle_message(
state_arc: Arc<Mutex<NodeState>>,
swarm: &mut Swarm<P2PBehaviour>,
peer_id: PeerId,
message: Message,
) -> Result<(), Box<dyn Error>> {
let mut state = state_arc.lock().unwrap();
let message_data: BroadcastMessage =
serde_json::from_slice(message.data.as_slice()).unwrap();
match message_data {
BroadcastMessage::IdIndexMessage(msg) => {
state.peer_id_to_index.insert(peer_id, msg.index);
Ok(())
}
BroadcastMessage::OPRFRegInitMessage(msg) => {
handle_message_reg_init(&mut state, swarm, peer_id, msg)
}
BroadcastMessage::OPRFRegStartRespMessage(msg) => {
handle_message_reg_start_resp(&mut state, swarm, peer_id, msg)
}
BroadcastMessage::OPRFRegFinishReqMessage(msg) => {
handle_message_reg_finish_req(&mut state, swarm, peer_id, msg)?;
update_peer_ids_kademlia_record(state_arc.clone(), swarm)
}
BroadcastMessage::OPRFRecoveryStartReqMessage(msg) => {
handle_message_rec_start_req(&mut state, swarm, peer_id, msg)
}
BroadcastMessage::OPRFRecoveryStartRespMessage(msg) => {
handle_message_rec_start_resp(&mut state, swarm, peer_id, msg)
}
BroadcastMessage::DPSSRefreshInitMessage(msg) => {
handle_message_dpss_init(&mut state, swarm, peer_id, msg)
}
BroadcastMessage::DPSSRefreshReshareMessage(msg) => {
handle_message_dpss_reshare(&mut state, swarm, peer_id, msg)?;
update_peer_ids_kademlia_record(state_arc.clone(), swarm)
}
}
}
fn handle_reg_init(
state_arc: Arc<Mutex<NodeState>>,
swarm: &mut Swarm<P2PBehaviour>,
password: String,
recovery_addresses: HashMap<PeerId, i32>,
) -> Result<NodeState, Box<dyn Error>> {
let mut state = state_arc.lock().unwrap();
let s = Scalar::random(&mut OsRng);
let (acss_dealer_share, phi, phi_hat) = ACSS::share_dealer(
state.acss_inputs.clone(),
s,
state.acss_inputs.degree,
state.opaque_keypair.private_key,
)?;
state.phi_polynomials = Some((phi, phi_hat));
state.registration_received = Some(HashMap::new());
let reg_start_req = state.opaque_node.local_registration_start(password)?;
for (address, index) in recovery_addresses.iter() {
state
.peer_id_to_index
.insert(address.clone(), index.clone());
let topic = state.point_to_point_topics.get(&address).unwrap().clone();
let init_message = serde_json::to_vec(&OPRFRegInitMessage {
inputs: state.acss_inputs.clone(),
reg_start_req: reg_start_req.clone(),
dealer_shares: acss_dealer_share
.iter()
.map(|(k, v)| (PeerId::from_str(k).unwrap(), v.clone()))
.collect(),
dealer_key: state.opaque_keypair.public_key,
user_index: state.index,
user_id: state.peer_id,
node_index: index.clone(),
node_id: address.clone(),
})
.unwrap();
let message_id = swarm
.behaviour_mut()
.gossipsub
.publish(topic.clone(), init_message);
if let Err(e) = message_id {
println!("Publish error: {e:?}");
} else {
println!(
"[INIT] Sending ACSS share messages for index {}",
state.index
);
}
}
Ok(state.clone())
}
fn handle_message_reg_init(
state: &mut NodeState,
swarm: &mut Swarm<P2PBehaviour>,
peer_id: PeerId,
message: OPRFRegInitMessage,
) -> Result<(), Box<dyn Error>> {
let node_share = ACSS::share(
message.inputs.clone(),
message.dealer_shares.get(&state.peer_id).unwrap().clone(),
state.opaque_keypair.clone(),
message.dealer_key,
)?;
state
.peer_recoveries
.insert(peer_id, (node_share.clone(), message.node_index));
let topic = state
.point_to_point_topics
.get(&message.user_id)
.unwrap()
.clone();
let other_indices = message
.dealer_shares
.values()
.map(|share| share.index.try_into().unwrap())
.collect();
let reg_start_resp = state.opaque_node.peer_registration_start(
message.reg_start_req,
message.node_index,
other_indices,
)?;
let reg_start_resp_message = serde_json::to_vec(&OPRFRegStartRespMessage {
reg_start_resp,
user_index: message.user_index,
user_id: message.user_id,
node_index: state.index,
node_id: state.peer_id,
})
.unwrap();
if let Err(e) = swarm
.behaviour_mut()
.gossipsub
.publish(topic.clone(), reg_start_resp_message)
{
println!("Publish error: {e:?}");
} else {
println!("[REG INIT] Published acknowledgement message");
}
Ok(())
}
fn handle_message_reg_start_resp(
state: &mut NodeState,
swarm: &mut Swarm<P2PBehaviour>,
peer_id: PeerId,
message: OPRFRegStartRespMessage,
) -> Result<(), Box<dyn Error>> {
if let None = state.registration_received {
return Ok(());
}
let mut s = state.registration_received.take().unwrap();
s.insert(peer_id, message.reg_start_resp);
if s.len() < state.threshold {
state.registration_received = Some(s);
return Ok(());
}
let reg_finish_reqs = state.opaque_node.local_registration_finish(
state.libp2p_keypair_bytes,
s.values().map(|v| v.clone()).collect(),
state.threshold,
)?;
for reg_finish_req in reg_finish_reqs.iter() {
let index = state.peer_id_to_index.get(&peer_id).unwrap().clone();
let reg_finish_req_message = serde_json::to_vec(&OPRFRegFinishReqMessage {
reg_finish_req: reg_finish_req.clone(),
user_index: state.index,
user_id: state.peer_id,
node_index: index,
node_id: peer_id,
})
.unwrap();
let topic = state
.point_to_point_topics
.get(&PeerId::from_str(®_finish_req.peer_id).unwrap())
.unwrap()
.clone();
let message_id = swarm
.behaviour_mut()
.gossipsub
.publish(topic.clone(), reg_finish_req_message);
if let Err(e) = message_id {
println!("Publish error: {e:?}");
} else {
println!(
"[REG START RESP] Sending reg start finish messages {}",
state.index
);
}
}
Ok(())
}
fn handle_message_reg_finish_req(
state: &mut NodeState,
_swarm: &mut Swarm<P2PBehaviour>,
_peer_id: PeerId,
message: OPRFRegFinishReqMessage,
) -> Result<(), Box<dyn Error>> {
state
.opaque_node
.peer_registration_finish(message.reg_finish_req)?;
println!(
"[REG FINISH] Finished peer registration for {}",
message.user_id
);
Ok(())
}
fn handle_recovery_init(
state_arc: Arc<Mutex<NodeState>>,
swarm: &mut Swarm<P2PBehaviour>,
username: String,
password: String,
recovery_addresses: HashMap<PeerId, i32>,
) -> Result<NodeState, Box<dyn Error>> {
let mut state = state_arc.lock().unwrap();
state.username = username;
state.recovery_received = Some(HashMap::new());
let recovery_start_req = state.opaque_node.local_login_start(password)?;
let other_indices: HashSet<i32> = recovery_addresses
.clone()
.values()
.map(|v| v.clone())
.collect();
for (address, index) in recovery_addresses.iter() {
let topic = state.point_to_point_topics.get(&address).unwrap().clone();
let login_start_req = serde_json::to_vec(&OPRFRecoveryStartReqMessage {
recovery_start_req: recovery_start_req.clone(),
other_indices: other_indices.clone(),
user_index: state.index,
user_id: state.peer_id,
node_index: index.clone(),
node_id: address.clone(),
})
.unwrap();
let message_id = swarm
.behaviour_mut()
.gossipsub
.publish(topic.clone(), login_start_req);
if let Err(e) = message_id {
println!("Publish error: {e:?}");
} else {
println!("[REC INIT] Sending initial req for index {}", state.index);
}
}
Ok(state.clone())
}
fn handle_message_rec_start_req(
state: &mut NodeState,
swarm: &mut Swarm<P2PBehaviour>,
_peer_id: PeerId,
message: OPRFRecoveryStartReqMessage,
) -> Result<(), Box<dyn Error>> {
let rec_start_resp = state.opaque_node.peer_login_start(
message.recovery_start_req,
message.node_index,
message.other_indices,
)?;
let rec_start_resp_message = serde_json::to_vec(&OPRFRecoveryStartRespMessage {
recovery_start_resp: rec_start_resp,
user_index: message.user_index,
user_id: message.user_id,
node_index: state.index,
node_id: state.peer_id,
})
.unwrap();
let topic = state
.point_to_point_topics
.get(&message.user_id)
.unwrap()
.clone();
if let Err(e) = swarm
.behaviour_mut()
.gossipsub
.publish(topic.clone(), rec_start_resp_message)
{
println!("Publish error: {e:?}");
} else {
println!("[REC INIT] Published acknowledgement message");
}
Ok(())
}
fn handle_message_rec_start_resp(
state: &mut NodeState,
_swarm: &mut Swarm<P2PBehaviour>,
peer_id: PeerId,
message: OPRFRecoveryStartRespMessage,
) -> Result<(), Box<dyn Error>> {
if let None = state.recovery_received {
return Ok(());
}
let mut s = state.recovery_received.take().unwrap();
s.insert(peer_id, message.recovery_start_resp);
if s.len() < state.threshold {
state.recovery_received = Some(s);
return Ok(());
}
let (opaque_keypair, libp2p_keypair_bytes) = state
.opaque_node
.local_login_finish(s.values().map(|v| v.clone()).collect())?;
state.opaque_keypair = opaque_keypair.clone();
state.libp2p_keypair_bytes = libp2p_keypair_bytes;
let libp2p_keypair =
libp2p::identity::ed25519::Keypair::try_from_bytes(&mut libp2p_keypair_bytes.clone())?;
let new_peer_id =
PeerId::from_public_key(&(libp2p::identity::PublicKey::from(libp2p_keypair.public())));
update_with_peer_id(
state,
opaque_keypair,
libp2p_keypair_bytes,
state.tx.clone(),
new_peer_id,
)?;
Ok(())
}
fn handle_refresh_init(
state_arc: Arc<Mutex<NodeState>>,
swarm: &mut Swarm<P2PBehaviour>,
new_recovery_addresses: HashMap<PeerId, i32>,
new_threshold: usize,
) -> Result<NodeState, Box<dyn Error>> {
let mut state = state_arc.lock().unwrap();
if new_threshold + 1 > new_recovery_addresses.len() {
return Err(Box::from(
"Not enough recovery addresses for this threshold",
));
}
for (address, index) in state.peer_id_to_index.iter() {
let topic = state.point_to_point_topics.get(&address).unwrap();
let init_message = serde_json::to_vec(&DPSSRefreshInitMessage {
new_recovery_addresses: new_recovery_addresses.clone(),
new_threshold,
user_index: state.index,
user_id: state.peer_id,
node_index: index.clone(),
node_id: address.clone(),
})
.unwrap();
let message_id = swarm
.behaviour_mut()
.gossipsub
.publish(topic.clone(), init_message);
if let Err(e) = message_id {
println!("Publish error: {e:?}");
} else {
println!("[DPSS INIT] Sending init message");
}
}
state.peer_id_to_index = new_recovery_addresses;
Ok(state.clone())
}
fn handle_message_dpss_init(
state: &mut NodeState,
swarm: &mut Swarm<P2PBehaviour>,
peer_id: PeerId,
message: DPSSRefreshInitMessage,
) -> Result<(), Box<dyn Error>> {
let (node_share, _) = state.peer_recoveries.get(&peer_id).unwrap();
let (acss_dealer_share_s, _, _) = ACSS::share_dealer(
state.acss_inputs.clone(),
node_share.s_i_d,
message.new_recovery_addresses.len() - 1,
state.opaque_keypair.private_key,
)?;
let (acss_dealer_share_s_hat, _, _) = ACSS::share_dealer(
state.acss_inputs.clone(),
node_share.s_hat_i_d,
message.new_recovery_addresses.len() - 1,
state.opaque_keypair.private_key,
)?;
let old_commitments: HashMap<Scalar, RistrettoPoint> = state
.peer_recoveries
.iter()
.map(|(_, v)| (i32_to_scalar(v.1), v.0.c_i.clone()))
.collect();
for (address, index) in message.new_recovery_addresses.iter() {
let topic = state.point_to_point_topics.get(&address).unwrap().clone();
let reshare_msg = serde_json::to_vec(&DPSSRefreshReshareMessage {
inputs: state.acss_inputs.clone(),
dealer_shares: acss_dealer_share_s
.iter()
.map(|(k, v)| (PeerId::from_str(k).unwrap(), v.clone()))
.collect(),
dealer_shares_hat: acss_dealer_share_s_hat
.iter()
.map(|(k, v)| (PeerId::from_str(k).unwrap(), v.clone()))
.collect(),
dealer_key: state.opaque_keypair.private_key,
new_threshold: message.new_threshold,
commitments: old_commitments.clone(),
user_index: state.index,
user_id: state.peer_id,
node_index: index.clone(),
node_id: address.clone(),
})
.unwrap();
let message_id = swarm
.behaviour_mut()
.gossipsub
.publish(topic.clone(), reshare_msg);
if let Err(e) = message_id {
println!("Publish error: {e:?}");
} else {
println!(
"[DPSS INIT] Sending initial ACSS reshares for index {}",
state.index
);
}
}
if !message.new_recovery_addresses.contains_key(&state.peer_id) {
state.peer_recoveries.remove(&message.user_id);
}
Ok(())
}
fn handle_message_dpss_reshare(
state: &mut NodeState,
_swarm: &mut Swarm<P2PBehaviour>,
peer_id: PeerId,
message: DPSSRefreshReshareMessage,
) -> Result<(), Box<dyn Error>> {
let node_share = ACSS::share(
message.inputs.clone(),
message.dealer_shares.get(&state.peer_id).unwrap().clone(),
state.opaque_keypair.clone(),
message.dealer_key,
)?;
let node_share_hat = ACSS::share(
message.inputs.clone(),
message
.dealer_shares_hat
.get(&state.peer_id)
.unwrap()
.clone(),
state.opaque_keypair.clone(),
message.dealer_key,
)?;
let mut s: HashMap<PeerId, (ACSSNodeShare, ACSSNodeShare)>;
if let None = state.reshare_received {
s = HashMap::new();
} else {
s = state.reshare_received.take().unwrap();
}
s.insert(peer_id, (node_share, node_share_hat));
if s.len() < state.threshold {
state.reshare_received = Some(s);
return Ok(());
}
let evaluations: HashMap<Scalar, Scalar> = s
.iter()
.map(|(_, v)| (i32_to_scalar(message.node_index), v.0.s_i_d))
.collect();
let evaluations_hat: HashMap<Scalar, Scalar> = s
.iter()
.map(|(_, v)| (i32_to_scalar(message.node_index), v.1.s_i_d))
.collect();
let (s_i_d_prime, s_hat_i_d_prime, new_commitments) =
DPSS::reshare_w_evals(evaluations, evaluations_hat, message.commitments)?;
let commitment_i = new_commitments
.get(&i32_to_scalar(message.node_index))
.unwrap();
state.peer_recoveries.insert(
peer_id,
(
ACSSNodeShare {
s_i_d: s_i_d_prime,
s_hat_i_d: s_hat_i_d_prime,
c_i: commitment_i.clone(),
},
message.node_index,
),
);
state.threshold = message.new_threshold;
Ok(())
}
fn update_peer_ids(state_arc: Arc<Mutex<NodeState>>) -> Result<(), Box<dyn Error>> {
let state = state_arc.lock().unwrap();
let serialized_peers = serde_json::to_string(&(
state.peer_id_to_index.clone(),
state.peer_recoveries.clone(),
))?;
let file_path = "tmp/peers.list".to_string();
let mut file = fs::File::create(file_path)?;
file.write_all(serialized_peers.as_bytes())?;
Ok(())
}
fn update_peer_ids_kademlia_record(
state_arc: Arc<Mutex<NodeState>>,
swarm: &mut Swarm<P2PBehaviour>,
) -> Result<(), Box<dyn Error>> {
let state = state_arc.lock().unwrap();
let serialized_peers = serde_json::to_vec(&state.peer_id_to_index)?;
let mut pk_record =
kad::Record::new(Vec::from(state.username.as_bytes()), serialized_peers);
pk_record.publisher = Some(*swarm.local_peer_id());
pk_record.expires = Some(Instant::now().add(Duration::from_secs(86400)));
swarm.behaviour_mut().kad.put_record(
pk_record,
kad::Quorum::N(NonZeroUsize::new(state.threshold).unwrap()),
)?;
Ok(())
}
fn add_peer(
state_arc: Arc<Mutex<NodeState>>,
swarm: &mut Swarm<P2PBehaviour>,
peer: PeerId,
) -> Result<(), Box<dyn Error>> {
let mut state = state_arc.lock().unwrap();
println!("Routing updated with peer: {:?}", peer);
swarm.behaviour_mut().gossipsub.add_explicit_peer(&peer);
let subscribe_handle = gossipsub::IdentTopic::new(format!("{peer}"));
state
.broadcast_topics
.insert(peer, subscribe_handle.clone());
swarm
.behaviour_mut()
.gossipsub
.subscribe(&subscribe_handle)?;
if let None = state.point_to_point_topics.get(&peer) {
let topic_name;
if state.peer_id.to_string() < peer.to_string() {
topic_name = format!("{}-{}", state.peer_id, peer);
} else {
topic_name = format!("{}-{}", peer, state.peer_id);
}
let topic = gossipsub::IdentTopic::new(topic_name);
state.point_to_point_topics.insert(peer, topic.clone());
swarm.behaviour_mut().gossipsub.subscribe(&topic)?;
}
return Ok(());
}
fn remove_peer(
state_arc: Arc<Mutex<NodeState>>,
swarm: &mut Swarm<P2PBehaviour>,
peer: PeerId,
) -> Result<(), Box<dyn Error>> {
let mut state = state_arc.lock().unwrap();
swarm.behaviour_mut().gossipsub.remove_explicit_peer(&peer);
if let Some(topic) = state.point_to_point_topics.get(&peer) {
swarm.behaviour_mut().gossipsub.unsubscribe(&topic)?;
state.point_to_point_topics.remove(&peer);
}
if let Some(topic) = state.broadcast_topics.get(&peer) {
swarm.behaviour_mut().gossipsub.unsubscribe(&topic)?;
state.broadcast_topics.remove(&peer);
}
Ok(())
}
struct TauriState(
Arc<Mutex<NodeState>>,
tokio::sync::mpsc::Sender<TauriToRustCommand>,
);
#[tauri::command]
fn get_peer_id(state: State<TauriState>) -> String {
let node_state = state.0.lock().unwrap();
node_state.peer_id.to_string()
}
#[tauri::command]
fn get_peers(state: State<TauriState>) -> Vec<String> {
let node_state = state.0.lock().unwrap();
return Vec::from_iter(
node_state
.point_to_point_topics
.keys()
.map(|v| v.to_string()),
);
}
#[tauri::command]
fn local_register(
state: State<TauriState>,
username: String,
password: String,
recovery_addresses: HashMap<String, i32>,
) -> Result<(), String> {
let mut node_state = state.0.lock().unwrap();
let file_path = "tmp/login.envelope".to_string();
if Path::new(&file_path).exists() {
return Err("Encrypted envelope already exists".to_string());
}
if let Err(e) = fs::create_dir_all("tmp") {
return Err(e.to_string());
}
let file = fs::File::create(file_path);
if let Err(e) = file {
return Err(e.to_string());
}
node_state.opaque_keypair = Keypair::new();
let libp2p_keypair = libp2p::identity::ed25519::Keypair::generate();
let envelope = LocalEnvelope {
keypair: node_state.opaque_keypair.clone(),
libp2p_keypair_bytes: libp2p_keypair.to_bytes(),
peer_public_key: (Scalar::ZERO * RISTRETTO_BASEPOINT_POINT)
.compress()
.to_bytes(),
peer_id: node_state.peer_id.to_string(),
username,
};
let encrypted_envelope = envelope.clone().encrypt_w_password(password.clone());
if let Err(e) = encrypted_envelope {
return Err(e.to_string());
}
let serialized_envelope = serde_json::to_string(&encrypted_envelope.unwrap());
if let Err(e) = serialized_envelope {
return Err(e.to_string());
}
let result = file
.unwrap()
.write_all(serialized_envelope.unwrap().as_bytes());
if let Err(e) = result {
return Err(e.to_string());
}
let tx_clone = state.1.clone();
let keypair = libp2p_keypair.clone();
let username = node_state.username.clone();
let password_clone = password.clone();
let recovery_nodes: HashMap<PeerId, i32> = recovery_addresses
.iter()
.map(|(k, v)| (PeerId::from_str(k).unwrap(), v.clone()))
.collect();
tokio::spawn(async move {
tx_clone
.send(TauriToRustCommand::RegStart(
keypair,
username,
password_clone,
recovery_nodes,
))
.await
.unwrap();
});