-
Notifications
You must be signed in to change notification settings - Fork 57
Expand file tree
/
Copy pathmessages.rs
More file actions
1151 lines (956 loc) · 31.2 KB
/
Copy pathmessages.rs
File metadata and controls
1151 lines (956 loc) · 31.2 KB
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::{
collections::{HashMap, HashSet},
fmt,
fmt::Debug,
marker::Send,
net::SocketAddr,
ops::{Bound, RangeBounds},
time::Duration,
};
use actix::{
dev::{MessageResponse, OneshotSender, ToEnvelope},
Actor, Addr, Handler, Message,
};
use serde::{Deserialize, Serialize};
use tokio::net::TcpStream;
use witnet_data_structures::{
chain::{
Block, CheckpointBeacon, DataRequestInfo, DataRequestOutput, Epoch, EpochConstants, Hash,
InventoryEntry, InventoryItem, NodeStats, PointerToBlock, PublicKeyHash, RADRequest,
RADTally, Reputation, StateMachine, SuperBlock, SuperBlockVote, SupplyInfo,
ValueTransferOutput,
},
mainnet_validations::{ActiveWips, BitVotesCounter},
radon_report::RadonReport,
transaction::{CommitTransaction, RevealTransaction, Transaction},
transaction_factory::NodeBalance,
types::LastBeacon,
utxo_pool::{UtxoInfo, UtxoSelectionStrategy},
};
use witnet_p2p::{
error::SessionsError,
sessions::{GetConsolidatedPeersResult, SessionStatus, SessionType},
};
use witnet_rad::{error::RadError, types::RadonTypes};
use super::{
chain_manager::{ChainManagerError, MAX_BLOCKS_SYNC},
connections_manager::resolver::ResolverError,
epoch_manager::{
AllEpochSubscription, EpochManagerError, SendableNotification, SingleEpochSubscription,
},
inventory_manager::InventoryManagerError,
rad_manager::RadManager,
session::Session,
};
////////////////////////////////////////////////////////////////////////////////////////
// MESSAGES FROM CHAIN MANAGER
////////////////////////////////////////////////////////////////////////////////////////
/// Message result of unit
pub type SessionUnitResult = ();
/// Message to obtain the highest block checkpoint managed by the `ChainManager`
/// actor.
pub struct GetHighestCheckpointBeacon;
impl Message for GetHighestCheckpointBeacon {
type Result = Result<CheckpointBeacon, failure::Error>;
}
/// Message to obtain the last super block votes managed by the `ChainManager`
/// actor.
pub struct GetSuperBlockVotes;
impl Message for GetSuperBlockVotes {
type Result = Result<HashSet<SuperBlockVote>, failure::Error>;
}
/// Add a new block
pub struct AddBlocks {
/// Blocks
pub blocks: Vec<Block>,
/// Sender peer
pub sender: Option<SocketAddr>,
}
impl Message for AddBlocks {
type Result = SessionUnitResult;
}
/// Add a new candidate
pub struct AddCandidates {
/// Candidates
pub blocks: Vec<Block>,
}
impl Message for AddCandidates {
type Result = SessionUnitResult;
}
/// Add a superblock vote
pub struct AddSuperBlockVote {
/// Superblock vote
pub superblock_vote: SuperBlockVote,
}
impl Message for AddSuperBlockVote {
type Result = Result<(), failure::Error>;
}
/// Add a new transaction
pub struct AddTransaction {
/// Transaction
pub transaction: Transaction,
/// Broadcasting flag
pub broadcast_flag: bool,
}
impl Message for AddTransaction {
type Result = Result<(), failure::Error>;
}
/// Ask for a block identified by its hash
pub struct GetBlock {
/// Block hash
pub hash: Hash,
}
impl Message for GetBlock {
type Result = Result<Block, ChainManagerError>;
}
/// Message to obtain a vector of block hashes using a range of epochs
pub struct GetBlocksEpochRange {
/// Range of Epochs (prefer using the new method to create a range)
pub range: (Bound<Epoch>, Bound<Epoch>),
/// Maximum blocks limit. 0 means unlimited
pub limit: usize,
/// Whether to apply the limit from the end: return the last n blocks
pub limit_from_end: bool,
}
impl GetBlocksEpochRange {
/// Create a GetBlockEpochRange message using range syntax:
///
/// ```rust
/// # use witnet_node::actors::messages::GetBlocksEpochRange;
/// GetBlocksEpochRange::new(..); // Unbounded range: all items
/// GetBlocksEpochRange::new(10..); // All items starting from epoch 10
/// GetBlocksEpochRange::new(..10); // All items up to epoch 10 (10 excluded)
/// GetBlocksEpochRange::new(..=9); // All items up to epoch 9 inclusive (same as above)
/// GetBlocksEpochRange::new(4..=4); // Only epoch 4
/// ```
pub fn new<R: RangeBounds<Epoch>>(r: R) -> Self {
Self::new_with_limit(r, 0)
}
/// new method with a constant limit
pub fn new_with_const_limit<R: RangeBounds<Epoch>>(r: R) -> Self {
Self::new_with_limit(r, MAX_BLOCKS_SYNC)
}
/// new method with a specified limit
pub fn new_with_limit<R: RangeBounds<Epoch>>(r: R, limit: usize) -> Self {
// Manually implement `cloned` method
let cloned = |b: Bound<&Epoch>| match b {
Bound::Included(x) => Bound::Included(*x),
Bound::Excluded(x) => Bound::Excluded(*x),
Bound::Unbounded => Bound::Unbounded,
};
Self {
range: (cloned(r.start_bound()), cloned(r.end_bound())),
limit,
limit_from_end: false,
}
}
/// new method with a specified limit, returning the last `limit` items
pub fn new_with_limit_from_end<R: RangeBounds<Epoch>>(r: R, limit: usize) -> Self {
let mut rb = Self::new_with_limit(r, limit);
rb.limit_from_end = true;
rb
}
}
impl Message for GetBlocksEpochRange {
type Result = Result<Vec<(Epoch, Hash)>, ChainManagerError>;
}
/// A list of peers and their respective last beacon, used to establish consensus
pub struct PeersBeacons {
/// A list of peers and their respective last beacon
pub pb: Vec<(SocketAddr, Option<LastBeacon>)>,
/// Outbound limit: how many beacons did we expect in total
pub outbound_limit: Option<u16>,
}
impl Message for PeersBeacons {
/// Result: list of peers out of consensus which will be unregistered
type Result = Result<Vec<SocketAddr>, ()>;
}
/// Builds a `ValueTransferTransaction` from a list of `ValueTransferOutput`s
#[derive(Clone, Debug, Default, Hash, Eq, PartialEq, Serialize, Deserialize)]
pub struct BuildVtt {
/// List of `ValueTransferOutput`s
pub vto: Vec<ValueTransferOutput>,
/// Fee
pub fee: u64,
/// Strategy to sort the unspent outputs pool
#[serde(default)]
pub utxo_strategy: UtxoSelectionStrategy,
}
impl Message for BuildVtt {
type Result = Result<Hash, failure::Error>;
}
/// Builds a `DataRequestTransaction` from a `DataRequestOutput`
#[derive(Clone, Debug, Default, Hash, Eq, PartialEq, Serialize, Deserialize)]
pub struct BuildDrt {
/// `DataRequestOutput`
pub dro: DataRequestOutput,
/// Fee
pub fee: u64,
}
impl Message for BuildDrt {
type Result = Result<Hash, failure::Error>;
}
/// Get ChainManager State (WaitingConsensus, Synchronizing, AlmostSynced, Synced)
#[derive(Clone, Debug, Default, Hash, Eq, PartialEq, Serialize, Deserialize)]
pub struct GetState;
impl Message for GetState {
type Result = Result<StateMachine, ()>;
}
/// Get Data Request Info
#[derive(Clone, Debug, Default, Hash, Eq, PartialEq, Serialize, Deserialize)]
pub struct GetDataRequestInfo {
/// `DataRequest` transaction hash
pub dr_pointer: Hash,
}
impl Message for GetDataRequestInfo {
type Result = Result<DataRequestInfo, failure::Error>;
}
/// Get Balance
#[derive(Clone, Debug, Default, Hash, Eq, PartialEq, Serialize, Deserialize)]
pub struct GetBalance {
/// Public key hash
pub pkh: PublicKeyHash,
/// Distinguish between fetching a simple balance or fetching confirmed and unconfirmed balance
pub simple: bool,
}
impl Message for GetBalance {
type Result = Result<NodeBalance, failure::Error>;
}
/// Get Supply
#[derive(Clone, Debug, Default, Hash, Eq, PartialEq, Serialize, Deserialize)]
pub struct GetSupplyInfo;
impl Message for GetSupplyInfo {
type Result = Result<SupplyInfo, failure::Error>;
}
/// Get Balance
#[derive(Clone, Debug, Default, Hash, Eq, PartialEq, Serialize, Deserialize)]
pub struct GetUtxoInfo {
/// Public key hash
pub pkh: PublicKeyHash,
}
impl Message for GetUtxoInfo {
type Result = Result<UtxoInfo, failure::Error>;
}
/// Reputation info
#[derive(Clone, Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
pub struct ReputationStats {
/// Reputation
pub reputation: Reputation,
/// Eligibility: Trapezoidal reputation based on ranking
pub eligibility: u32,
/// Is active flag
pub is_active: bool,
}
/// GetReputation result
#[derive(Clone, Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
pub struct GetReputationResult {
/// Map of identity public key hash to reputation stats
pub stats: HashMap<PublicKeyHash, ReputationStats>,
/// Total active reputation
pub total_reputation: u64,
}
/// Get reputation of one identity if `all` is set to `false`,
/// or all identities if `all` is set to `true`
#[derive(Clone, Debug, Default, Hash, Eq, PartialEq, Serialize, Deserialize)]
pub struct GetReputation {
/// Public key hash
pub pkh: PublicKeyHash,
/// All flag
pub all: bool,
}
impl Message for GetReputation {
type Result = Result<GetReputationResult, failure::Error>;
}
/// Get all the pending transactions
#[derive(Clone, Debug, Default, Hash, Eq, PartialEq, Serialize, Deserialize)]
pub struct GetMempool;
impl Message for GetMempool {
type Result = Result<GetMempoolResult, failure::Error>;
}
/// Result of GetMempool message: list of pending transactions categorized by type
#[derive(Serialize)]
pub struct GetMempoolResult {
/// Pending value transfer transactions
pub value_transfer: Vec<Hash>,
/// Pending data request transactions
pub data_request: Vec<Hash>,
}
/// Try to mine a block: signal the ChainManager to check if it can produce a new block
#[derive(Clone, Debug, Default, Hash, Eq, PartialEq, Serialize, Deserialize)]
pub struct TryMineBlock;
impl Message for TryMineBlock {
type Result = ();
}
/// Add a commit-reveal pair to ChainManager.
/// This will broadcast the commit and save the reveal for later
#[derive(Clone, Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
pub struct AddCommitReveal {
/// Signed commit transaction
pub commit_transaction: CommitTransaction,
/// Signed reveal transaction for the commit transaction
pub reveal_transaction: RevealTransaction,
}
impl Message for AddCommitReveal {
type Result = Result<(), failure::Error>;
}
/// Get transaction from mempool by hash
pub struct GetMemoryTransaction {
/// item hash
pub hash: Hash,
}
impl Message for GetMemoryTransaction {
type Result = Result<Transaction, ()>;
}
/// Used to set the target superblock needed for synchronization
pub struct AddSuperBlock {
/// Superblock
pub superblock: SuperBlock,
}
impl Message for AddSuperBlock {
type Result = ();
}
/// Returns true if the provided block hash is the consolidated block for the provided epoch, and
/// there exists a superblock with a majority of votes to confirm that.
pub struct IsConfirmedBlock {
/// Block hash
pub block_hash: Hash,
/// Block checkpoint
pub block_epoch: u32,
}
impl Message for IsConfirmedBlock {
type Result = Result<bool, failure::Error>;
}
/// Additional configuration for the rewind method
#[derive(Debug, Default, Clone, Deserialize, Serialize)]
pub struct RewindMode {
/// Validate block and transaction signatures
#[serde(default)]
pub validate_signatures: bool,
/// Write all the blocks, transactions, and data request reports to storage, regardless of
/// whether they already exist or not
#[serde(default)]
pub write_items_to_storage: bool,
}
/// Rewind chain state back to some epoch
#[derive(Debug, Default, Clone, Deserialize, Serialize)]
pub struct Rewind {
/// Epoch of the last block that will be consolidated by the rewind method
#[serde(default)]
pub epoch: Option<Epoch>,
/// Additional configuration for the rewind method
#[serde(default)]
pub mode: RewindMode,
}
impl Message for Rewind {
type Result = Result<bool, failure::Error>;
}
////////////////////////////////////////////////////////////////////////////////////////
// MESSAGES FROM CONNECTIONS MANAGER
////////////////////////////////////////////////////////////////////////////////////////
/// Actor message that holds the TCP stream from an inbound TCP connection
pub struct InboundTcpConnect {
/// Tcp stream of the inbound connections
pub stream: TcpStream,
}
impl Message for InboundTcpConnect {
type Result = ();
}
impl InboundTcpConnect {
/// Method to create a new InboundTcpConnect message from a TCP stream
pub fn new(stream: TcpStream) -> InboundTcpConnect {
InboundTcpConnect { stream }
}
}
/// Actor message to request the creation of an outbound TCP connection to a peer.
pub struct OutboundTcpConnect {
/// Address of the outbound connection
pub address: SocketAddr,
/// Flag to indicate if it is a peers provided from the feeler function
pub session_type: SessionType,
}
impl Message for OutboundTcpConnect {
type Result = ();
}
/// Returned type by the Resolver actor for the ConnectAddr message
pub type ResolverResult = Result<TcpStream, ResolverError>;
////////////////////////////////////////////////////////////////////////////////////////
// MESSAGES FROM EPOCH MANAGER
////////////////////////////////////////////////////////////////////////////////////////
/// Returns the current epoch
pub struct GetEpoch;
/// Epoch result
pub type EpochResult<T> = Result<T, EpochManagerError>;
impl Message for GetEpoch {
type Result = EpochResult<Epoch>;
}
/// Subscribe
pub struct Subscribe;
/// Subscribe to a single checkpoint
pub struct SubscribeEpoch {
/// Checkpoint to be subscribed to
pub checkpoint: Epoch,
/// Notification to be sent when the checkpoint is reached
pub notification: Box<dyn SendableNotification>,
}
impl Message for SubscribeEpoch {
type Result = ();
}
/// Subscribe to all new checkpoints
pub struct SubscribeAll {
/// Notification
pub notification: Box<dyn SendableNotification>,
}
impl Message for SubscribeAll {
type Result = ();
}
impl Subscribe {
/// Subscribe to a specific checkpoint to get an EpochNotification
// TODO: rename to to_checkpoint?
// TODO: add helper Subscribe::to_next_epoch?
// TODO: helper to subscribe to nth epoch in the future
#[allow(clippy::wrong_self_convention)]
pub fn to_epoch<T, U>(checkpoint: Epoch, addr: Addr<U>, payload: T) -> SubscribeEpoch
where
T: 'static + Send,
U: Actor + Handler<EpochNotification<T>>,
U::Context: ToEnvelope<U, EpochNotification<T>>,
{
SubscribeEpoch {
checkpoint,
notification: Box::new(SingleEpochSubscription {
recipient: addr.recipient(),
payload: Some(payload),
}),
}
}
/// Subscribe to all checkpoints to get an EpochNotification on every new epoch
#[allow(clippy::wrong_self_convention)]
pub fn to_all<T, U>(addr: Addr<U>, payload: T) -> SubscribeAll
where
T: 'static + Send + Clone,
U: Actor + Handler<EpochNotification<T>>,
U::Context: ToEnvelope<U, EpochNotification<T>>,
{
SubscribeAll {
notification: Box::new(AllEpochSubscription {
recipient: addr.recipient(),
payload,
}),
}
}
}
/// Message that the EpochManager sends to subscriber actors to notify a new epoch
pub struct EpochNotification<T: Send> {
/// Epoch that has just started
pub checkpoint: Epoch,
/// Timestamp of the start of the epoch.
/// This is used to verify that the messages arrive on time
pub timestamp: i64,
/// Payload for the epoch notification
pub payload: T,
}
impl<T: Send> Message for EpochNotification<T> {
type Result = ();
}
/// Return a function which can be used to calculate the timestamp for a
/// checkpoint (the start of an epoch). This assumes that the
/// checkpoint_zero_timestamp and checkpoints_period constants never change
pub struct GetEpochConstants;
impl Message for GetEpochConstants {
type Result = Option<EpochConstants>;
}
////////////////////////////////////////////////////////////////////////////////////////
// MESSAGES FROM INVENTORY MANAGER
////////////////////////////////////////////////////////////////////////////////////////
/// Inventory element: block, txns
#[derive(Debug, Eq, PartialEq, Clone)]
pub enum StoreInventoryItem {
/// Blocks are stored with all the transactions inside
Block(Box<Block>),
/// Transactions are stored as pointers to blocks
Transaction(Hash, PointerToBlock),
/// Superblocks are stored as the list of block hashes
Superblock(SuperBlockNotify),
}
/// Add a new item
pub struct AddItem {
/// Item
pub item: StoreInventoryItem,
}
impl Message for AddItem {
type Result = Result<(), InventoryManagerError>;
}
/// Add a new item
pub struct AddItems {
/// Item
pub items: Vec<StoreInventoryItem>,
}
impl Message for AddItems {
type Result = Result<(), InventoryManagerError>;
}
/// Ask for an item identified by its hash
pub struct GetItem {
/// item kind and hash
pub item: InventoryEntry,
}
impl Message for GetItem {
type Result = Result<InventoryItem, InventoryManagerError>;
}
/// Ask for an item identified by its hash
pub struct GetItemBlock {
/// item hash
pub hash: Hash,
}
impl Message for GetItemBlock {
type Result = Result<Block, InventoryManagerError>;
}
/// Ask for an item identified by its hash
pub struct GetItemTransaction {
/// item hash
pub hash: Hash,
}
impl Message for GetItemTransaction {
type Result = Result<(Transaction, PointerToBlock, Epoch), InventoryManagerError>;
}
/// Ask for a superblock identified by its index
pub struct GetItemSuperblock {
/// item hash
pub superblock_index: u32,
}
impl Message for GetItemSuperblock {
type Result = Result<SuperBlockNotify, InventoryManagerError>;
}
/// Get TAPI Signaling Info
pub struct GetSignalingInfo {}
/// Result of GetSignalingInfo
#[derive(Deserialize, Serialize)]
pub struct SignalingInfo {
/// List of protocol upgrades that are already active, and their activation epoch
pub active_upgrades: HashMap<String, Epoch>,
/// List of protocol upgrades that are currently being polled for activation signaling
pub pending_upgrades: Vec<BitVotesCounter>,
/// Last epoch
pub epoch: Epoch,
}
impl Message for GetSignalingInfo {
type Result = Result<SignalingInfo, failure::Error>;
}
////////////////////////////////////////////////////////////////////////////////////////
// MESSAGES FROM PEERS MANAGER
////////////////////////////////////////////////////////////////////////////////////////
/// One peer
pub type PeersSocketAddrResult = Result<Option<SocketAddr>, failure::Error>;
/// One or more peer addresses
pub type PeersSocketAddrsResult = Result<Vec<SocketAddr>, failure::Error>;
/// Message to add one or more peer addresses to the list
pub struct AddPeers {
/// Addresses of the peer
pub addresses: Vec<SocketAddr>,
/// Address of the peer that sent us this peers using the Peers protocol message, or None if
/// the peers were added from config or from command line
pub src_address: Option<SocketAddr>,
}
impl Message for AddPeers {
type Result = PeersSocketAddrsResult;
}
/// Message to clear peers from buckets
pub struct ClearPeers;
impl Message for ClearPeers {
type Result = Result<(), failure::Error>;
}
/// Message to clear peers from buckets and initialize to those in config
pub struct InitializePeers {
/// Peers with which to initialize the buckets
pub known_peers: Vec<SocketAddr>,
}
impl Message for InitializePeers {
type Result = Result<(), failure::Error>;
}
/// Message to add one peer address to the tried addresses bucket
pub struct AddConsolidatedPeer {
/// Tried addresses to add
pub address: SocketAddr,
}
impl Message for AddConsolidatedPeer {
type Result = PeersSocketAddrResult;
}
/// Message to remove one or more peer addresses from the list
pub struct RemoveAddressesFromTried {
/// Address of the peer
pub addresses: Vec<SocketAddr>,
/// Request the removed peer addresses to be iced
pub ice: bool,
}
impl Message for RemoveAddressesFromTried {
type Result = PeersSocketAddrsResult;
}
/// Message to get a (random) peer address from the list
pub struct GetRandomPeers {
/// Number of random peers
pub n: usize,
}
impl Message for GetRandomPeers {
type Result = PeersSocketAddrsResult;
}
/// Message to get all the peer addresses from the tried list
pub struct RequestPeers;
impl Message for RequestPeers {
type Result = PeersSocketAddrsResult;
}
/// Message to get all the peer addresses from the new and tried lists
pub struct GetKnownPeers;
impl Message for GetKnownPeers {
type Result = Result<PeersNewTried, failure::Error>;
}
/// Message to get node stats
pub struct GetNodeStats;
impl Message for GetNodeStats {
type Result = Result<NodeStats, failure::Error>;
}
/// List of known peers sorted by bucket
pub struct PeersNewTried {
/// Peers in new bucket
pub new: Vec<SocketAddr>,
/// Peers in tried bucket
pub tried: Vec<SocketAddr>,
}
////////////////////////////////////////////////////////////////////////////////////////
// MESSAGES FROM RAD MANAGER
////////////////////////////////////////////////////////////////////////////////////////
/// Message for resolving the request-aggregate step of a data
/// request.
#[derive(Debug)]
pub struct ResolveRA {
/// RAD request to be executed
pub rad_request: RADRequest,
/// Timeout: if the execution does not finish before the timeout, it is cancelled.
pub timeout: Option<Duration>,
/// Active Witnet protocol improvements as of the current epoch.
/// Used to select the correct version of the validation logic.
pub active_wips: ActiveWips,
}
/// Message for running the tally step of a data request.
#[derive(Debug)]
pub struct RunTally {
/// RAD tally to be executed
pub script: RADTally,
/// Reveals vector for tally
pub reports: Vec<RadonReport<RadonTypes>>,
/// Minimum values vs. errors ratio over which tally is run, otherwise return mode of errors
pub min_consensus_ratio: f64,
/// Number of commits
pub commits_count: usize,
/// Active Witnet protocol improvements as of the block that will include this tally.
/// Used to select the correct version of the validation logic.
pub active_wips: ActiveWips,
}
impl Message for ResolveRA {
type Result = Result<RadonReport<RadonTypes>, RadError>;
}
impl Message for RunTally {
type Result = RadonReport<RadonTypes>;
}
impl<M> MessageResponse<RadManager, M> for RadonReport<RadonTypes>
where
M: Message<Result = Self>,
{
fn handle(self, _: &mut <RadManager as Actor>::Context, tx: Option<OneshotSender<M::Result>>) {
if let Some(tx) = tx {
if let Err(_self) = tx.send(self) {
// TODO: can this ever happen?
log::error!("Failed to send RadonReport through OneshotSender channel");
}
}
}
}
////////////////////////////////////////////////////////////////////////////////////////
// MESSAGES FROM SESSION
////////////////////////////////////////////////////////////////////////////////////////
/// Message to indicate that the session needs to send a GetPeers message through the network
#[derive(Debug)]
pub struct SendGetPeers;
impl Message for SendGetPeers {
type Result = SessionUnitResult;
}
impl fmt::Display for SendGetPeers {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "SendGetPeers")
}
}
/// Message to announce new inventory entries through the network
#[derive(Clone, Debug)]
pub struct SendInventoryAnnouncement {
/// Inventory entries
pub items: Vec<InventoryEntry>,
}
impl Message for SendInventoryAnnouncement {
type Result = ();
}
impl fmt::Display for SendInventoryAnnouncement {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "SendInventoryAnnouncement")
}
}
/// Message to request new inventory entries through the network
#[derive(Clone, Debug)]
pub struct SendInventoryRequest {
/// Inventory entries
pub items: Vec<InventoryEntry>,
}
impl Message for SendInventoryRequest {
type Result = ();
}
impl fmt::Display for SendInventoryRequest {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "SendInventoryRequest")
}
}
/// Message to send inventory items through the network
#[derive(Clone, Debug)]
pub struct SendInventoryItem {
/// InventoryItem
pub item: InventoryItem,
}
impl Message for SendInventoryItem {
type Result = ();
}
impl fmt::Display for SendInventoryItem {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "SendInventoryItem")
}
}
/// Message to send beacon through the network
#[derive(Clone, Debug)]
pub struct SendLastBeacon {
/// Last block and superblock checkpoints
pub last_beacon: LastBeacon,
}
impl Message for SendLastBeacon {
type Result = ();
}
impl fmt::Display for SendLastBeacon {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "SendLastBeacon")
}
}
/// Message to send beacon through the network
#[derive(Clone, Debug)]
pub struct SendSuperBlockVote {
/// The superblock vote
pub superblock_vote: SuperBlockVote,
}
impl Message for SendSuperBlockVote {
type Result = ();
}
impl fmt::Display for SendSuperBlockVote {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "SendSuperBlockVote")
}
}
/// Message to close an open session
#[derive(Clone, Debug)]
pub struct CloseSession;
impl Message for CloseSession {
type Result = ();
}
////////////////////////////////////////////////////////////////////////////////////////
// MESSAGES FROM SESSIONS MANAGER
////////////////////////////////////////////////////////////////////////////////////////
/// Message result of unit
pub type SessionsUnitResult = Result<(), SessionsError>;
/// Message indicating a new session needs to be created
pub struct Create {
/// TCP stream
pub stream: TcpStream,
/// Session type
pub session_type: SessionType,
}
impl Message for Create {
type Result = ();
}
/// Message indicating a new session needs to be registered
pub struct Register {
/// Socket address which identifies the peer
pub address: SocketAddr,
/// Address of the session actor that is to be connected
pub actor: Addr<Session>,
/// Session type
pub session_type: SessionType,
}
impl Message for Register {
type Result = SessionsUnitResult;
}
/// Message indicating a session needs to be unregistered
pub struct Unregister {
/// Socket address identifying the peer
pub address: SocketAddr,
/// Session type
pub session_type: SessionType,
/// Session status
pub status: SessionStatus,
}
impl Message for Unregister {
type Result = SessionsUnitResult;
}
/// Message indicating a session needs to be consolidated
pub struct Consolidate {
/// Socket address which identifies the peer
pub address: SocketAddr,
/// Potential peer to be added
/// In their `Version` messages the nodes communicate the address of their server and that
/// is a potential peer that should try to be added
pub potential_new_peer: Option<SocketAddr>,
/// Session type
pub session_type: SessionType,
}
impl Message for Consolidate {
type Result = SessionsUnitResult;
}
/// Message indicating a message is to be forwarded to a random consolidated outbound session
pub struct Anycast<T> {
/// Command to be sent to the session
pub command: T,
/// Safu flag: use only outbound peers in consensus with us?
pub safu: bool,
}
impl<T> Message for Anycast<T>
where
T: Message + Send + Debug,
T::Result: Send,
Session: Handler<T>,
{
type Result = Result<T::Result, ()>;
}
/// Message indicating a message is to be forwarded to all the consolidated outbound sessions
pub struct Broadcast<T> {
/// Command to be sent to all the sessions
pub command: T,
/// Inbound flag: use only inbound peers
pub only_inbound: bool,
}