-
Notifications
You must be signed in to change notification settings - Fork 329
/
link.rs
1747 lines (1502 loc) · 61.4 KB
/
link.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
#![allow(clippy::borrowed_box)]
use std::collections::HashMap;
use std::fmt;
use std::thread;
use std::time::Instant;
use prost_types::Any;
use thiserror::Error;
use tracing::{debug, error, info, trace, warn};
use ibc::{
downcast,
events::{IbcEvent, IbcEventType, PrettyEvents},
ics03_connection::connection::State as ConnectionState,
ics04_channel::{
channel::{ChannelEnd, Order, QueryPacketEventDataRequest, State as ChannelState},
events::{SendPacket, WriteAcknowledgement},
msgs::{
acknowledgement::MsgAcknowledgement, chan_close_confirm::MsgChannelCloseConfirm,
recv_packet::MsgRecvPacket, timeout::MsgTimeout, timeout_on_close::MsgTimeoutOnClose,
},
packet::{Packet, PacketMsgType, Sequence},
},
ics24_host::identifier::{ChainId, ChannelId, ClientId, ConnectionId, PortChannelId, PortId},
query::QueryTxRequest,
signer::Signer,
timestamp::ZERO_DURATION,
tx_msg::Msg,
Height,
};
use ibc_proto::ibc::core::channel::v1::{
QueryNextSequenceReceiveRequest, QueryPacketAcknowledgementsRequest,
QueryPacketCommitmentsRequest, QueryUnreceivedAcksRequest, QueryUnreceivedPacketsRequest,
};
use crate::chain::counterparty::check_channel_counterparty;
use crate::chain::handle::ChainHandle;
use crate::channel::{Channel, ChannelError, ChannelSide};
use crate::connection::ConnectionError;
use crate::error::Error;
use crate::event::monitor::EventBatch;
use crate::foreign_client::{ForeignClient, ForeignClientError};
use crate::transfer::PacketError;
const MAX_RETRIES: usize = 5;
#[derive(Debug, Error)]
pub enum LinkError {
#[error("failed with underlying error: {0}")]
Failed(String),
#[error("failed with underlying error: {0}")]
Generic(#[from] Error),
#[error("link initialization failed during channel counterparty verification: {0}")]
Initialization(ChannelError),
#[error("failed to construct packet proofs for chain {0} with error: {1}")]
PacketProofsConstructor(ChainId, Error),
#[error("failed during query to chain id {0} with underlying error: {1}")]
QueryError(ChainId, Error),
#[error("connection error: {0}:")]
ConnectionError(#[from] ConnectionError),
#[error("channel error: {0}:")]
ChannelError(#[from] ChannelError),
#[error("failed during a client operation: {0}:")]
ClientError(ForeignClientError),
#[error("packet error: {0}:")]
PacketError(#[from] PacketError),
#[error("clearing of old packets failed")]
OldPacketClearingFailed,
#[error("chain error when sending messages: {0}")]
SendError(Box<IbcEvent>),
}
#[derive(Clone, Copy, PartialEq)]
pub enum OperationalDataTarget {
Source,
Destination,
}
impl fmt::Display for OperationalDataTarget {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
OperationalDataTarget::Source => write!(f, "Source"),
OperationalDataTarget::Destination => write!(f, "Destination"),
}
}
}
/// A packet messages that is prepared for sending to a chain, but has not been sent yet.
/// Comprises both the proto-encoded packet message, alongside the event which generated it.
#[derive(Clone)]
pub struct TransitMessage {
event: IbcEvent,
msg: Any,
}
/// Holds all the necessary information for handling a set of in-transit messages.
///
/// Each `OperationalData` item is uniquely identified by the combination of two attributes:
/// - `target`: represents the target of the packet messages, either source or destination chain,
/// - `proofs_height`: represents the height for the proofs in all the messages.
/// Note: this is the height at which the proofs are queried. A client consensus state at
/// `proofs_height + 1` must exist on-chain in order to verify the proofs.
#[derive(Clone)]
pub struct OperationalData {
proofs_height: Height,
batch: Vec<TransitMessage>,
target: OperationalDataTarget,
/// Stores the time when the clients on the target chain has been updated, i.e., when this data
/// was scheduled. Necessary for packet delays.
scheduled_time: Instant,
}
impl OperationalData {
pub fn new(proofs_height: Height, target: OperationalDataTarget) -> Self {
OperationalData {
proofs_height,
batch: vec![],
target,
scheduled_time: Instant::now(),
}
}
fn events(&self) -> Vec<IbcEvent> {
self.batch.iter().map(|gm| gm.event.clone()).collect()
}
/// Returns all the messages in this operational data, plus prepending the client update message
/// if necessary.
fn assemble_msgs(&self, relay_path: &RelayPath) -> Result<Vec<Any>, LinkError> {
if self.batch.is_empty() {
warn!("assemble_msgs() method call on an empty OperationalData!");
return Ok(vec![]);
}
let mut msgs: Vec<Any> = self.batch.iter().map(|gm| gm.msg.clone()).collect();
// For zero delay we prepend the client update msgs.
if relay_path.zero_delay() {
let update_height = self.proofs_height.increment();
info!(
"[{}] prepending {} client update @ height {}",
relay_path, self.target, update_height
);
// Fetch the client update message. Vector may be empty if the client already has the header
// for the requested height.
let mut client_update_opt = match self.target {
OperationalDataTarget::Source => {
relay_path.build_update_client_on_src(update_height)?
}
OperationalDataTarget::Destination => {
relay_path.build_update_client_on_dst(update_height)?
}
};
if let Some(client_update) = client_update_opt.pop() {
msgs.insert(0, client_update);
}
}
info!(
"[{}] assembled batch of {} message(s)",
relay_path,
msgs.len()
);
Ok(msgs)
}
}
impl fmt::Display for OperationalData {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"Op.Data [->{} @{}; {} event(s) & msg(s) in batch]",
self.target,
self.proofs_height,
self.batch.len(),
)
}
}
pub struct RelayPath {
channel: Channel,
clear_packets: bool,
// 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.
src_operational_data: Vec<OperationalData>,
// The operational data targeting the destination chain comprises mostly RecvPacket and Ack msgs.
dst_operational_data: Vec<OperationalData>,
}
impl RelayPath {
pub fn new(channel: Channel) -> Self {
Self {
channel,
clear_packets: true,
src_operational_data: vec![],
dst_operational_data: vec![],
}
}
pub fn src_chain(&self) -> &Box<dyn ChainHandle> {
self.channel.src_chain()
}
pub fn dst_chain(&self) -> &Box<dyn ChainHandle> {
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.channel.src_port_id()
}
pub fn dst_port_id(&self) -> &PortId {
self.channel.dst_port_id()
}
pub fn src_channel_id(&self) -> Result<&ChannelId, LinkError> {
self.channel.src_channel_id().ok_or_else(|| {
LinkError::Failed(format!(
"channel_id on source chain '{}' is 'None'",
self.src_chain().id()
))
})
}
pub fn dst_channel_id(&self) -> Result<&ChannelId, LinkError> {
self.channel.dst_channel_id().ok_or_else(|| {
LinkError::Failed(format!(
"channel_id on destination chain '{}' is 'None'",
self.dst_chain().id()
))
})
}
pub fn channel(&self) -> &Channel {
&self.channel
}
fn src_channel(&self, height: Height) -> Result<ChannelEnd, LinkError> {
Ok(self
.src_chain()
.query_channel(self.src_port_id(), self.src_channel_id()?, height)
.map_err(|e| ChannelError::QueryError(self.src_chain().id(), e))?)
}
fn dst_channel(&self, height: Height) -> Result<ChannelEnd, LinkError> {
Ok(self
.dst_chain()
.query_channel(self.dst_port_id(), self.dst_channel_id()?, height)
.map_err(|e| ChannelError::QueryError(self.src_chain().id(), e))?)
}
fn src_signer(&self) -> Result<Signer, LinkError> {
self.src_chain().get_signer().map_err(|e| {
LinkError::Failed(format!(
"could not retrieve signer from src chain {} with error: {}",
self.src_chain().id(),
e
))
})
}
fn dst_signer(&self) -> Result<Signer, LinkError> {
self.dst_chain().get_signer().map_err(|e| {
LinkError::Failed(format!(
"could not retrieve signer from dst chain {} with error: {}",
self.dst_chain().id(),
e
))
})
}
pub fn dst_latest_height(&self) -> Result<Height, LinkError> {
self.dst_chain()
.query_latest_height()
.map_err(|e| LinkError::QueryError(self.dst_chain().id(), e))
}
fn unordered_channel(&self) -> bool {
self.channel.ordering == Order::Unordered
}
fn ordered_channel(&self) -> bool {
self.channel.ordering == Order::Ordered
}
pub fn build_update_client_on_dst(&self, height: Height) -> Result<Vec<Any>, LinkError> {
let client = self.restore_dst_client();
client
.build_update_client(height)
.map_err(LinkError::ClientError)
}
pub fn build_update_client_on_src(&self, height: Height) -> Result<Vec<Any>, LinkError> {
let client = self.restore_src_client();
client
.build_update_client(height)
.map_err(LinkError::ClientError)
}
fn build_chan_close_confirm_from_event(&self, event: &IbcEvent) -> Result<Any, LinkError> {
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| ChannelError::Failed(format!("failed to build channel proofs: {}", e)))?;
// Build the domain type message
let new_msg = MsgChannelCloseConfirm {
port_id: self.dst_port_id().clone(),
channel_id: src_channel_id.clone(),
proofs,
signer: self.dst_signer()?,
};
Ok(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_events(&self, events: &[IbcEvent]) -> Vec<IbcEvent> {
let mut result = vec![];
let src_channel_id = if let Ok(some_id) = self.src_channel_id() {
some_id
} else {
return vec![];
};
for event in events.iter() {
match 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.clone());
}
}
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.clone());
}
}
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.clone());
}
}
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.clone());
}
}
_ => {}
}
}
result
}
fn relay_pending_packets(&mut self, height: Height) -> Result<(), LinkError> {
info!("[{}] clearing old packets", self);
for _ in 0..MAX_RETRIES {
if self
.build_recv_packet_and_timeout_msgs(Some(height))
.is_ok()
&& self.build_packet_ack_msgs(Some(height)).is_ok()
{
return Ok(());
}
}
Err(LinkError::OldPacketClearingFailed)
}
/// Should not run more than once per execution.
pub fn clear_packets(&mut self, above_height: Height) -> Result<(), LinkError> {
if self.clear_packets {
info!(
"[{}] clearing pending packets from events before height {}",
self, above_height
);
let clear_height = above_height.decrement().map_err(|e| LinkError::Failed(
format!("Cannot clear packets @height {}, because this height cannot be decremented: {}", above_height, e.to_string())))?;
self.relay_pending_packets(clear_height)?;
info!("[{}] finished clearing pending packets", self);
self.clear_packets = false;
}
Ok(())
}
/// Generate & schedule operational data from the input `batch` of IBC events.
pub fn update_schedule(&mut self, batch: EventBatch) -> Result<(), LinkError> {
self.clear_packets(batch.height)?;
// Collect relevant events from the incoming batch & adjust their height.
let events = self.filter_events(&batch.events);
// 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.
fn events_to_operational_data(&mut self, events: Vec<IbcEvent>) -> 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,
input: Vec<IbcEvent>,
) -> Result<(Option<OperationalData>, Option<OperationalData>), LinkError> {
if !input.is_empty() {
info!(
"[{}] generate messages from batch with {} events",
self,
input.len()
);
}
let src_height = match input.get(0) {
None => return Ok((None, None)),
Some(ev) => ev.height(),
};
let dst_height = self.dst_latest_height()?;
// Operational data targeting the source chain (e.g., Timeout packets)
let mut src_od = OperationalData::new(dst_height, OperationalDataTarget::Source);
// Operational data targeting the destination chain (e.g., SendPacket messages)
let mut dst_od = OperationalData::new(src_height, OperationalDataTarget::Destination);
for event in input {
debug!("[{}] {} => {}", self, self.src_chain().id(), event);
let (dst_msg, src_msg) = match event {
IbcEvent::CloseInitChannel(_) => (
Some(self.build_chan_close_confirm_from_event(&event)?),
None,
),
IbcEvent::TimeoutPacket(ref timeout_ev) => {
// 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(timeout_ev.height)?
.state_matches(&ChannelState::Closed)
{
(
Some(self.build_chan_close_confirm_from_event(&event)?),
None,
)
} else {
(None, None)
}
}
IbcEvent::SendPacket(ref send_packet_ev) => {
if self.send_packet_event_handled(send_packet_ev)? {
debug!("[{}] {} already handled", self, send_packet_ev);
(None, None)
} else {
self.build_recv_or_timeout_from_send_packet_event(
send_packet_ev,
dst_height,
)?
}
}
IbcEvent::WriteAcknowledgement(ref write_ack_ev) => {
if self
.dst_channel(Height::zero())?
.state_matches(&ChannelState::Closed)
{
(None, None)
} else if self.write_ack_event_handled(write_ack_ev)? {
debug!("[{}] {} already handled", self, write_ack_ev);
(None, None)
} else {
(self.build_ack_from_recv_event(write_ack_ev)?, None)
}
}
_ => (None, None),
};
// Collect messages to be sent to the destination chain (e.g., RecvPacket)
if let Some(msg) = dst_msg {
debug!(
"[{}] {} <= {} from {}",
self,
self.dst_chain().id(),
msg.type_url,
event
);
dst_od.batch.push(TransitMessage {
event: event.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() {
debug!(
"[{}] {} <= {} from {}",
self,
self.src_chain().id(),
msg.type_url,
event
);
src_od.batch.push(TransitMessage { event, msg });
}
}
}
let src_od_res = if src_od.batch.is_empty() {
None
} else {
Some(src_od)
};
let dst_od_res = if dst_od.batch.is_empty() {
None
} else {
Some(dst_od)
};
Ok((src_od_res, dst_od_res))
}
/// Returns the events generated by the target chain
fn relay_from_operational_data(
&mut self,
initial_od: OperationalData,
) -> Result<RelaySummary, LinkError> {
// We will operate on potentially different operational data if the initial one fails.
let mut odata = initial_od;
for i in 0..MAX_RETRIES {
info!(
"[{}] relay op. data to {}, proofs height {}, (delayed by: {:?}) [try {}/{}]",
self,
odata.target,
odata.proofs_height,
odata.scheduled_time.elapsed(),
i + 1,
MAX_RETRIES
);
// Consume the operational data by attempting to send its messages
match self.send_from_operational_data(odata.clone()) {
Ok(summary) => {
// Done with this op. data
info!("[{}] success", self);
return Ok(summary);
}
Err(LinkError::SendError(ev)) => {
// This error means we could retry
error!("[{}] error {}", self, ev);
if i + 1 == MAX_RETRIES {
error!(
"[{}] {}/{} retries exhausted. giving up",
self,
i + 1,
MAX_RETRIES
)
} else {
// If we haven't exhausted all retries, regenerate the op. data & retry
match self.regenerate_operational_data(odata.clone()) {
None => return Ok(RelaySummary::empty()), // Nothing to retry
Some(new_od) => odata = new_od,
}
}
}
Err(e) => {
// Unrecoverable error, propagate up the stack
return Err(e);
}
}
}
Ok(RelaySummary::empty())
}
/// Helper for managing retries of the `relay_from_operational_data` method.
/// Expects as input 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.
fn regenerate_operational_data(
&mut self,
initial_odata: OperationalData,
) -> Option<OperationalData> {
info!(
"[{}] failed. Regenerate operational data from {} events",
self,
initial_odata.events().len()
);
// Retry by re-generating the operational data using the initial events
let (src_opt, dst_opt) = match self.generate_operational_data(initial_odata.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",
self, initial_odata, e
);
return None;
} // Cannot retry, contain the error by reporting a None
};
if let Some(src_od) = src_opt {
if src_od.target == initial_odata.target {
// Our target is the _source_ chain, retry these messages
info!("[{}] will retry with op data {}", self, src_od);
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",
self, initial_odata, e
);
return None;
}
}
}
if let Some(dst_od) = dst_opt {
if dst_od.target == initial_odata.target {
// Our target is the _destination_ chain, retry these messages
info!("[{}] will retry with op data {}", self, dst_od);
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!",
self
);
}
} else {
// There is no message intended for the destination chain
if initial_odata.target == OperationalDataTarget::Destination {
info!("[{}] exhausted all events from this operational data", self);
return None;
}
}
None
}
/// Sends a transaction to the chain targeted by the operational data `odata`.
/// If the transaction generates an error, returns the error as well as `LinkError::SendError` if input events if a sending failure occurs.
/// Returns the events generated by the target chain upon success.
fn send_from_operational_data(
&mut self,
odata: OperationalData,
) -> Result<RelaySummary, LinkError> {
if odata.batch.is_empty() {
error!("[{}] ignoring empty operational data!", self);
return Ok(RelaySummary::empty());
}
let target = match odata.target {
OperationalDataTarget::Source => self.src_chain(),
OperationalDataTarget::Destination => self.dst_chain(),
};
let msgs = odata.assemble_msgs(self)?;
let tx_events = target.send_msgs(msgs)?;
info!("[{}] result {}\n", self, PrettyEvents(&tx_events));
let ev = tx_events
.clone()
.into_iter()
.find(|event| matches!(event, IbcEvent::ChainError(_)));
match ev {
Some(ev) => Err(LinkError::SendError(Box::new(ev))),
None => Ok(RelaySummary::from_events(tx_events)),
}
}
/// 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().to_string(),
channel_id: self.dst_channel_id()?.to_string(),
packet_commitment_sequences: vec![packet.sequence.into()],
})?;
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().build_packet_proofs(
PacketMsgType::Recv,
self.src_port_id(),
self.src_channel_id()?,
packet.sequence,
Height::zero(),
)?;
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_acknowledgement(QueryUnreceivedAcksRequest {
port_id: self.dst_port_id().to_string(),
channel_id: self.dst_channel_id()?.to_string(),
packet_ack_sequences: vec![packet.sequence.into()],
})?;
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 `true` if the delay for this relaying path is zero.
/// Conversely, returns `false` if the delay is non-zero.
fn zero_delay(&self) -> bool {
self.channel.connection_delay == ZERO_DURATION
}
/// Handles updating the client on the destination chain
fn update_client_dst(&self, src_chain_height: Height) -> Result<(), LinkError> {
// Handle the update on the destination chain
// Check if a consensus state at update_height exists on destination chain already
if self
.dst_chain()
.proven_client_consensus(self.dst_client_id(), src_chain_height, Height::zero())
.is_ok()
{
return Ok(());
}
let mut dst_err_ev = None;
for i in 0..MAX_RETRIES {
let dst_update = self.build_update_client_on_dst(src_chain_height)?;
info!(
"[{}] sending updateClient to client hosted on dest. chain {} for height {} [try {}/{}]",
self,
self.dst_chain().id(),
src_chain_height,
i + 1, MAX_RETRIES,
);
let dst_tx_events = self.dst_chain().send_msgs(dst_update)?;
info!("[{}] result {}\n", self, PrettyEvents(&dst_tx_events));
dst_err_ev = dst_tx_events
.into_iter()
.find(|event| matches!(event, IbcEvent::ChainError(_)));
if dst_err_ev.is_none() {
return Ok(());
}
}
Err(LinkError::ClientError(ForeignClientError::ClientUpdate(
format!(
"Failed to update client on destination {} with err: {}",
self.dst_chain().id(),
dst_err_ev.unwrap()
),
)))
}
/// Handles updating the client on the source chain
fn update_client_src(&self, dst_chain_height: Height) -> Result<(), LinkError> {
if self
.src_chain()
.proven_client_consensus(self.src_client_id(), dst_chain_height, Height::zero())
.is_ok()
{
return Ok(());
}
let mut src_err_ev = None;
for _ in 0..MAX_RETRIES {
let src_update = self.build_update_client_on_src(dst_chain_height)?;
info!(
"[{}] sending updateClient to client hosted on src. chain {} for height {}",
self,
self.src_chain().id(),
dst_chain_height,
);
let src_tx_events = self.src_chain().send_msgs(src_update)?;
info!("[{}] result {}\n", self, PrettyEvents(&src_tx_events));
src_err_ev = src_tx_events
.into_iter()
.find(|event| matches!(event, IbcEvent::ChainError(_)));
if src_err_ev.is_none() {
return Ok(());
}
}
Err(LinkError::ClientError(ForeignClientError::ClientUpdate(
format!(
"Failed to update client on source {} with err: {}",
self.src_chain().id(),
src_err_ev.unwrap()
),
)))
}
/// Returns relevant packet events for building RecvPacket and timeout messages.
/// Additionally returns the height (on source chain) corresponding to these events.
fn target_height_and_send_packet_events(
&self,
opt_query_height: Option<Height>,
) -> Result<(Vec<IbcEvent>, Height), LinkError> {
let mut events_result = vec![];
let src_channel_id = self.src_channel_id()?;
// Query packet commitments on source chain that have not been acknowledged
let pc_request = QueryPacketCommitmentsRequest {
port_id: self.src_port_id().to_string(),
channel_id: src_channel_id.to_string(),
pagination: ibc_proto::cosmos::base::query::pagination::all(),
};
let (packet_commitments, src_response_height) =
self.src_chain().query_packet_commitments(pc_request)?;
let query_height = opt_query_height.unwrap_or(src_response_height);
if packet_commitments.is_empty() {
return Ok((events_result, query_height));
}
let commit_sequences = packet_commitments.iter().map(|p| p.sequence).collect();
debug!(
"[{}] packets that still have commitments on {}: {:?}",
self,
self.src_chain().id(),
commit_sequences
);
// Get the packets that have not been received on destination chain
let request = QueryUnreceivedPacketsRequest {
port_id: self.dst_port_id().to_string(),
channel_id: self.dst_channel_id()?.to_string(),
packet_commitment_sequences: commit_sequences,
};
let sequences: Vec<Sequence> = self
.dst_chain()
.query_unreceived_packets(request)?
.into_iter()
.map(From::from)
.collect();
debug!(
"[{}] recv packets to send out to {} of the ones with commitments on source {}: {:?}",
self,
self.dst_chain().id(),
self.src_chain().id(),
sequences
);
if sequences.is_empty() {
return Ok((events_result, query_height));
}
let query = QueryTxRequest::Packet(QueryPacketEventDataRequest {
event_id: IbcEventType::SendPacket,
source_port_id: self.src_port_id().clone(),
source_channel_id: src_channel_id.clone(),
destination_port_id: self.dst_port_id().clone(),
destination_channel_id: self.dst_channel_id()?.clone(),
sequences,
height: query_height,
});
events_result = self.src_chain().query_txs(query)?;
let mut packet_sequences = vec![];
for event in events_result.iter() {
let send_event = downcast!(event => IbcEvent::SendPacket)
.ok_or_else(|| LinkError::Failed("unexpected query tx response".into()))?;
packet_sequences.push(send_event.packet.sequence);
}
debug!("[{}] received from query_txs {:?}", self, packet_sequences);
Ok((events_result, query_height))
}
/// Returns relevant packet events for building ack messages.
/// Additionally returns the height (on source chain) corresponding to these events.
fn target_height_and_write_ack_events(
&self,
opt_query_height: Option<Height>,
) -> Result<(Vec<IbcEvent>, Height), LinkError> {
let mut events_result = vec![];
let src_channel_id = self.src_channel_id()?;
let dst_channel_id = self.dst_channel_id()?;
// Get the sequences of packets that have been acknowledged on source
let pc_request = QueryPacketAcknowledgementsRequest {
port_id: self.src_port_id().to_string(),
channel_id: src_channel_id.to_string(),
pagination: ibc_proto::cosmos::base::query::pagination::all(),
};
let (acks_on_source, src_response_height) = self
.src_chain()
.query_packet_acknowledgements(pc_request)