-
Notifications
You must be signed in to change notification settings - Fork 63
/
internal.rs
1064 lines (919 loc) · 38.2 KB
/
internal.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
use std::sync::{Arc, Condvar, Mutex};
use tonic::{Code, Request, Response, Status};
use triggered::Trigger;
use crate::protos as msgs;
use crate::protos::private_tower_services_server::PrivateTowerServices;
use crate::protos::public_tower_services_server::PublicTowerServices;
use crate::watcher::{
AddAppointmentFailure, AppointmentInfo, GetAppointmentFailure, GetSubscriptionInfoFailure,
Watcher,
};
use teos_common::appointment::{Appointment, AppointmentStatus, Locator};
use teos_common::UserId;
/// Internal API of the tower.
/// Holds the [Watcher] (which is the single entry point of the tower's core) and offers interfaces
/// to all available methods. The [InternalAPI] has two interfaces, a public one, reachable from the [API]
/// and a private one, only accessible from the [RPCServer].
pub struct InternalAPI {
/// A [Watcher] instance.
watcher: Arc<Watcher>,
/// A flag that indicates wether bitcoind is reachable or not.
bitcoind_reachable: Arc<(Mutex<bool>, Condvar)>,
/// A signal indicating the tower is shuting down.
shutdown_trigger: Trigger,
}
impl InternalAPI {
/// Creates a new [InternalAPI] instance.
pub fn new(
watcher: Arc<Watcher>,
bitcoind_reachable: Arc<(Mutex<bool>, Condvar)>,
shutdown_trigger: Trigger,
) -> Self {
Self {
watcher,
bitcoind_reachable,
shutdown_trigger,
}
}
/// Checks whether bitcoind is reachable.
fn check_service_unavailable(&self) -> Result<(), Status> {
if *self.bitcoind_reachable.0.lock().unwrap() {
Ok(())
} else {
log::error!("Bitcoind not reachable");
Err(Status::new(
Code::Unavailable,
"Service currently unavailable",
))
}
}
}
/// Public tower API. Accessible by users.
#[tonic::async_trait]
impl PublicTowerServices for Arc<InternalAPI> {
/// Register endpoint. Part of the public API. Internally calls [Watcher::register].
async fn register(
&self,
request: Request<msgs::RegisterRequest>,
) -> Result<Response<msgs::RegisterResponse>, Status> {
self.check_service_unavailable()?;
let req_data = request.into_inner();
let user_id = UserId::deserialize(&req_data.user_id).map_err(|_| {
Status::new(
Code::InvalidArgument,
"Provided public key does not match expected format (33-byte compressed key)",
)
})?;
match self.watcher.register(user_id) {
Ok(receipt) => Ok(Response::new(msgs::RegisterResponse {
user_id: req_data.user_id,
available_slots: receipt.available_slots(),
subscription_expiry: receipt.subscription_expiry(),
subscription_signature: receipt.signature().unwrap(),
})),
Err(_) => Err(Status::new(
Code::ResourceExhausted,
"Subscription maximum slots count reached",
)),
}
}
/// Add appointment endpoint. Part of the public API. Internally calls [Watcher::add_appointment].
async fn add_appointment(
&self,
request: Request<msgs::AddAppointmentRequest>,
) -> Result<Response<msgs::AddAppointmentResponse>, Status> {
self.check_service_unavailable()?;
let req_data = request.into_inner();
let app_data = req_data.appointment.unwrap();
let appointment = Appointment::new(
Locator::deserialize(&app_data.locator).unwrap(),
app_data.encrypted_blob,
app_data.to_self_delay,
);
let locator = appointment.locator;
match self
.watcher
.add_appointment(appointment, req_data.signature)
{
Ok((receipt, available_slots, subscription_expiry)) => {
Ok(Response::new(msgs::AddAppointmentResponse {
locator: locator.serialize(),
start_block: receipt.start_block(),
signature: receipt.signature().unwrap(),
available_slots,
subscription_expiry,
}))
}
Err(e) => match e {
AddAppointmentFailure::AuthenticationFailure
| AddAppointmentFailure::NotEnoughSlots => Err(Status::new(
Code::Unauthenticated,
"Invalid signature or user does not have enough slots available",
)),
AddAppointmentFailure::SubscriptionExpired(x) => Err(Status::new(
Code::Unauthenticated,
format!("Your subscription expired at {}", x),
)),
AddAppointmentFailure::AlreadyTriggered => Err(Status::new(
Code::AlreadyExists,
"The provided appointment has already been triggered",
)),
},
}
}
/// Get appointment endpoint. Part of the public API. Internally calls [Watcher::get_appointment].
async fn get_appointment(
&self,
request: Request<msgs::GetAppointmentRequest>,
) -> Result<Response<msgs::GetAppointmentResponse>, Status> {
self.check_service_unavailable()?;
let req_data = request.into_inner();
let locator = Locator::deserialize(&req_data.locator).unwrap();
match self.watcher.get_appointment(locator, &req_data.signature) {
Ok(info) => {
let (appointment_data, status) = match info {
AppointmentInfo::Appointment(appointment) => (
msgs::AppointmentData {
appointment_data: Some(
msgs::appointment_data::AppointmentData::Appointment(
appointment.into(),
),
),
},
AppointmentStatus::BeingWatched,
),
AppointmentInfo::Tracker(tracker) => (
msgs::AppointmentData {
appointment_data: Some(
msgs::appointment_data::AppointmentData::Tracker(tracker.into()),
),
},
AppointmentStatus::DisputeResponded,
),
};
Ok(Response::new(msgs::GetAppointmentResponse {
appointment_data: Some(appointment_data),
status: status as i32,
}))
}
Err(e) => match e {
GetAppointmentFailure::NotFound => {
Err(Status::new(Code::NotFound, "Appointment not found"))
}
GetAppointmentFailure::AuthenticationFailure => Err(Status::new(
Code::Unauthenticated,
"User cannot be authenticated",
)),
GetAppointmentFailure::SubscriptionExpired(x) => Err(Status::new(
Code::Unauthenticated,
format!("Your subscription expired at {}", x),
)),
},
}
}
/// Get subscription info endpoint. Part of the public API. Internally calls [Watcher::get_subscription_info].
async fn get_subscription_info(
&self,
request: Request<msgs::GetSubscriptionInfoRequest>,
) -> Result<Response<msgs::GetSubscriptionInfoResponse>, Status> {
self.check_service_unavailable()?;
let (subscription_info, locators) = self
.watcher
.get_subscription_info(&request.into_inner().signature)
.map_err(|e| match e {
GetSubscriptionInfoFailure::AuthenticationFailure => Status::new(
Code::Unauthenticated,
"User not found. Have you registered?",
),
GetSubscriptionInfoFailure::SubscriptionExpired(x) => Status::new(
Code::Unauthenticated,
format!("Your subscription expired at {}", x),
),
})?;
Ok(Response::new(msgs::GetSubscriptionInfoResponse {
available_slots: subscription_info.available_slots,
subscription_expiry: subscription_info.subscription_expiry,
locators: locators.iter().map(|x| x.serialize()).collect(),
}))
}
}
/// Private tower API. Only accessible by the tower admin via RPC.
#[tonic::async_trait]
impl PrivateTowerServices for Arc<InternalAPI> {
/// Get all appointments endpoint. Gets all appointments in the tower. Part of the private API.
/// Internally calls [Watcher::get_all_watcher_appointments] and [Watcher::get_all_responder_trackers].
async fn get_all_appointments(
&self,
_: Request<()>,
) -> Result<Response<msgs::GetAllAppointmentsResponse>, Status> {
let mut all_appointments = Vec::new();
for (_, appointment) in self.watcher.get_all_watcher_appointments().into_iter() {
all_appointments.push(msgs::AppointmentData {
appointment_data: Some(msgs::appointment_data::AppointmentData::Appointment(
appointment.inner.into(),
)),
})
}
for (_, tracker) in self.watcher.get_all_responder_trackers().into_iter() {
all_appointments.push(msgs::AppointmentData {
appointment_data: Some(msgs::appointment_data::AppointmentData::Tracker(
tracker.into(),
)),
})
}
Ok(Response::new(msgs::GetAllAppointmentsResponse {
appointments: all_appointments,
}))
}
/// Get tower info endpoint. Gets information about the tower state. Part of the private API.
/// Internally calls [Watcher::get_registered_users_count], [Watcher::get_appointments_count]
/// and [Watcher::get_trackers_count].
async fn get_tower_info(
&self,
_: Request<()>,
) -> Result<Response<msgs::GetTowerInfoResponse>, Status> {
Ok(Response::new(msgs::GetTowerInfoResponse {
tower_id: self.watcher.tower_id.serialize(),
n_registered_users: self.watcher.get_registered_users_count() as u32,
n_watcher_appointments: self.watcher.get_appointments_count() as u32,
n_responder_trackers: self.watcher.get_trackers_count() as u32,
bitcoind_reachable: self.check_service_unavailable().is_ok(),
}))
}
/// Get user endpoint. Gets all users in the tower. Part of the private API.
/// Internally calls [Watcher::get_user_ids].
async fn get_users(&self, _: Request<()>) -> Result<Response<msgs::GetUsersResponse>, Status> {
let user_ids = self
.watcher
.get_user_ids()
.iter()
.map(|x| x.serialize())
.collect();
Ok(Response::new(msgs::GetUsersResponse { user_ids }))
}
/// Get user endpoint. Gets information about a given user. Part of the private API.
/// Internally calls [Watcher::get_user].
async fn get_user(
&self,
request: Request<msgs::GetUserRequest>,
) -> Result<Response<msgs::GetUserResponse>, Status> {
let user_id = UserId::deserialize(&request.into_inner().user_id).map_err(|_| {
Status::new(
Code::InvalidArgument,
"Provided public key does not match expected format (33-byte compressed key)",
)
})?;
match self.watcher.get_user_info(user_id) {
Some(info) => Ok(Response::new(msgs::GetUserResponse {
available_slots: info.available_slots,
subscription_expiry: info.subscription_expiry,
appointments: info
.appointments
.iter()
.map(|(uuid, _)| uuid.serialize())
.collect(),
})),
None => Err(Status::new(Code::NotFound, "User not found")),
}
}
/// Stop endpoint. Stops the tower daemon. Part of the private API.
async fn stop(&self, _: Request<()>) -> Result<Response<()>, Status> {
self.shutdown_trigger.trigger();
log::debug!("Received shutting down signal, notifying components");
Ok(Response::new(()))
}
}
#[cfg(test)]
mod tests_private_helpers {
use super::*;
impl InternalAPI {
pub(crate) fn get_watcher(&self) -> &Watcher {
&self.watcher
}
}
}
#[cfg(test)]
mod tests_private_api {
use super::*;
use std::collections::HashSet;
use std::iter::FromIterator;
use crate::extended_appointment::UUID;
use crate::test_utils::{
create_api, generate_dummy_appointment, DURATION, SLOTS, START_HEIGHT,
};
use teos_common::cryptography::{self, get_random_keypair};
#[tokio::test]
async fn test_get_all_appointments() {
let internal_api = create_api().await;
let response = internal_api
.get_all_appointments(Request::new(()))
.await
.unwrap()
.into_inner();
assert!(matches!(response, msgs::GetAllAppointmentsResponse { .. }))
}
#[tokio::test]
async fn test_get_all_appointments_watcher() {
let internal_api = create_api().await;
// Add data to the Watcher so we can retrieve it later on
let (user_sk, user_pk) = get_random_keypair();
internal_api.watcher.register(UserId(user_pk)).unwrap();
let appointment = generate_dummy_appointment(None).inner;
let user_signature = cryptography::sign(&appointment.serialize(), &user_sk).unwrap();
internal_api
.watcher
.add_appointment(appointment.clone(), user_signature)
.unwrap();
let response = internal_api
.get_all_appointments(Request::new(()))
.await
.unwrap()
.into_inner();
assert_eq!(response.appointments.len(), 1);
assert!(matches!(
response.appointments[0].appointment_data,
Some(msgs::appointment_data::AppointmentData::Appointment { .. })
));
}
#[tokio::test]
async fn test_get_all_appointments_responder() {
let internal_api = create_api().await;
// Add data to the Responser so we can retrieve it later on
let (_, user_pk) = get_random_keypair();
let user_id = UserId(user_pk);
internal_api.watcher.register(user_id).unwrap();
let appointment = generate_dummy_appointment(None).inner;
internal_api
.watcher
.add_random_tracker_to_responder(UUID::new(appointment.locator, user_id));
let response = internal_api
.get_all_appointments(Request::new(()))
.await
.unwrap()
.into_inner();
assert_eq!(response.appointments.len(), 1);
assert!(matches!(
response.appointments[0].appointment_data,
Some(msgs::appointment_data::AppointmentData::Tracker { .. })
));
}
#[tokio::test]
async fn test_get_tower_info_empty() {
let internal_api = create_api().await;
let response = internal_api
.get_tower_info(Request::new(()))
.await
.unwrap()
.into_inner();
assert_eq!(response.tower_id, internal_api.watcher.tower_id.serialize());
assert_eq!(response.n_registered_users, 0);
assert_eq!(response.n_watcher_appointments, 0);
assert_eq!(response.n_responder_trackers, 0);
}
#[tokio::test]
async fn test_get_tower_info() {
let internal_api = create_api().await;
// Register a user
let (user_sk, user_pk) = get_random_keypair();
let user_id = UserId(user_pk);
internal_api.watcher.register(user_id).unwrap();
// Add data to the Watcher
for _ in 0..2 {
let appointment = generate_dummy_appointment(None).inner;
let user_signature = cryptography::sign(&appointment.serialize(), &user_sk).unwrap();
internal_api
.watcher
.add_appointment(appointment.clone(), user_signature)
.unwrap();
}
// And the Responder
for _ in 0..3 {
let appointment = generate_dummy_appointment(None).inner;
internal_api
.watcher
.add_random_tracker_to_responder(UUID::new(appointment.locator, user_id));
}
let response = internal_api
.get_tower_info(Request::new(()))
.await
.unwrap()
.into_inner();
// Given get_tower_info checks data in memory, the data added to the Responder in the test won't be added to the Watcher too.
assert_eq!(response.tower_id, internal_api.watcher.tower_id.serialize());
assert_eq!(response.n_registered_users, 1);
assert_eq!(response.n_watcher_appointments, 2);
assert_eq!(response.n_responder_trackers, 3);
}
#[tokio::test]
async fn test_get_users() {
let internal_api = create_api().await;
let mut users = HashSet::new();
// Add a couple of users
for _ in 0..2 {
let (_, user_pk) = get_random_keypair();
let user_id = UserId(user_pk);
internal_api.watcher.register(user_id).unwrap();
users.insert(user_id.serialize());
}
let response = internal_api
.get_users(Request::new(()))
.await
.unwrap()
.into_inner();
assert_eq!(HashSet::from_iter(response.user_ids), users);
}
#[tokio::test]
async fn test_get_users_empty() {
let internal_api = create_api().await;
let response = internal_api
.get_users(Request::new(()))
.await
.unwrap()
.into_inner();
assert!(response.user_ids.is_empty());
}
#[tokio::test]
async fn test_get_user() {
let internal_api = create_api().await;
// Register a user and get it back
let (user_sk, user_pk) = get_random_keypair();
let user_id = UserId(user_pk);
internal_api.watcher.register(user_id).unwrap();
let response = internal_api
.get_user(Request::new(msgs::GetUserRequest {
user_id: user_id.serialize(),
}))
.await
.unwrap()
.into_inner();
assert_eq!(response.available_slots, SLOTS);
assert_eq!(response.subscription_expiry, START_HEIGHT as u32 + DURATION);
assert!(response.appointments.is_empty());
// Add an appointment and check back
let appointment = generate_dummy_appointment(None).inner;
let uuid = UUID::new(appointment.locator, user_id);
let user_signature = cryptography::sign(&appointment.serialize(), &user_sk).unwrap();
internal_api
.watcher
.add_appointment(appointment.clone(), user_signature)
.unwrap();
let response = internal_api
.get_user(Request::new(msgs::GetUserRequest {
user_id: user_id.serialize(),
}))
.await
.unwrap()
.into_inner();
assert_eq!(response.available_slots, SLOTS - 1);
assert_eq!(response.subscription_expiry, START_HEIGHT as u32 + DURATION);
assert_eq!(response.appointments, Vec::from([uuid.serialize()]));
}
#[tokio::test]
async fn test_get_user_not_found() {
let internal_api = create_api().await;
// Non-registered user
let (_, user_pk) = get_random_keypair();
match internal_api
.get_user(Request::new(msgs::GetUserRequest {
user_id: UserId(user_pk).serialize(),
}))
.await
{
Err(status) => {
assert_eq!(status.code(), Code::NotFound);
assert_eq!(status.message(), "User not found")
}
_ => panic!("Test should have returned Err"),
}
}
#[tokio::test]
async fn test_stop() {
let internal_api = create_api().await;
assert!(!internal_api.shutdown_trigger.is_triggered());
internal_api.stop(Request::new(())).await.unwrap();
assert!(internal_api.shutdown_trigger.is_triggered());
}
}
#[cfg(test)]
mod tests_public_api {
use super::*;
use crate::extended_appointment::UUID;
use crate::test_utils::{
create_api, create_api_with_config, generate_dummy_appointment, ApiConfig, DURATION, SLOTS,
};
use teos_common::cryptography::{self, get_random_keypair};
#[tokio::test]
async fn test_register() {
let internal_api = create_api().await;
let (_, user_pk) = get_random_keypair();
// Registering (even multiple times) should work
for _ in 0..2 {
let response = internal_api
.register(Request::new(msgs::RegisterRequest {
user_id: UserId(user_pk).serialize(),
}))
.await
.unwrap()
.into_inner();
assert!(matches!(response, msgs::RegisterResponse { .. }))
}
}
#[tokio::test]
async fn test_register_wrong_user_id() {
let internal_api = create_api().await;
let mut user_ids = Vec::new();
// Wrong user id size
let (_, user_pk) = get_random_keypair();
let mut user_id_vec = UserId(user_pk).serialize();
user_id_vec.pop();
user_ids.push(user_id_vec);
// Wrong format (does not start with 2 nor 3)
user_id_vec = UserId(user_pk).serialize();
user_id_vec[0] = 1;
user_ids.push(user_id_vec);
for user_id in user_ids {
match internal_api
.register(Request::new(msgs::RegisterRequest { user_id }))
.await
{
Err(status) => {
assert_eq!(status.code(), Code::InvalidArgument);
assert_eq!(status.message(), "Provided public key does not match expected format (33-byte compressed key)")
}
_ => panic!("Test should have returned Err"),
}
}
}
#[tokio::test]
async fn test_register_max_slots() {
let internal_api = create_api_with_config(ApiConfig::new(u32::MAX, DURATION)).await;
let (_, user_pk) = get_random_keypair();
let user_id = UserId(user_pk).serialize();
// First registration should go trough
internal_api
.register(Request::new(msgs::RegisterRequest {
user_id: user_id.clone(),
}))
.await
.unwrap();
// Trying to add more slots (re-register) must fail
match internal_api
.register(Request::new(msgs::RegisterRequest { user_id }))
.await
{
Err(status) => {
assert_eq!(status.code(), Code::ResourceExhausted);
assert_eq!(status.message(), "Subscription maximum slots count reached")
}
_ => panic!("Test should have returned Err"),
}
}
#[tokio::test]
async fn test_register_service_unavailable() {
let internal_api =
create_api_with_config(ApiConfig::new(u32::MAX, DURATION).bitcoind_unreachable()).await;
let (_, user_pk) = get_random_keypair();
let user_id = UserId(user_pk).serialize();
match internal_api
.register(Request::new(msgs::RegisterRequest { user_id }))
.await
{
Err(status) => {
assert_eq!(status.code(), Code::Unavailable);
assert_eq!(status.message(), "Service currently unavailable")
}
_ => panic!("Test should have returned Err"),
}
}
#[tokio::test]
async fn test_add_appointment() {
let internal_api = create_api().await;
// User must be registered
let (user_sk, user_pk) = get_random_keypair();
internal_api.watcher.register(UserId(user_pk)).unwrap();
let appointment = generate_dummy_appointment(None).inner;
let user_signature = cryptography::sign(&appointment.serialize(), &user_sk).unwrap();
let response = internal_api
.add_appointment(Request::new(msgs::AddAppointmentRequest {
appointment: Some(appointment.clone().into()),
signature: user_signature.clone(),
}))
.await
.unwrap()
.into_inner();
assert!(matches!(response, msgs::AddAppointmentResponse { .. }));
}
#[tokio::test]
async fn test_add_appointment_non_registered() {
let internal_api = create_api().await;
// User is not registered this time
let (user_sk, _) = get_random_keypair();
let appointment = generate_dummy_appointment(None).inner;
let user_signature = cryptography::sign(&appointment.serialize(), &user_sk).unwrap();
match internal_api
.add_appointment(Request::new(msgs::AddAppointmentRequest {
appointment: Some(appointment.clone().into()),
signature: user_signature.clone(),
}))
.await
{
Err(status) => {
assert_eq!(status.code(), Code::Unauthenticated);
assert_eq!(
status.message(),
"Invalid signature or user does not have enough slots available"
)
}
_ => panic!("Test should have returned Err"),
}
}
#[tokio::test]
async fn test_add_appointment_not_enough_slots() {
let internal_api = create_api_with_config(ApiConfig::new(0, DURATION)).await;
// User is registered but has no slots
let (user_sk, user_pk) = get_random_keypair();
internal_api.watcher.register(UserId(user_pk)).unwrap();
let appointment = generate_dummy_appointment(None).inner;
let user_signature = cryptography::sign(&appointment.serialize(), &user_sk).unwrap();
match internal_api
.add_appointment(Request::new(msgs::AddAppointmentRequest {
appointment: Some(appointment.clone().into()),
signature: user_signature.clone(),
}))
.await
{
Err(status) => {
assert_eq!(status.code(), Code::Unauthenticated);
assert_eq!(
status.message(),
"Invalid signature or user does not have enough slots available"
)
}
_ => panic!("Test should have returned Err"),
}
}
#[tokio::test]
async fn test_add_appointment_subscription_expired() {
let internal_api = create_api_with_config(ApiConfig::new(SLOTS, 0)).await;
// User is registered but subscription is expired
let (user_sk, user_pk) = get_random_keypair();
internal_api.watcher.register(UserId(user_pk)).unwrap();
let appointment = generate_dummy_appointment(None).inner;
let user_signature = cryptography::sign(&appointment.serialize(), &user_sk).unwrap();
match internal_api
.add_appointment(Request::new(msgs::AddAppointmentRequest {
appointment: Some(appointment.clone().into()),
signature: user_signature.clone(),
}))
.await
{
Err(status) => {
assert_eq!(status.code(), Code::Unauthenticated);
assert!(status.message().starts_with("Your subscription expired at"),)
}
_ => panic!("Test should have returned Err"),
}
}
#[tokio::test]
async fn test_add_appointment_already_triggered() {
let internal_api = create_api().await;
let (user_sk, user_pk) = get_random_keypair();
let user_id = UserId(user_pk);
internal_api.watcher.register(user_id).unwrap();
let appointment = generate_dummy_appointment(None).inner;
let user_signature = cryptography::sign(&appointment.serialize(), &user_sk).unwrap();
internal_api
.watcher
.add_random_tracker_to_responder(UUID::new(appointment.locator, user_id));
match internal_api
.add_appointment(Request::new(msgs::AddAppointmentRequest {
appointment: Some(appointment.clone().into()),
signature: user_signature.clone(),
}))
.await
{
Err(status) => {
assert_eq!(status.code(), Code::AlreadyExists);
assert!(status
.message()
.starts_with("The provided appointment has already been triggered"),)
}
_ => panic!("Test should have returned Err"),
}
}
#[tokio::test]
async fn test_add_appointment_service_unavailable() {
let internal_api =
create_api_with_config(ApiConfig::new(u32::MAX, DURATION).bitcoind_unreachable()).await;
let (user_sk, _) = get_random_keypair();
let appointment = generate_dummy_appointment(None).inner;
let user_signature = cryptography::sign(&appointment.serialize(), &user_sk).unwrap();
match internal_api
.add_appointment(Request::new(msgs::AddAppointmentRequest {
appointment: Some(appointment.clone().into()),
signature: user_signature.clone(),
}))
.await
{
Err(status) => {
assert_eq!(status.code(), Code::Unavailable);
assert_eq!(status.message(), "Service currently unavailable")
}
_ => panic!("Test should have returned Err"),
}
}
#[tokio::test]
async fn test_get_appointment() {
let internal_api = create_api().await;
// The user must be registered
let (user_sk, user_pk) = get_random_keypair();
internal_api.watcher.register(UserId(user_pk)).unwrap();
// Add the appointment
let appointment = generate_dummy_appointment(None).inner;
let user_signature = cryptography::sign(&appointment.serialize(), &user_sk).unwrap();
internal_api
.watcher
.add_appointment(appointment.clone(), user_signature)
.unwrap();
// Get the appointment through the API
let message = format!("get appointment {}", appointment.locator);
let response = internal_api
.get_appointment(Request::new(msgs::GetAppointmentRequest {
locator: appointment.locator.serialize(),
signature: cryptography::sign(message.as_bytes(), &user_sk).unwrap(),
}))
.await
.unwrap()
.into_inner();
assert!(matches!(response, msgs::GetAppointmentResponse { .. }))
}
#[tokio::test]
async fn test_get_appointment_non_registered() {
let internal_api = create_api().await;
// Add a first user to link the appointment to him
let (user_sk, user_pk) = get_random_keypair();
internal_api.watcher.register(UserId(user_pk)).unwrap();
// There's no need to add the appointment given the subscription status is checked first
let appointment = generate_dummy_appointment(None).inner;
// Try to get the appointment through the API
let message = format!("get appointment {}", appointment.locator);
match internal_api
.get_appointment(Request::new(msgs::GetAppointmentRequest {
locator: appointment.locator.serialize(),
signature: cryptography::sign(message.as_bytes(), &user_sk).unwrap(),
}))
.await
{
Err(status) => {
assert_eq!(status.code(), Code::NotFound);
assert_eq!(status.message(), "Appointment not found");
}
_ => panic!("Test should have returned Err"),
}
}
#[tokio::test]
async fn test_get_appointment_non_existent() {
let internal_api = create_api().await;
// The user is registered but the appointment does not exist
let (user_sk, user_pk) = get_random_keypair();
internal_api.watcher.register(UserId(user_pk)).unwrap();
// Try to get the appointment through the API
let appointment = generate_dummy_appointment(None).inner;
let message = format!("get appointment {}", appointment.locator);
match internal_api
.get_appointment(Request::new(msgs::GetAppointmentRequest {
locator: appointment.locator.serialize(),
signature: cryptography::sign(message.as_bytes(), &user_sk).unwrap(),
}))
.await
{
Err(status) => {
assert_eq!(status.code(), Code::NotFound);
assert_eq!(status.message(), "Appointment not found");
}
_ => panic!("Test should have returned Err"),
}
}
#[tokio::test]
async fn test_get_appointment_subscription_expired() {
let internal_api = create_api_with_config(ApiConfig::new(SLOTS, 0)).await;
// Register the user
let (user_sk, user_pk) = get_random_keypair();
internal_api.watcher.register(UserId(user_pk)).unwrap();
// There s no need to add the appointment given the subscription status is checked first.
let appointment = generate_dummy_appointment(None).inner;
// Try to get the appointment through the API
let message = format!("get appointment {}", appointment.locator);
match internal_api
.get_appointment(Request::new(msgs::GetAppointmentRequest {
locator: appointment.locator.serialize(),
signature: cryptography::sign(message.as_bytes(), &user_sk).unwrap(),
}))
.await
{
Err(status) => {
assert_eq!(status.code(), Code::Unauthenticated);
assert!(status.message().starts_with("Your subscription expired at"));
}
_ => panic!("Test should have returned Err"),
}
}
#[tokio::test]
async fn test_get_appointment_service_unavailable() {
let internal_api =
create_api_with_config(ApiConfig::new(SLOTS, DURATION).bitcoind_unreachable()).await;
let (user_sk, _) = get_random_keypair();
let appointment = generate_dummy_appointment(None).inner;
let message = format!("get appointment {}", appointment.locator);
match internal_api
.get_appointment(Request::new(msgs::GetAppointmentRequest {
locator: appointment.locator.serialize(),
signature: cryptography::sign(message.as_bytes(), &user_sk).unwrap(),
}))
.await
{
Err(status) => {
assert_eq!(status.code(), Code::Unavailable);
assert_eq!(status.message(), "Service currently unavailable");
}
_ => panic!("Test should have returned Err"),
}
}
#[tokio::test]
async fn test_get_subscription_info() {
let internal_api = create_api().await;
// The user must be registered
let (user_sk, user_pk) = get_random_keypair();
internal_api.watcher.register(UserId(user_pk)).unwrap();
// Get the subscription info though the API
let message = "get subscription info".to_string();
let response = internal_api
.get_subscription_info(Request::new(msgs::GetSubscriptionInfoRequest {
signature: cryptography::sign(message.as_bytes(), &user_sk).unwrap(),
}))
.await
.unwrap()
.into_inner();
assert!(matches!(response, msgs::GetSubscriptionInfoResponse { .. }))
}
#[tokio::test]
async fn test_get_subscription_info_non_registered() {
let internal_api = create_api_with_config(ApiConfig::new(SLOTS, 0)).await;