-
Notifications
You must be signed in to change notification settings - Fork 358
/
Copy pathrelay_path.rs
2007 lines (1752 loc) · 75.4 KB
/
relay_path.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 alloc::collections::BTreeMap as HashMap;
use alloc::collections::VecDeque;
use ibc_relayer_types::core::ics04_channel::packet::Sequence;
use std::ops::Sub;
use std::time::{Duration, Instant};
use ibc_proto::google::protobuf::Any;
use ibc_proto::ibc::applications::transfer::v2::FungibleTokenPacketData as RawPacketData;
use itertools::Itertools;
use tracing::{debug, error, info, span, trace, warn, Level};
use ibc_relayer_types::core::ics02_client::events::ClientMisbehaviour as ClientMisbehaviourEvent;
use ibc_relayer_types::core::ics04_channel::channel::{
ChannelEnd, Ordering, State as ChannelState,
};
use ibc_relayer_types::core::ics04_channel::events::{SendPacket, WriteAcknowledgement};
use ibc_relayer_types::core::ics04_channel::msgs::{
acknowledgement::MsgAcknowledgement, chan_close_confirm::MsgChannelCloseConfirm,
recv_packet::MsgRecvPacket, timeout::MsgTimeout, timeout_on_close::MsgTimeoutOnClose,
};
use ibc_relayer_types::core::ics04_channel::packet::{Packet, PacketMsgType};
use ibc_relayer_types::core::ics24_host::identifier::{ChannelId, ClientId, ConnectionId, PortId};
use ibc_relayer_types::events::{IbcEvent, IbcEventType, WithBlockDataType};
use ibc_relayer_types::signer::Signer;
use ibc_relayer_types::timestamp::Timestamp;
use ibc_relayer_types::tx_msg::Msg;
use ibc_relayer_types::Height;
use crate::chain::counterparty::unreceived_acknowledgements;
use crate::chain::counterparty::unreceived_packets;
use crate::chain::endpoint::ChainStatus;
use crate::chain::handle::ChainHandle;
use crate::chain::requests::Paginate;
use crate::chain::requests::QueryChannelRequest;
use crate::chain::requests::QueryClientEventRequest;
use crate::chain::requests::QueryHeight;
use crate::chain::requests::QueryHostConsensusStateRequest;
use crate::chain::requests::QueryNextSequenceReceiveRequest;
use crate::chain::requests::QueryPacketCommitmentRequest;
use crate::chain::requests::QueryTxRequest;
use crate::chain::requests::QueryUnreceivedAcksRequest;
use crate::chain::requests::QueryUnreceivedPacketsRequest;
use crate::chain::requests::{IncludeProof, Qualified};
use crate::chain::tracking::TrackedMsgs;
use crate::chain::tracking::TrackingId;
use crate::channel::error::ChannelError;
use crate::channel::Channel;
use crate::config::types::ics20_field_size_limit::Ics20FieldSizeLimit;
use crate::config::types::ics20_field_size_limit::ValidationResult;
use crate::event::source::EventBatch;
use crate::event::IbcEventWithHeight;
use crate::foreign_client::{ForeignClient, ForeignClientError};
use crate::link::error::{self, LinkError};
use crate::link::operational_data::{
OperationalData, OperationalDataTarget, TrackedEvents, TransitMessage,
};
use crate::link::packet_events::query_packet_events_with;
use crate::link::packet_events::query_send_packet_events;
use crate::link::packet_events::query_write_ack_events;
use crate::link::pending::PendingTxs;
use crate::link::relay_sender::{AsyncReply, SubmitReply};
use crate::link::relay_summary::RelaySummary;
use crate::link::LinkParameters;
use crate::link::{pending, relay_sender};
use crate::path::PathIdentifiers;
use crate::telemetry;
use crate::util::collate::CollatedIterExt;
use crate::util::pretty::PrettyEvents;
use crate::util::queue::Queue;
const MAX_RETRIES: usize = 5;
/// Whether or not to resubmit packets when pending transactions
/// fail to process within the given timeout duration.
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum Resubmit {
Yes,
No,
}
impl Resubmit {
/// Packet resubmission is enabled when the clear interval for packets is 0. Otherwise,
/// when the packet clear interval is > 0, the relayer will periodically clear unsent packets
/// such that resubmitting packets is not necessary.
pub fn from_clear_interval(clear_interval: u64) -> Self {
if clear_interval == 0 {
Self::Yes
} else {
Self::No
}
}
}
pub struct RelayPath<ChainA: ChainHandle, ChainB: ChainHandle> {
channel: Channel<ChainA, ChainB>,
pub(crate) path_id: PathIdentifiers,
// Operational data, targeting both the source and destination chain.
// These vectors of operational data are ordered decreasingly by
// their age, with element at position `0` being the oldest.
// The operational data targeting the source chain comprises
// mostly timeout packet messages.
// The operational data targeting the destination chain
// comprises mostly RecvPacket and Ack msgs.
pub src_operational_data: Queue<OperationalData>,
pub dst_operational_data: Queue<OperationalData>,
// Toggle for the transaction confirmation mechanism.
confirm_txes: bool,
// Stores pending (i.e., unconfirmed) operational data.
// The relaying path periodically tries to confirm these pending
// transactions if [`confirm_txes`] is true.
pending_txs_src: PendingTxs<ChainA>,
pending_txs_dst: PendingTxs<ChainB>,
pub max_memo_size: Ics20FieldSizeLimit,
pub max_receiver_size: Ics20FieldSizeLimit,
pub exclude_src_sequences: Vec<Sequence>,
}
impl<ChainA: ChainHandle, ChainB: ChainHandle> RelayPath<ChainA, ChainB> {
pub fn new(
channel: Channel<ChainA, ChainB>,
with_tx_confirmation: bool,
link_parameters: LinkParameters,
) -> Result<Self, LinkError> {
let src_chain = channel.src_chain().clone();
let dst_chain = channel.dst_chain().clone();
let src_chain_id = src_chain.id();
let dst_chain_id = dst_chain.id();
let src_channel_id = channel
.src_channel_id()
.ok_or_else(|| LinkError::missing_channel_id(src_chain.id()))?
.clone();
let dst_channel_id = channel
.dst_channel_id()
.ok_or_else(|| LinkError::missing_channel_id(dst_chain.id()))?
.clone();
let src_port_id = channel.src_port_id().clone();
let dst_port_id = channel.dst_port_id().clone();
let path = PathIdentifiers {
port_id: dst_port_id.clone(),
channel_id: dst_channel_id.clone(),
counterparty_port_id: src_port_id.clone(),
counterparty_channel_id: src_channel_id.clone(),
};
Ok(Self {
channel,
path_id: path,
src_operational_data: Queue::new(),
dst_operational_data: Queue::new(),
confirm_txes: with_tx_confirmation,
pending_txs_src: PendingTxs::new(src_chain, src_channel_id, src_port_id, dst_chain_id),
pending_txs_dst: PendingTxs::new(dst_chain, dst_channel_id, dst_port_id, src_chain_id),
max_memo_size: link_parameters.max_memo_size,
max_receiver_size: link_parameters.max_receiver_size,
exclude_src_sequences: link_parameters.exclude_src_sequences,
})
}
pub fn src_chain(&self) -> &ChainA {
self.channel.src_chain()
}
pub fn dst_chain(&self) -> &ChainB {
self.channel.dst_chain()
}
pub fn src_client_id(&self) -> &ClientId {
self.channel.src_client_id()
}
pub fn dst_client_id(&self) -> &ClientId {
self.channel.dst_client_id()
}
pub fn src_connection_id(&self) -> &ConnectionId {
self.channel.src_connection_id()
}
pub fn dst_connection_id(&self) -> &ConnectionId {
self.channel.dst_connection_id()
}
pub fn src_port_id(&self) -> &PortId {
&self.path_id.counterparty_port_id
}
pub fn dst_port_id(&self) -> &PortId {
&self.path_id.port_id
}
pub fn src_channel_id(&self) -> &ChannelId {
&self.path_id.counterparty_channel_id
}
pub fn dst_channel_id(&self) -> &ChannelId {
&self.path_id.channel_id
}
pub fn channel(&self) -> &Channel<ChainA, ChainB> {
&self.channel
}
fn src_channel(&self, height_query: QueryHeight) -> Result<ChannelEnd, LinkError> {
self.src_chain()
.query_channel(
QueryChannelRequest {
port_id: self.src_port_id().clone(),
channel_id: self.src_channel_id().clone(),
height: height_query,
},
IncludeProof::No,
)
.map(|(channel_end, _)| channel_end)
.map_err(|e| LinkError::channel(ChannelError::query(self.src_chain().id(), e)))
}
fn dst_channel(&self, height_query: QueryHeight) -> Result<ChannelEnd, LinkError> {
self.dst_chain()
.query_channel(
QueryChannelRequest {
port_id: self.dst_port_id().clone(),
channel_id: self.dst_channel_id().clone(),
height: height_query,
},
IncludeProof::No,
)
.map(|(channel_end, _)| channel_end)
.map_err(|e| LinkError::channel(ChannelError::query(self.dst_chain().id(), e)))
}
fn src_signer(&self) -> Result<Signer, LinkError> {
self.src_chain()
.get_signer()
.map_err(|e| LinkError::signer(self.src_chain().id(), e))
}
fn dst_signer(&self) -> Result<Signer, LinkError> {
self.dst_chain()
.get_signer()
.map_err(|e| LinkError::signer(self.dst_chain().id(), e))
}
pub(crate) fn src_latest_height(&self) -> Result<Height, LinkError> {
self.src_chain()
.query_latest_height()
.map_err(|e| LinkError::query(self.src_chain().id(), e))
}
pub(crate) fn dst_latest_height(&self) -> Result<Height, LinkError> {
self.dst_chain()
.query_latest_height()
.map_err(|e| LinkError::query(self.dst_chain().id(), e))
}
fn src_time_at_height(&self, height: Height) -> Result<Instant, LinkError> {
Self::chain_time_at_height(self.src_chain(), height)
}
fn dst_time_at_height(&self, height: Height) -> Result<Instant, LinkError> {
Self::chain_time_at_height(self.dst_chain(), height)
}
pub(crate) fn src_time_latest(&self) -> Result<Instant, LinkError> {
let elapsed = Timestamp::now()
.duration_since(
&self
.src_chain()
.query_application_status()
.unwrap()
.timestamp,
)
.unwrap_or_default();
Ok(Instant::now().sub(elapsed))
}
pub(crate) fn dst_time_latest(&self) -> Result<Instant, LinkError> {
let elapsed = Timestamp::now()
.duration_since(
&self
.dst_chain()
.query_application_status()
.unwrap()
.timestamp,
)
.unwrap_or_default();
Ok(Instant::now().sub(elapsed))
}
pub(crate) fn src_max_block_time(&self) -> Result<Duration, LinkError> {
// TODO(hu55a1n1): Ideally, we should get the `max_expected_time_per_block` using the
// `/genesis` endpoint once it is working in tendermint-rs.
Ok(self
.src_chain()
.config()
.map_err(LinkError::relayer)?
.max_block_time())
}
pub(crate) fn dst_max_block_time(&self) -> Result<Duration, LinkError> {
Ok(self
.dst_chain()
.config()
.map_err(LinkError::relayer)?
.max_block_time())
}
fn unordered_channel(&self) -> bool {
self.channel.ordering == Ordering::Unordered
}
fn ordered_channel(&self) -> bool {
self.channel.ordering == Ordering::Ordered
}
pub fn build_update_client_on_dst(&self, height: Height) -> Result<Vec<Any>, LinkError> {
let client = self.restore_dst_client();
client
.wait_and_build_update_client(height)
.map_err(LinkError::client)
}
pub fn build_update_client_on_src(&self, height: Height) -> Result<Vec<Any>, LinkError> {
let client = self.restore_src_client();
client
.wait_and_build_update_client(height)
.map_err(LinkError::client)
}
fn build_chan_close_confirm_from_event(
&self,
event: &IbcEventWithHeight,
) -> Result<Option<Any>, LinkError> {
// Build the `MsgChannelCloseConfirm` only from `Timeout` or `CloseInitChannel` event types
if event.event.event_type() != IbcEventType::Timeout
&& event.event.event_type() != IbcEventType::CloseInitChannel
{
return Ok(None);
}
// Nothing to do if channel on destination is already closed
let dst_channel = self.dst_channel(QueryHeight::Latest)?;
if dst_channel.state_matches(&ChannelState::Closed) {
return Ok(None);
}
let src_channel_id = self.src_channel_id();
let proofs = self
.src_chain()
.build_channel_proofs(self.src_port_id(), src_channel_id, event.height)
.map_err(|e| LinkError::channel(ChannelError::channel_proof(e)))?;
let counterparty_upgrade_sequence = self.src_channel(QueryHeight::Latest)?.upgrade_sequence;
// Build the domain type message
let new_msg = MsgChannelCloseConfirm {
port_id: self.dst_port_id().clone(),
channel_id: self.dst_channel_id().clone(),
proofs,
signer: self.dst_signer()?,
counterparty_upgrade_sequence,
};
Ok(Some(new_msg.to_any()))
}
/// Determines if the events received are relevant and should be processed.
/// Only events for a port/channel matching one of the channel ends should be processed.
fn filter_relaying_events(
&self,
events: Vec<IbcEventWithHeight>,
tracking_id: TrackingId,
) -> TrackedEvents {
let src_channel_id = self.src_channel_id();
let mut result = vec![];
for event_with_height in events.into_iter() {
match &event_with_height.event {
IbcEvent::SendPacket(send_packet_ev) => {
if src_channel_id == send_packet_ev.src_channel_id()
&& self.src_port_id() == send_packet_ev.src_port_id()
{
result.push(event_with_height);
}
}
IbcEvent::WriteAcknowledgement(write_ack_ev) => {
if src_channel_id == write_ack_ev.dst_channel_id()
&& self.src_port_id() == write_ack_ev.dst_port_id()
{
result.push(event_with_height);
}
}
IbcEvent::CloseInitChannel(chan_close_ev) => {
if src_channel_id == chan_close_ev.channel_id()
&& self.src_port_id() == chan_close_ev.port_id()
{
result.push(event_with_height);
}
}
IbcEvent::TimeoutPacket(timeout_ev) => {
if src_channel_id == timeout_ev.src_channel_id()
&& self.channel.src_port_id() == timeout_ev.src_port_id()
{
result.push(event_with_height);
}
}
_ => {}
}
}
// Transform into `TrackedEvents`
TrackedEvents::new(result, tracking_id)
}
fn relay_pending_packets(
&self,
height: Option<Height>,
clear_limit: usize,
) -> Result<(), LinkError> {
let _span = span!(Level::ERROR, "relay_pending_packets", ?height).entered();
let tracking_id = TrackingId::new_packet_clearing();
telemetry!(received_event_batch, tracking_id);
let src_config = self.src_chain().config().map_err(LinkError::relayer)?;
let chunk_size = src_config.query_packets_chunk_size();
for i in 1..=MAX_RETRIES {
let cleared_recv = self.schedule_recv_packet_and_timeout_msgs(
height,
chunk_size,
clear_limit,
tracking_id,
);
let cleared_ack =
self.schedule_packet_ack_msgs(height, chunk_size, clear_limit, tracking_id);
match cleared_recv.and(cleared_ack) {
Ok(()) => return Ok(()),
Err(e) => error!(
"failed to clear packets, retry {}/{}: {}",
i, MAX_RETRIES, e
),
}
}
Err(LinkError::old_packet_clearing_failed())
}
/// Clears any packets that were sent before `height`.
/// If no height is passed in, then the latest height of the source chain is used.
pub fn schedule_packet_clearing(
&self,
height: Option<Height>,
clear_limit: usize,
) -> Result<(), LinkError> {
let _span = span!(Level::ERROR, "schedule_packet_clearing", ?height).entered();
let clear_height = height
.map(|h| h.decrement().map_err(|e| LinkError::decrement_height(h, e)))
.transpose()?;
self.relay_pending_packets(clear_height, clear_limit)?;
debug!(height = ?clear_height, "done relaying pending packets at clear height");
Ok(())
}
/// Generate & schedule operational data from the input `batch` of IBC events.
pub fn update_schedule(&self, batch: EventBatch) -> Result<(), LinkError> {
let _span = span!(
Level::ERROR,
"update_schedule",
%batch.tracking_id,
%batch.height,
)
.entered();
// Collect relevant events from the incoming batch & adjust their height.
let events = self.filter_relaying_events(batch.events, batch.tracking_id);
// Update telemetry info
telemetry!({
for event_with_height in events.events() {
self.backlog_update(&event_with_height.event);
}
});
// Transform the events into operational data items
self.events_to_operational_data(events)
}
/// Produces and schedules operational data for this relaying path based on the input events.
pub(crate) fn events_to_operational_data(
&self,
events: TrackedEvents,
) -> Result<(), LinkError> {
// Obtain the operational data for the source chain (mostly timeout packets) and for the
// destination chain (e.g., receive packet messages).
let (src_opt, dst_opt) = self.generate_operational_data(events)?;
if let Some(src_od) = src_opt {
self.schedule_operational_data(src_od)?;
}
if let Some(dst_od) = dst_opt {
self.schedule_operational_data(dst_od)?;
}
Ok(())
}
/// Generates operational data out of a set of events.
/// Handles building operational data targeting both the destination and source chains.
///
/// For the destination chain, the op. data will contain `RecvPacket` messages,
/// as well as channel close handshake (`ChanCloseConfirm`), `WriteAck` messages.
///
/// For the source chain, the op. data will contain timeout packet messages (`MsgTimeoutOnClose`
/// or `MsgTimeout`).
fn generate_operational_data(
&self,
events: TrackedEvents,
) -> Result<(Option<OperationalData>, Option<OperationalData>), LinkError> {
let _span = span!(
Level::ERROR,
"generate_operational_data",
tracking_id = %events.tracking_id(),
)
.entered();
let input = events.events();
let src_height = match input.first() {
None => return Ok((None, None)),
Some(ev) => ev.height,
};
let dst_latest_info = self
.dst_chain()
.query_application_status()
.map_err(|e| LinkError::query(self.dst_chain().id(), e))?;
let dst_latest_height = dst_latest_info.height;
// Operational data targeting the source chain (e.g., Timeout packets)
let mut src_od = OperationalData::new(
dst_latest_height,
OperationalDataTarget::Source,
events.tracking_id(),
self.channel.connection_delay,
);
// Operational data targeting the destination chain (e.g., SendPacket messages)
let mut dst_od = OperationalData::new(
src_height,
OperationalDataTarget::Destination,
events.tracking_id(),
self.channel.connection_delay,
);
for event_with_height in input {
trace!(event = %event_with_height, "processing event");
if let Some(packet) = event_with_height.event.packet() {
// If the event is a ICS-04 packet event, and the packet contains ICS-20
// packet data, check that the ICS-20 fields are within the configured limits.
if !check_ics20_fields_size(
&packet.data,
self.max_memo_size,
self.max_receiver_size,
) {
telemetry!(
filtered_packets,
&self.src_chain().id(),
&self.dst_chain().id(),
&packet.source_channel,
&packet.destination_channel,
&packet.source_port,
&packet.destination_port,
1
);
continue;
}
}
let (dst_msg, src_msg) = match &event_with_height.event {
IbcEvent::CloseInitChannel(_) => (
self.build_chan_close_confirm_from_event(event_with_height)?,
None,
),
IbcEvent::TimeoutPacket(_) => {
// When a timeout packet for an ordered channel is processed on-chain (src here)
// the chain closes the channel but no close init event is emitted, instead
// we get a timeout packet event (this happens for both unordered and ordered channels)
// Here we check that the channel is closed on src and send a channel close confirm
// to the counterparty.
if self.ordered_channel()
&& self
.src_channel(QueryHeight::Specific(event_with_height.height))?
.state_matches(&ChannelState::Closed)
{
(
self.build_chan_close_confirm_from_event(event_with_height)?,
None,
)
} else {
(None, None)
}
}
IbcEvent::SendPacket(ref event) => {
if self.send_packet_event_handled(event)? {
debug!(?event, "SendPacket event has already been handled");
(None, None)
} else {
self.build_recv_or_timeout_from_send_packet_event(
event,
&dst_latest_info,
event_with_height.height,
)?
}
}
IbcEvent::WriteAcknowledgement(ref event) => {
if self
.dst_channel(QueryHeight::Latest)?
.state_matches(&ChannelState::Closed)
{
(None, None)
} else if self.write_ack_event_handled(event)? {
debug!(
?event,
"WriteAcknowledgement event has already been handled"
);
(None, None)
} else {
(
self.build_ack_from_recv_event(event, event_with_height.height)?,
None,
)
}
}
_ => (None, None),
};
// Collect messages to be sent to the destination chain (e.g., RecvPacket)
if let Some(msg) = dst_msg {
trace!(%msg.type_url, event = %event_with_height, "collected event");
dst_od.batch.push(TransitMessage {
event_with_height: event_with_height.clone(),
msg,
});
}
// Collect timeout messages, to be sent to the source chain
if let Some(msg) = src_msg {
// For Ordered channels a single timeout event should be sent as this closes the channel.
// Otherwise a multi message transaction will fail.
if self.unordered_channel() || src_od.batch.is_empty() {
trace!(%msg.type_url, event = %event_with_height, "collected event");
src_od.batch.push(TransitMessage {
event_with_height: event_with_height.clone(),
msg,
});
}
}
}
let src_od = Some(src_od).filter(|s| !s.batch.is_empty());
let dst_od = Some(dst_od).filter(|s| !s.batch.is_empty());
Ok((src_od, dst_od))
}
/// Relays an [`OperationalData`] using a specific
/// sender, which implements [`relay_sender::Submit`].
pub(crate) fn relay_from_operational_data<S: relay_sender::Submit>(
&self,
initial_od: OperationalData,
) -> Result<S::Reply, LinkError> {
// We will operate on potentially different operational data if the initial one fails.
let _span = span!(Level::INFO, "relay", odata = %initial_od.info()).entered();
let mut odata = initial_od;
for i in 0..MAX_RETRIES {
debug!(retry.current = i + 1, retry.max = MAX_RETRIES, "retrying");
// Consume the operational data by attempting to send its messages
match self.send_from_operational_data::<S>(&odata) {
Ok(reply) => {
// Done with this op. data
info!("submitted");
telemetry!({
let (chain, counterparty, channel_id, port_id) =
self.target_info(odata.target);
ibc_telemetry::global().tx_submitted(
reply.len(),
odata.tracking_id,
&chain,
channel_id,
port_id,
&counterparty,
);
});
return Ok(reply);
}
Err(LinkError(error::LinkErrorDetail::Send(_), _)) => {
if i + 1 == MAX_RETRIES {
error!("{}/{} retries exhausted, giving up", i + 1, MAX_RETRIES)
} else {
debug!("{}/{} retries exhausted, retrying with newly-generated operational data", i + 1, MAX_RETRIES);
// If we haven't exhausted all retries, regenerate the op. data & retry
match self.regenerate_operational_data(odata.clone()) {
None => return Ok(S::Reply::empty()), // Nothing to retry
Some(new_od) => odata = new_od,
}
}
}
Err(e) => {
// Unrecoverable error, propagate up the stack
return Err(e);
}
}
}
Ok(S::Reply::empty())
}
/// Generates fresh operational data for a tx given the initial operational data
/// that failed to send.
///
/// Return value:
/// - `Some(..)`: a new operational data from which to retry sending,
/// - `None`: all the events in the initial operational data were exhausted (i.e., turned
/// into timeouts), so there is nothing to retry.
///
/// Side effects: may schedule a new operational data targeting the source chain, comprising
/// new timeout messages.
pub(crate) fn regenerate_operational_data(
&self,
initial_odata: OperationalData,
) -> Option<OperationalData> {
let op_info = initial_odata.info();
warn!(
"failed. Regenerate operational data from {} events",
op_info.batch_len()
);
// Retry by re-generating the operational data using the initial events
let (src_opt, dst_opt) = match self.generate_operational_data(initial_odata.into_events()) {
Ok(new_operational_data) => new_operational_data,
Err(e) => {
error!(
"failed to regenerate operational data from initial data: {} \
with error {}, discarding this op. data",
op_info, e
);
return None;
} // Cannot retry, contain the error by reporting a None
};
if let Some(src_od) = src_opt {
if src_od.target == op_info.target() {
// Our target is the _source_ chain, retry these messages
info!(odata = %src_od.info(), "will retry");
return Some(src_od);
} else {
// Our target is the _destination_ chain, the data in `src_od` contains
// potentially new timeout messages that have to be handled separately.
if let Err(e) = self.schedule_operational_data(src_od) {
error!(
"failed to schedule newly-generated operational data from \
initial data: {} with error {}, discarding this op. data",
op_info, e
);
return None;
}
}
}
if let Some(dst_od) = dst_opt {
if dst_od.target == op_info.target() {
// Our target is the _destination_ chain, retry these messages
info!(odata = %dst_od.info(), "will retry");
return Some(dst_od);
} else {
// Our target is the _source_ chain, but `dst_od` has new messages
// intended for the destination chain, this should never be the case
error!(
"generated new messages for destination chain while handling \
failed events targeting the source chain!",
);
}
} else {
// There is no message intended for the destination chain
if op_info.target() == OperationalDataTarget::Destination {
info!("exhausted all events from this operational data");
return None;
}
}
None
}
/// Sends a transaction based on the [`OperationalData`] to
/// the corresponding target chain.
///
/// Returns the appropriate reply associated with the given
/// [`relay_sender::Submit`]. The reply consists of either the tx
/// hashes generated by the target chain, if [`Async`] sender,
/// or the ibc events, if the sender is [`Sync`].
///
/// Propagates any encountered errors.
fn send_from_operational_data<S: relay_sender::Submit>(
&self,
odata: &OperationalData,
) -> Result<S::Reply, LinkError> {
if odata.batch.is_empty() {
error!("ignoring empty operational data!");
return Ok(S::Reply::empty());
}
let msgs = odata.assemble_msgs(self)?;
match odata.target {
OperationalDataTarget::Source => S::submit(self.src_chain(), msgs),
OperationalDataTarget::Destination => S::submit(self.dst_chain(), msgs),
}
}
fn enqueue_pending_tx(&self, reply: AsyncReply, odata: OperationalData) {
if !self.confirm_txes {
return;
}
match odata.target {
OperationalDataTarget::Source => {
self.pending_txs_src.insert_new_pending_tx(reply, odata);
}
OperationalDataTarget::Destination => {
self.pending_txs_dst.insert_new_pending_tx(reply, odata);
}
}
}
/// Checks if a sent packet has been received on destination.
fn send_packet_received_on_dst(&self, packet: &Packet) -> Result<bool, LinkError> {
let unreceived_packet = self
.dst_chain()
.query_unreceived_packets(QueryUnreceivedPacketsRequest {
port_id: self.dst_port_id().clone(),
channel_id: self.dst_channel_id().clone(),
packet_commitment_sequences: vec![packet.sequence],
})
.map_err(LinkError::relayer)?;
Ok(unreceived_packet.is_empty())
}
/// Checks if a packet commitment has been cleared on source.
/// The packet commitment is cleared when either an acknowledgment or a timeout is received on source.
fn send_packet_commitment_cleared_on_src(&self, packet: &Packet) -> Result<bool, LinkError> {
let (bytes, _) = self
.src_chain()
.query_packet_commitment(
QueryPacketCommitmentRequest {
port_id: self.src_port_id().clone(),
channel_id: self.src_channel_id().clone(),
sequence: packet.sequence,
height: QueryHeight::Latest,
},
IncludeProof::No,
)
.map_err(LinkError::relayer)?;
Ok(bytes.is_empty())
}
/// Checks if a send packet event has already been handled (e.g. by another relayer).
fn send_packet_event_handled(&self, sp: &SendPacket) -> Result<bool, LinkError> {
Ok(self.send_packet_received_on_dst(&sp.packet)?
|| self.send_packet_commitment_cleared_on_src(&sp.packet)?)
}
/// Checks if an acknowledgement for the given packet has been received on
/// source chain of the packet, ie. the destination chain of the relay path
/// that sends the acknowledgment.
fn recv_packet_acknowledged_on_src(&self, packet: &Packet) -> Result<bool, LinkError> {
let unreceived_ack = self
.dst_chain()
.query_unreceived_acknowledgements(QueryUnreceivedAcksRequest {
port_id: self.dst_port_id().clone(),
channel_id: self.dst_channel_id().clone(),
packet_ack_sequences: vec![packet.sequence],
})
.map_err(LinkError::relayer)?;
Ok(unreceived_ack.is_empty())
}
/// Checks if a receive packet event has already been handled (e.g. by another relayer).
fn write_ack_event_handled(&self, rp: &WriteAcknowledgement) -> Result<bool, LinkError> {
self.recv_packet_acknowledged_on_src(&rp.packet)
}
/// Returns the `processed_height` for the consensus state at specified height
fn update_height(
chain: &impl ChainHandle,
client_id: ClientId,
consensus_height: Height,
) -> Result<Height, LinkError> {
let events_with_heights = chain
.query_txs(QueryTxRequest::Client(QueryClientEventRequest {
query_height: QueryHeight::Latest,
event_id: WithBlockDataType::UpdateClient,
client_id,
consensus_height,
}))
.map_err(|e| LinkError::query(chain.id(), e))?;
// The handler may treat redundant updates as no-ops and emit `UpdateClient` events for them
// but the `processed_height` is the height at which the first `UpdateClient` event for this
// consensus state/height was emitted. We expect that these events are received in the exact
// same order in which they were emitted.
match events_with_heights.first() {
Some(event_with_height) => {
if matches!(&event_with_height.event, IbcEvent::UpdateClient(_)) {
Ok(event_with_height.height)
} else {
Err(LinkError::unexpected_event(event_with_height.event.clone()))
}
}
None => Err(LinkError::update_client_event_not_found()),
}
}
/// Loops over `tx_events` and returns a tuple of optional events where the first element is a
/// `ChainError` variant, the second one is an `UpdateClient` variant and the third one is a
/// `ClientMisbehaviour` variant. This function is essentially just an `Iterator::find()` for
/// multiple variants with a single pass.
#[inline]
fn event_per_type(
mut tx_events: Vec<IbcEventWithHeight>,
) -> (
Option<IbcEvent>,
Option<Height>,
Option<ClientMisbehaviourEvent>,
) {
let mut error = None;
let mut update = None;
let mut misbehaviour = None;
while let Some(event_with_height) = tx_events.pop() {
match event_with_height.event {
IbcEvent::ChainError(_) => error = Some(event_with_height.event),
IbcEvent::UpdateClient(_) => update = Some(event_with_height.height),
IbcEvent::ClientMisbehaviour(event) => misbehaviour = Some(event),
_ => {}
}
}
(error, update, misbehaviour)
}
/// Returns an instant (in the past) that corresponds to the block timestamp of the chain at
/// specified height (relative to the relayer's current time). If the timestamp is in the future
/// wrt the relayer's current time, we simply return the current relayer time.
fn chain_time_at_height(
chain: &impl ChainHandle,
height: Height,
) -> Result<Instant, LinkError> {
let chain_time = chain
.query_host_consensus_state(QueryHostConsensusStateRequest {