-
Notifications
You must be signed in to change notification settings - Fork 766
/
Copy pathlib.rs
1566 lines (1443 loc) · 55 KB
/
lib.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
// Copyright 2019-2021 Parity Technologies (UK) Ltd.
// This file is part of Parity Bridges Common.
// Parity Bridges Common is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity Bridges Common is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity Bridges Common. If not, see <http://www.gnu.org/licenses/>.
//! Module that adds XCM support to bridge pallets. The pallet allows to dynamically
//! open and close bridges between local (to this pallet location) and remote XCM
//! destinations.
//!
//! The `pallet_xcm_bridge_hub` pallet is used to manage (open, close) bridges between chains from
//! different consensuses. The new extrinsics `fn open_bridge` and `fn close_bridge` are introduced.
//! Other chains can manage channels with different bridged global consensuses.
//!
//! # Concept of `lane` and `LaneId`
//!
//! There is another `pallet_bridge_messages` pallet that handles inbound/outbound lanes for
//! messages. Each lane is a unique connection between two chains from different consensuses and is
//! identified by `LaneId`. `LaneId` is generated once when a new bridge is requested by `fn
//! open_bridge`. It is generated by `BridgeLocations::calculate_lane_id` based on the following
//! parameters:
//! - Source `bridge_origin_universal_location` (latest XCM)
//! - Destination `bridge_destination_universal_location` (latest XCM)
//! - XCM version (both sides of the bridge must use the same parameters to generate the same
//! `LaneId`)
//! - `bridge_origin_universal_location`, `bridge_destination_universal_location` is converted to
//! the `Versioned*` structs
//!
//! `LaneId` is expected to never change because:
//! - We need the same `LaneId` on both sides of the bridge, as `LaneId` is part of the message key
//! proofs.
//! - Runtime upgrades are entirely asynchronous.
//! - We already have a running production Polkadot/Kusama bridge that uses `LaneId([0, 0, 0, 0])`.
//!
//! `LaneId` is backward compatible, meaning it can be encoded/decoded from the older format `[u8;
//! 4]` used for static lanes, as well as the new format `H256` generated by
//! `BridgeLocations::calculate_lane_id`.
//!
//! # Concept of `bridge` and `BridgeId`
//!
//! The `pallet_xcm_bridge_hub` pallet needs to store some metadata about opened bridges. The bridge
//! (or bridge metadata) is stored under the `BridgeId` key.
//!
//! `BridgeId` is generated from `bridge_origin_relative_location` and
//! `bridge_origin_universal_location` using the `latest` XCM structs. `BridgeId` is not transferred
//! over the bridge; it is only important for local consensus. It essentially serves as an index/key
//! to bridge metadata. All the XCM infrastructure around `XcmExecutor`, `SendXcm`, `ExportXcm` use
//! the `latest` XCM, so `BridgeId` must remain compatible with the `latest` XCM. For example, we
//! have an `ExportXcm` implementation in `exporter.rs` that handles the `ExportMessage` instruction
//! with `universal_source` and `destination` (latest XCM), so we need to create `BridgeId` and the
//! corresponding `LaneId`.
//!
//! # Migrations and State
//!
//! This pallet implements `try_state`, ensuring compatibility and checking everything so we know if
//! any migration is needed. `do_try_state` checks for `BridgeId` compatibility, which is
//! recalculated on runtime upgrade. Upgrading to a new XCM version should not break anything,
//! except removing older XCM versions. In such cases, we need to add migration for `BridgeId` and
//! stored `Versioned*` structs and update `LaneToBridge` mapping, but this won't affect `LaneId`
//! over the bridge.
//!
//! # How to Open a Bridge?
//!
//! The `pallet_xcm_bridge_hub` pallet has the extrinsic `fn open_bridge` and an important
//! configuration `pallet_xcm_bridge_hub::Config::OpenBridgeOrigin`, which translates the call's
//! origin to the XCM `Location` and converts it to the `bridge_origin_universal_location`. With the
//! current setup, this origin/location is expected to be either the relay chain or a sibling
//! parachain as one side of the bridge. Another parameter is
//! `bridge_destination_universal_location`, which is the other side of the bridge from a different
//! global consensus.
//!
//! Every bridge between two XCM locations has a dedicated lane in associated
//! messages pallet. Assuming that this pallet is deployed at the bridge hub
//! parachain and there's a similar pallet at the bridged network, the dynamic
//! bridge lifetime is as follows:
//!
//! 1) the sibling parachain opens a XCMP channel with this bridge hub;
//!
//! 2) the sibling parachain funds its sovereign parachain account at this bridge hub. It shall hold
//! enough funds to pay for the bridge (see `BridgeDeposit`);
//!
//! 3) the sibling parachain opens the bridge by sending XCM `Transact` instruction with the
//! `open_bridge` call. The `BridgeDeposit` amount is reserved on the sovereign account of
//! sibling parachain;
//!
//! 4) at the other side of the bridge, the same thing (1, 2, 3) happens. Parachains that need to
//! connect over the bridge need to coordinate the moment when they start sending messages over
//! the bridge. Otherwise they may lose messages and/or bundled assets;
//!
//! 5) when either side wants to close the bridge, it sends the XCM `Transact` with the
//! `close_bridge` call. The bridge is closed immediately if there are no queued messages.
//! Otherwise, the owner must repeat the `close_bridge` call to prune all queued messages first.
//!
//! The pallet doesn't provide any mechanism for graceful closure, because it always involves
//! some contract between two connected chains and the bridge hub knows nothing about that. It
//! is the task for the connected chains to make sure that all required actions are completed
//! before the closure. In the end, the bridge hub can't even guarantee that all messages that
//! are delivered to the destination, are processed in the way their sender expects. So if we
//! can't guarantee that, we shall not care about more complex procedures and leave it to the
//! participating parties.
//!
//! # Example
//!
//! Example of opening a bridge between some random parachains from Polkadot and Kusama:
//!
//! 1. The local sibling parachain `Location::new(1, Parachain(1234))` must send some DOTs to its
//! sovereign account on BridgeHubPolkadot to cover `BridgeDeposit`, fees for `Transact`, and the
//! existential deposit.
//! 2. Send a call to the BridgeHubPolkadot from the local sibling parachain: `Location::new(1,
//! Parachain(1234))` ``` xcm::Transact( origin_kind: OriginKind::Xcm,
//! XcmOverBridgeHubKusama::open_bridge( VersionedInteriorLocation::V4([GlobalConsensus(Kusama),
//! Parachain(4567)].into()), ); ) ```
//! 3. Check the stored bridge metadata and generated `LaneId`.
//! 4. The local sibling parachain `Location::new(1, Parachain(4567))` must send some KSMs to its
//! sovereign account
//! on BridgeHubKusama to cover `BridgeDeposit`, fees for `Transact`, and the existential deposit.
//! 5. Send a call to the BridgeHubKusama from the local sibling parachain: `Location::new(1,
//! Parachain(4567))` ``` xcm::Transact( origin_kind: OriginKind::Xcm,
//! XcmOverBridgeHubKusama::open_bridge(
//! VersionedInteriorLocation::V4([GlobalConsensus(Polkadot), Parachain(1234)].into()), ); ) ```
//! 6. Check the stored bridge metadata and generated `LaneId`.
//! 7. Run the bridge messages relayer for `LaneId`.
//! 8. Send messages from both sides.
//!
//! The opening bridge holds the configured `BridgeDeposit` from the origin's sovereign account, but
//! this deposit is returned when the bridge is closed with `fn close_bridge`.
#![warn(missing_docs)]
#![cfg_attr(not(feature = "std"), no_std)]
use bp_messages::{LaneId, LaneState, MessageNonce};
use bp_runtime::{AccountIdOf, BalanceOf, RangeInclusiveExt};
use bp_xcm_bridge_hub::{
Bridge, BridgeId, BridgeLocations, BridgeLocationsError, BridgeState, LocalXcmChannelManager,
};
use frame_support::{traits::fungible::MutateHold, DefaultNoBound};
use frame_system::Config as SystemConfig;
use pallet_bridge_messages::{Config as BridgeMessagesConfig, LanesManagerError};
use sp_runtime::traits::Zero;
use sp_std::{boxed::Box, vec::Vec};
use xcm::prelude::*;
use xcm_builder::DispatchBlob;
use xcm_executor::traits::ConvertLocation;
pub use bp_xcm_bridge_hub::XcmAsPlainPayload;
pub use dispatcher::XcmBlobMessageDispatchResult;
pub use exporter::PalletAsHaulBlobExporter;
pub use pallet::*;
mod dispatcher;
mod exporter;
mod mock;
/// The target that will be used when publishing logs related to this pallet.
pub const LOG_TARGET: &str = "runtime::bridge-xcm";
#[frame_support::pallet]
pub mod pallet {
use super::*;
use frame_support::{
pallet_prelude::*,
traits::{tokens::Precision, Contains},
};
use frame_system::pallet_prelude::{BlockNumberFor, *};
/// The reason for this pallet placing a hold on funds.
#[pallet::composite_enum]
pub enum HoldReason<I: 'static = ()> {
/// The funds are held as a deposit for opened bridge.
#[codec(index = 0)]
BridgeDeposit,
}
#[pallet::config]
#[pallet::disable_frame_system_supertrait_check]
pub trait Config<I: 'static = ()>:
BridgeMessagesConfig<Self::BridgeMessagesPalletInstance>
{
/// The overarching event type.
type RuntimeEvent: From<Event<Self, I>>
+ IsType<<Self as frame_system::Config>::RuntimeEvent>;
/// Runtime's universal location.
type UniversalLocation: Get<InteriorLocation>;
// TODO: https://github.com/paritytech/parity-bridges-common/issues/1666 remove `ChainId` and
// replace it with the `NetworkId` - then we'll be able to use
// `T as pallet_bridge_messages::Config<T::BridgeMessagesPalletInstance>::BridgedChain::NetworkId`
/// Bridged network as relative location of bridged `GlobalConsensus`.
#[pallet::constant]
type BridgedNetwork: Get<Location>;
/// Associated messages pallet instance that bridges us with the
/// `BridgedNetworkId` consensus.
type BridgeMessagesPalletInstance: 'static;
/// Price of single message export to the bridged consensus (`Self::BridgedNetwork`).
type MessageExportPrice: Get<Assets>;
/// Checks the XCM version for the destination.
type DestinationVersion: GetVersion;
/// The origin that is allowed to call privileged operations on the pallet, e.g. open/close
/// bridge for location that coresponds to `Self::BridgeOriginAccountIdConverter` and
/// `Self::BridgedNetwork`.
type AdminOrigin: EnsureOrigin<<Self as SystemConfig>::RuntimeOrigin>;
/// A set of XCM locations within local consensus system that are allowed to open
/// bridges with remote destinations.
type OpenBridgeOrigin: EnsureOrigin<
<Self as SystemConfig>::RuntimeOrigin,
Success = Location,
>;
/// A converter between a location and a sovereign account.
type BridgeOriginAccountIdConverter: ConvertLocation<AccountIdOf<ThisChainOf<Self, I>>>;
/// Amount of this chain native tokens that is reserved on the sibling parachain account
/// when bridge open request is registered.
#[pallet::constant]
type BridgeDeposit: Get<BalanceOf<ThisChainOf<Self, I>>>;
/// Currency used to pay for bridge registration.
type Currency: MutateHold<
AccountIdOf<ThisChainOf<Self, I>>,
Balance = BalanceOf<ThisChainOf<Self, I>>,
Reason = Self::RuntimeHoldReason,
>;
/// The overarching runtime hold reason.
type RuntimeHoldReason: From<HoldReason<I>>;
/// Do not hold `Self::BridgeDeposit` for the location of `Self::OpenBridgeOrigin`.
/// For example, it is possible to make an exception for a system parachain or relay.
type AllowWithoutBridgeDeposit: Contains<Location>;
/// Local XCM channel manager.
type LocalXcmChannelManager: LocalXcmChannelManager;
/// XCM-level dispatcher for inbound bridge messages.
type BlobDispatcher: DispatchBlob;
}
/// An alias for the bridge metadata.
pub type BridgeOf<T, I> = Bridge<ThisChainOf<T, I>>;
/// An alias for this chain.
pub type ThisChainOf<T, I> =
pallet_bridge_messages::ThisChainOf<T, <T as Config<I>>::BridgeMessagesPalletInstance>;
/// An alias for the associated lanes manager.
pub type LanesManagerOf<T, I> =
pallet_bridge_messages::LanesManager<T, <T as Config<I>>::BridgeMessagesPalletInstance>;
#[pallet::pallet]
pub struct Pallet<T, I = ()>(PhantomData<(T, I)>);
#[pallet::hooks]
impl<T: Config<I>, I: 'static> Hooks<BlockNumberFor<T>> for Pallet<T, I> {
fn integrity_test() {
assert!(
Self::bridged_network_id().is_ok(),
"Configured `T::BridgedNetwork`: {:?} does not contain `GlobalConsensus` junction with `NetworkId`",
T::BridgedNetwork::get()
)
}
#[cfg(feature = "try-runtime")]
fn try_state(_n: BlockNumberFor<T>) -> Result<(), sp_runtime::TryRuntimeError> {
Self::do_try_state()
}
}
#[pallet::call]
impl<T: Config<I>, I: 'static> Pallet<T, I> {
/// Open a bridge between two locations.
///
/// The caller must be within the `T::OpenBridgeOrigin` filter (presumably: a sibling
/// parachain or a parent relay chain). The `bridge_destination_universal_location` must be
/// a destination within the consensus of the `T::BridgedNetwork` network.
///
/// The `BridgeDeposit` amount is reserved on the caller account. This deposit
/// is unreserved after bridge is closed.
///
/// The states after this call: bridge is `Opened`, outbound lane is `Opened`, inbound lane
/// is `Opened`.
#[pallet::call_index(0)]
#[pallet::weight(Weight::zero())] // TODO:(bridges-v2) - https://github.com/paritytech/polkadot-sdk/pull/4949 - add benchmarks impl - FAIL-CI
pub fn open_bridge(
origin: OriginFor<T>,
bridge_destination_universal_location: Box<VersionedInteriorLocation>,
) -> DispatchResult {
// check and compute required bridge locations and laneId
let xcm_version = bridge_destination_universal_location.identify_version();
let locations =
Self::bridge_locations_from_origin(origin, bridge_destination_universal_location)?;
let lane_id = locations.calculate_lane_id(xcm_version).map_err(|e| {
log::trace!(
target: LOG_TARGET,
"calculate_lane_id error: {e:?}",
);
Error::<T, I>::BridgeLocations(e)
})?;
// reserve balance on the origin's sovereign account
let deposit = if T::AllowWithoutBridgeDeposit::contains(
locations.bridge_origin_relative_location(),
) {
BalanceOf::<ThisChainOf<T, I>>::zero()
} else {
T::BridgeDeposit::get()
};
let bridge_owner_account = T::BridgeOriginAccountIdConverter::convert_location(
locations.bridge_origin_relative_location(),
)
.ok_or(Error::<T, I>::InvalidBridgeOriginAccount)?;
T::Currency::hold(&HoldReason::BridgeDeposit.into(), &bridge_owner_account, deposit)
.map_err(|_| Error::<T, I>::FailedToReserveBridgeDeposit)?;
// save bridge metadata
Bridges::<T, I>::try_mutate(locations.bridge_id(), |bridge| match bridge {
Some(_) => Err(Error::<T, I>::BridgeAlreadyExists),
None => {
*bridge = Some(BridgeOf::<T, I> {
bridge_origin_relative_location: Box::new(
locations.bridge_origin_relative_location().clone().into(),
),
bridge_origin_universal_location: Box::new(
locations.bridge_origin_universal_location().clone().into(),
),
bridge_destination_universal_location: Box::new(
locations.bridge_destination_universal_location().clone().into(),
),
state: BridgeState::Opened,
bridge_owner_account,
deposit,
lane_id,
});
Ok(())
},
})?;
// save lane to bridge mapping
LaneToBridge::<T, I>::try_mutate(lane_id, |bridge| match bridge {
Some(_) => Err(Error::<T, I>::BridgeAlreadyExists),
None => {
*bridge = Some(*locations.bridge_id());
Ok(())
},
})?;
// create new lanes. Under normal circumstances, following calls shall never fail
let lanes_manager = LanesManagerOf::<T, I>::new();
lanes_manager
.create_inbound_lane(lane_id)
.map_err(Error::<T, I>::LanesManager)?;
lanes_manager
.create_outbound_lane(lane_id)
.map_err(Error::<T, I>::LanesManager)?;
// write something to log
log::trace!(
target: LOG_TARGET,
"Bridge {:?} between {:?} and {:?} has been opened using lane_id: {lane_id:?}",
locations.bridge_id(),
locations.bridge_origin_universal_location(),
locations.bridge_destination_universal_location(),
);
// deposit `BridgeOpened` event
Self::deposit_event(Event::<T, I>::BridgeOpened {
bridge_id: *locations.bridge_id(),
bridge_deposit: deposit,
local_endpoint: Box::new(locations.bridge_origin_universal_location().clone()),
remote_endpoint: Box::new(
locations.bridge_destination_universal_location().clone(),
),
lane_id,
});
Ok(())
}
/// Try to close the bridge.
///
/// Can only be called by the "owner" of this side of the bridge, meaning that the
/// inbound XCM channel with the local origin chain is working.
///
/// Closed bridge is a bridge without any traces in the runtime storage. So this method
/// first tries to prune all queued messages at the outbound lane. When there are no
/// outbound messages left, outbound and inbound lanes are purged. After that, funds
/// are returned back to the owner of this side of the bridge.
///
/// The number of messages that we may prune in a single call is limited by the
/// `may_prune_messages` argument. If there are more messages in the queue, the method
/// prunes exactly `may_prune_messages` and exits early. The caller may call it again
/// until outbound queue is depleted and get his funds back.
///
/// The states after this call: everything is either `Closed`, or purged from the
/// runtime storage.
#[pallet::call_index(1)]
#[pallet::weight(Weight::zero())] // TODO:(bridges-v2) - https://github.com/paritytech/polkadot-sdk/pull/4949 - add benchmarks impl - FAIL-CI
pub fn close_bridge(
origin: OriginFor<T>,
bridge_destination_universal_location: Box<VersionedInteriorLocation>,
may_prune_messages: MessageNonce,
) -> DispatchResult {
// compute required bridge locations
let locations =
Self::bridge_locations_from_origin(origin, bridge_destination_universal_location)?;
// TODO: https://github.com/paritytech/parity-bridges-common/issues/1760 - may do refund here, if
// bridge/lanes are already closed + for messages that are not pruned
// update bridge metadata - this also guarantees that the bridge is in the proper state
let bridge =
Bridges::<T, I>::try_mutate_exists(locations.bridge_id(), |bridge| match bridge {
Some(bridge) => {
bridge.state = BridgeState::Closed;
Ok(bridge.clone())
},
None => Err(Error::<T, I>::UnknownBridge),
})?;
// close inbound and outbound lanes
let lanes_manager = LanesManagerOf::<T, I>::new();
let mut inbound_lane = lanes_manager
.any_state_inbound_lane(bridge.lane_id)
.map_err(Error::<T, I>::LanesManager)?;
let mut outbound_lane = lanes_manager
.any_state_outbound_lane(bridge.lane_id)
.map_err(Error::<T, I>::LanesManager)?;
// now prune queued messages
let mut pruned_messages = 0;
for _ in outbound_lane.queued_messages() {
if pruned_messages == may_prune_messages {
break
}
outbound_lane.remove_oldest_unpruned_message();
pruned_messages += 1;
}
// if there are outbound messages in the queue, just update states and early exit
if !outbound_lane.queued_messages().is_empty() {
// update lanes state. Under normal circumstances, following calls shall never fail
inbound_lane.set_state(LaneState::Closed);
outbound_lane.set_state(LaneState::Closed);
// write something to log
let enqueued_messages = outbound_lane.queued_messages().saturating_len();
log::trace!(
target: LOG_TARGET,
"Bridge {:?} between {:?} and {:?} is closing lane_id: {:?}. {} messages remaining",
locations.bridge_id(),
locations.bridge_origin_universal_location(),
locations.bridge_destination_universal_location(),
bridge.lane_id,
enqueued_messages,
);
// deposit the `ClosingBridge` event
Self::deposit_event(Event::<T, I>::ClosingBridge {
bridge_id: *locations.bridge_id(),
lane_id: bridge.lane_id,
pruned_messages,
enqueued_messages,
});
return Ok(())
}
// else we have pruned all messages, so lanes and the bridge itself may gone
inbound_lane.purge();
outbound_lane.purge();
Bridges::<T, I>::remove(locations.bridge_id());
LaneToBridge::<T, I>::remove(bridge.lane_id);
// return deposit
let released_deposit = T::Currency::release(
&HoldReason::BridgeDeposit.into(),
&bridge.bridge_owner_account,
bridge.deposit,
Precision::BestEffort,
)
.map_err(|e| {
// we can't do anything here - looks like funds have been (partially) unreserved
// before by someone else. Let's not fail, though - it'll be worse for the caller
log::error!(
target: LOG_TARGET,
"Failed to unreserve during the bridge {:?} closure with error: {e:?}",
locations.bridge_id(),
);
e
})
.ok()
.unwrap_or(BalanceOf::<ThisChainOf<T, I>>::zero());
// write something to log
log::trace!(
target: LOG_TARGET,
"Bridge {:?} between {:?} and {:?} has closed lane_id: {:?}, the bridge deposit {released_deposit:?} was returned",
locations.bridge_id(),
bridge.lane_id,
locations.bridge_origin_universal_location(),
locations.bridge_destination_universal_location(),
);
// deposit the `BridgePruned` event
Self::deposit_event(Event::<T, I>::BridgePruned {
bridge_id: *locations.bridge_id(),
lane_id: bridge.lane_id,
bridge_deposit: released_deposit,
pruned_messages,
});
Ok(())
}
}
impl<T: Config<I>, I: 'static> Pallet<T, I> {
/// Return bridge endpoint locations and dedicated lane identifier. This method converts
/// runtime `origin` argument to relative `Location` using the `T::OpenBridgeOrigin`
/// converter.
pub fn bridge_locations_from_origin(
origin: OriginFor<T>,
bridge_destination_universal_location: Box<VersionedInteriorLocation>,
) -> Result<Box<BridgeLocations>, sp_runtime::DispatchError> {
Self::bridge_locations(
T::OpenBridgeOrigin::ensure_origin(origin)?,
(*bridge_destination_universal_location)
.try_into()
.map_err(|_| Error::<T, I>::UnsupportedXcmVersion)?,
)
}
/// Return bridge endpoint locations and dedicated **bridge** identifier (`BridgeId`).
pub fn bridge_locations(
bridge_origin_relative_location: Location,
bridge_destination_universal_location: InteriorLocation,
) -> Result<Box<BridgeLocations>, sp_runtime::DispatchError> {
BridgeLocations::bridge_locations(
T::UniversalLocation::get(),
bridge_origin_relative_location,
bridge_destination_universal_location,
Self::bridged_network_id()?,
)
.map_err(|e| {
log::trace!(
target: LOG_TARGET,
"bridge_locations error: {e:?}",
);
Error::<T, I>::BridgeLocations(e).into()
})
}
/// Return bridge metadata by lane_id
pub fn bridge_by_lane_id(lane_id: &LaneId) -> Option<(BridgeId, BridgeOf<T, I>)> {
LaneToBridge::<T, I>::get(lane_id)
.and_then(|bridge_id| Self::bridge(bridge_id).map(|bridge| (bridge_id, bridge)))
}
}
impl<T: Config<I>, I: 'static> Pallet<T, I> {
/// Returns some `NetworkId` if contains `GlobalConsensus` junction.
fn bridged_network_id() -> Result<NetworkId, sp_runtime::DispatchError> {
match T::BridgedNetwork::get().take_first_interior() {
Some(GlobalConsensus(network)) => Ok(network),
_ => Err(Error::<T, I>::BridgeLocations(
BridgeLocationsError::InvalidBridgeDestination,
)
.into()),
}
}
}
#[cfg(any(test, feature = "try-runtime", feature = "std"))]
impl<T: Config<I>, I: 'static> Pallet<T, I> {
/// Ensure the correctness of the state of this pallet.
pub fn do_try_state() -> Result<(), sp_runtime::TryRuntimeError> {
use sp_std::collections::btree_set::BTreeSet;
let mut lanes = BTreeSet::new();
// check all known bridge configurations
for (bridge_id, bridge) in Bridges::<T, I>::iter() {
log::info!(target: LOG_TARGET, "Checking `do_try_state` for bridge_id: {bridge_id:?} and bridge: {bridge:?}");
lanes.insert(Self::do_try_state_for_bridge(bridge_id, bridge)?);
}
ensure!(
lanes.len() == Bridges::<T, I>::iter().count(),
"Invalid `Bridges` configuration, probably two bridges handle the same laneId!"
);
ensure!(
lanes.len() == LaneToBridge::<T, I>::iter().count(),
"Invalid `LaneToBridge` configuration, probably missing or not removed laneId!"
);
Ok(())
}
/// Ensure the correctness of the state of the bridge.
pub fn do_try_state_for_bridge(
bridge_id: BridgeId,
bridge: BridgeOf<T, I>,
) -> Result<LaneId, sp_runtime::TryRuntimeError> {
// check `BridgeId` points to the same `LaneId` and vice versa.
ensure!(
Some(bridge_id) == Self::lane_to_bridge(bridge.lane_id),
"Found `LaneToBridge` inconsistency for bridge_id - missing mapping!"
);
// check that `locations` are convertible to the `latest` XCM.
let bridge_origin_relative_location_as_latest: &Location =
bridge.bridge_origin_relative_location.try_as().map_err(|_| {
"`bridge.bridge_origin_relative_location` cannot be converted to the `latest` XCM, needs migration!"
})?;
let bridge_origin_universal_location_as_latest: &InteriorLocation = bridge.bridge_origin_universal_location
.try_as()
.map_err(|_| "`bridge.bridge_origin_universal_location` cannot be converted to the `latest` XCM, needs migration!")?;
let bridge_destination_universal_location_as_latest: &InteriorLocation = bridge.bridge_destination_universal_location
.try_as()
.map_err(|_| "`bridge.bridge_destination_universal_location` cannot be converted to the `latest` XCM, needs migration!")?;
// check `BridgeId` does not change
ensure!(
bridge_id == BridgeId::new(bridge_origin_universal_location_as_latest, bridge_destination_universal_location_as_latest),
"`bridge_id` is different than calculated from `bridge_origin_universal_location_as_latest` and `bridge_destination_universal_location_as_latest`, needs migration!"
);
// check bridge account owner
ensure!(
T::BridgeOriginAccountIdConverter::convert_location(bridge_origin_relative_location_as_latest) == Some(bridge.bridge_owner_account),
"`bridge.bridge_owner_account` is different than calculated from `bridge.bridge_origin_relative_location`, needs migration!"
);
Ok(bridge.lane_id)
}
}
/// All registered bridges.
#[pallet::storage]
#[pallet::getter(fn bridge)]
pub type Bridges<T: Config<I>, I: 'static = ()> =
StorageMap<_, Identity, BridgeId, BridgeOf<T, I>>;
/// All registered `lane_id` and `bridge_id` mappings.
#[pallet::storage]
#[pallet::getter(fn lane_to_bridge)]
pub type LaneToBridge<T: Config<I>, I: 'static = ()> =
StorageMap<_, Identity, LaneId, BridgeId>;
#[pallet::genesis_config]
#[derive(DefaultNoBound)]
pub struct GenesisConfig<T: Config<I>, I: 'static = ()> {
/// Opened bridges.
///
/// Keep in mind that we are **NOT** reserving any amount for the bridges, opened at
/// genesis. We are **NOT** opening lanes, used by this bridge. It all must be done using
/// other pallets genesis configuration or some other means.
pub opened_bridges: Vec<(Location, InteriorLocation)>,
/// Dummy marker.
pub phantom: sp_std::marker::PhantomData<(T, I)>,
}
#[pallet::genesis_build]
impl<T: Config<I>, I: 'static> BuildGenesisConfig for GenesisConfig<T, I>
where
T: frame_system::Config<AccountId = AccountIdOf<ThisChainOf<T, I>>>,
{
fn build(&self) {
for (bridge_origin_relative_location, bridge_destination_universal_location) in
&self.opened_bridges
{
let locations = Pallet::<T, I>::bridge_locations(
bridge_origin_relative_location.clone(),
bridge_destination_universal_location.clone().into(),
)
.expect("Invalid genesis configuration");
let lane_id =
locations.calculate_lane_id(xcm::latest::VERSION).expect("Valid locations");
let bridge_owner_account = T::BridgeOriginAccountIdConverter::convert_location(
locations.bridge_origin_relative_location(),
)
.expect("Invalid genesis configuration");
Bridges::<T, I>::insert(
locations.bridge_id(),
Bridge {
bridge_origin_relative_location: Box::new(
locations.bridge_origin_relative_location().clone().into(),
),
bridge_origin_universal_location: Box::new(
locations.bridge_origin_universal_location().clone().into(),
),
bridge_destination_universal_location: Box::new(
locations.bridge_destination_universal_location().clone().into(),
),
state: BridgeState::Opened,
bridge_owner_account,
deposit: Zero::zero(),
lane_id,
},
);
LaneToBridge::<T, I>::insert(lane_id, locations.bridge_id());
let lanes_manager = LanesManagerOf::<T, I>::new();
lanes_manager
.create_inbound_lane(lane_id)
.expect("Invalid genesis configuration");
lanes_manager
.create_outbound_lane(lane_id)
.expect("Invalid genesis configuration");
}
}
}
#[pallet::event]
#[pallet::generate_deposit(pub(super) fn deposit_event)]
pub enum Event<T: Config<I>, I: 'static = ()> {
/// The bridge between two locations has been opened.
BridgeOpened {
/// Bridge identifier.
bridge_id: BridgeId,
/// Amount of deposit held.
bridge_deposit: BalanceOf<ThisChainOf<T, I>>,
/// Universal location of local bridge endpoint.
local_endpoint: Box<InteriorLocation>,
/// Universal location of remote bridge endpoint.
remote_endpoint: Box<InteriorLocation>,
/// Lane identifier.
lane_id: LaneId,
},
/// Bridge is going to be closed, but not yet fully pruned from the runtime storage.
ClosingBridge {
/// Bridge identifier.
bridge_id: BridgeId,
/// Lane identifier.
lane_id: LaneId,
/// Number of pruned messages during the close call.
pruned_messages: MessageNonce,
/// Number of enqueued messages that need to be pruned in follow up calls.
enqueued_messages: MessageNonce,
},
/// Bridge has been closed and pruned from the runtime storage. It now may be reopened
/// again by any participant.
BridgePruned {
/// Bridge identifier.
bridge_id: BridgeId,
/// Lane identifier.
lane_id: LaneId,
/// Amount of deposit released.
bridge_deposit: BalanceOf<ThisChainOf<T, I>>,
/// Number of pruned messages during the close call.
pruned_messages: MessageNonce,
},
}
#[pallet::error]
pub enum Error<T, I = ()> {
/// Bridge locations error.
BridgeLocations(BridgeLocationsError),
/// Invalid local bridge origin account.
InvalidBridgeOriginAccount,
/// The bridge is already registered in this pallet.
BridgeAlreadyExists,
/// The local origin already owns a maximal number of bridges.
TooManyBridgesForLocalOrigin,
/// Trying to close already closed bridge.
BridgeAlreadyClosed,
/// Lanes manager error.
LanesManager(LanesManagerError),
/// Trying to access unknown bridge.
UnknownBridge,
/// The bridge origin can't pay the required amount for opening the bridge.
FailedToReserveBridgeDeposit,
/// The version of XCM location argument is unsupported.
UnsupportedXcmVersion,
}
}
#[cfg(test)]
mod tests {
use super::*;
use mock::*;
use bp_messages::LaneId;
use frame_support::{assert_err, assert_noop, assert_ok, traits::fungible::Mutate, BoundedVec};
use frame_system::{EventRecord, Phase};
use sp_core::H256;
use sp_runtime::TryRuntimeError;
fn fund_origin_sovereign_account(locations: &BridgeLocations, balance: Balance) -> AccountId {
let bridge_owner_account =
LocationToAccountId::convert_location(locations.bridge_origin_relative_location())
.unwrap();
assert_ok!(Balances::mint_into(&bridge_owner_account, balance));
bridge_owner_account
}
fn mock_open_bridge_from_with(
origin: RuntimeOrigin,
deposit: Balance,
with: InteriorLocation,
) -> (BridgeOf<TestRuntime, ()>, BridgeLocations) {
let locations =
XcmOverBridge::bridge_locations_from_origin(origin, Box::new(with.into())).unwrap();
let lane_id = locations.calculate_lane_id(xcm::latest::VERSION).unwrap();
let bridge_owner_account =
fund_origin_sovereign_account(&locations, deposit + ExistentialDeposit::get());
Balances::hold(&HoldReason::BridgeDeposit.into(), &bridge_owner_account, deposit).unwrap();
let bridge = Bridge {
bridge_origin_relative_location: Box::new(
locations.bridge_origin_relative_location().clone().into(),
),
bridge_origin_universal_location: Box::new(
locations.bridge_origin_universal_location().clone().into(),
),
bridge_destination_universal_location: Box::new(
locations.bridge_destination_universal_location().clone().into(),
),
state: BridgeState::Opened,
bridge_owner_account,
deposit,
lane_id,
};
Bridges::<TestRuntime, ()>::insert(locations.bridge_id(), bridge.clone());
LaneToBridge::<TestRuntime, ()>::insert(bridge.lane_id, locations.bridge_id());
let lanes_manager = LanesManagerOf::<TestRuntime, ()>::new();
lanes_manager.create_inbound_lane(bridge.lane_id).unwrap();
lanes_manager.create_outbound_lane(bridge.lane_id).unwrap();
assert_ok!(XcmOverBridge::do_try_state());
(bridge, *locations)
}
fn mock_open_bridge_from(
origin: RuntimeOrigin,
deposit: Balance,
) -> (BridgeOf<TestRuntime, ()>, BridgeLocations) {
mock_open_bridge_from_with(origin, deposit, bridged_asset_hub_universal_location())
}
fn enqueue_message(lane: LaneId) {
let lanes_manager = LanesManagerOf::<TestRuntime, ()>::new();
lanes_manager
.active_outbound_lane(lane)
.unwrap()
.send_message(BoundedVec::try_from(vec![42]).expect("We craft valid messages"));
}
#[test]
fn open_bridge_fails_if_origin_is_not_allowed() {
run_test(|| {
assert_noop!(
XcmOverBridge::open_bridge(
OpenBridgeOrigin::disallowed_origin(),
Box::new(bridged_asset_hub_universal_location().into()),
),
sp_runtime::DispatchError::BadOrigin,
);
})
}
#[test]
fn open_bridge_fails_if_origin_is_not_relative() {
run_test(|| {
assert_noop!(
XcmOverBridge::open_bridge(
OpenBridgeOrigin::parent_relay_chain_universal_origin(),
Box::new(bridged_asset_hub_universal_location().into()),
),
Error::<TestRuntime, ()>::BridgeLocations(
BridgeLocationsError::InvalidBridgeOrigin
),
);
assert_noop!(
XcmOverBridge::open_bridge(
OpenBridgeOrigin::sibling_parachain_universal_origin(),
Box::new(bridged_asset_hub_universal_location().into()),
),
Error::<TestRuntime, ()>::BridgeLocations(
BridgeLocationsError::InvalidBridgeOrigin
),
);
})
}
#[test]
fn open_bridge_fails_if_destination_is_not_remote() {
run_test(|| {
assert_noop!(
XcmOverBridge::open_bridge(
OpenBridgeOrigin::parent_relay_chain_origin(),
Box::new(
[GlobalConsensus(RelayNetwork::get()), Parachain(BRIDGED_ASSET_HUB_ID)]
.into()
),
),
Error::<TestRuntime, ()>::BridgeLocations(BridgeLocationsError::DestinationIsLocal),
);
});
}
#[test]
fn open_bridge_fails_if_outside_of_bridged_consensus() {
run_test(|| {
assert_noop!(
XcmOverBridge::open_bridge(
OpenBridgeOrigin::parent_relay_chain_origin(),
Box::new(
[
GlobalConsensus(NonBridgedRelayNetwork::get()),
Parachain(BRIDGED_ASSET_HUB_ID)
]
.into()
),
),
Error::<TestRuntime, ()>::BridgeLocations(
BridgeLocationsError::UnreachableDestination
),
);
});
}
#[test]
fn open_bridge_fails_if_origin_has_no_sovereign_account() {
run_test(|| {
assert_noop!(
XcmOverBridge::open_bridge(
OpenBridgeOrigin::origin_without_sovereign_account(),
Box::new(bridged_asset_hub_universal_location().into()),
),
Error::<TestRuntime, ()>::InvalidBridgeOriginAccount,
);
});
}
#[test]
fn open_bridge_fails_if_origin_sovereign_account_has_no_enough_funds() {
run_test(|| {
assert_noop!(
XcmOverBridge::open_bridge(
OpenBridgeOrigin::parent_relay_chain_origin(),
Box::new(bridged_asset_hub_universal_location().into()),
),
Error::<TestRuntime, ()>::FailedToReserveBridgeDeposit,
);
});
}
#[test]
fn open_bridge_fails_if_it_already_exists() {
run_test(|| {
let origin = OpenBridgeOrigin::parent_relay_chain_origin();
let locations = XcmOverBridge::bridge_locations_from_origin(
origin.clone(),
Box::new(bridged_asset_hub_universal_location().into()),
)
.unwrap();
let lane_id = locations.calculate_lane_id(xcm::latest::VERSION).unwrap();
fund_origin_sovereign_account(
&locations,
BridgeDeposit::get() + ExistentialDeposit::get(),
);
Bridges::<TestRuntime, ()>::insert(
locations.bridge_id(),
Bridge {
bridge_origin_relative_location: Box::new(
locations.bridge_origin_relative_location().clone().into(),
),
bridge_origin_universal_location: Box::new(
locations.bridge_origin_universal_location().clone().into(),
),
bridge_destination_universal_location: Box::new(
locations.bridge_destination_universal_location().clone().into(),
),
state: BridgeState::Opened,
bridge_owner_account: [0u8; 32].into(),
deposit: 0,
lane_id,
},
);
assert_noop!(
XcmOverBridge::open_bridge(
origin,
Box::new(bridged_asset_hub_universal_location().into()),
),
Error::<TestRuntime, ()>::BridgeAlreadyExists,
);
})
}
#[test]
fn open_bridge_fails_if_its_lanes_already_exists() {