polkadot_runtime_parachains/hrmp/deposits.rs
1// Copyright (C) Parity Technologies (UK) Ltd.
2// This file is part of Polkadot.
3
4// Polkadot is free software: you can redistribute it and/or modify
5// it under the terms of the GNU General Public License as published by
6// the Free Software Foundation, either version 3 of the License, or
7// (at your option) any later version.
8
9// Polkadot is distributed in the hope that it will be useful,
10// but WITHOUT ANY WARRANTY; without even the implied warranty of
11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12// GNU General Public License for more details.
13
14// You should have received a copy of the GNU General Public License
15// along with Polkadot. If not, see <http://www.gnu.org/licenses/>.
16
17//! Channel deposits.
18//!
19//! The channel logic never touches the funds directly. Each call that takes or gives back a
20//! deposit sends a [`DepositChangeRequest`] to [`Config::DepositProvider`]. If the provider
21//! applies the request within the call, the call completes right away. If the provider holds the
22//! funds on another chain, it answers pending and the call completes in
23//! [`OnDepositSet::on_deposit_set`] once the provider reports back, or stops there if the
24//! provider refused the request.
25//!
26//! The pallet implements [`ChannelDepositProvider`] itself to hold the deposits in
27//! [`Config::Currency`], which keeps the behaviour from before the provider existed.
28
29use super::*;
30use frame_support::transactional;
31
32/// Holds HRMP channel deposits.
33///
34/// A provider either applies a request within the call or accepts it and reports the outcome
35/// later through [`Self::OnDepositSet`]. While a request for one side of a channel is pending, it
36/// refuses another request for that side.
37///
38/// A request whose action is [`DepositAction::Release`] must not fail: the provider always
39/// applies it. It gives back everything the provider holds for each side the request names,
40/// whatever the request says the side holds.
41///
42/// A provider that answers later keeps its own records of what each side holds, and applies the
43/// requests for a side in the order they were made, releases included.
44pub trait ChannelDepositProvider {
45 /// Receives the report of a pending request once it is done.
46 type OnDepositSet: OnDepositSet;
47
48 /// Applies `request`, or accepts it to apply it later. Refuses it with an error, e.g. when
49 /// the funds are short or a request for the same side is still pending. A refused request
50 /// changes nothing. A [`DepositAction::Release`] is always successfully applied, never pending.
51 fn try_set_deposit(
52 request: DepositChangeRequest,
53 ) -> Result<DepositChangeResponse, DispatchError>;
54
55 /// Upper bound of what [`Self::try_set_deposit`] spends on top of what the calls' benchmarks
56 /// measure with the in-pallet provider, e.g. sending a message.
57 fn weight_of_try_set_deposit() -> Weight;
58}
59
60/// Receives the outcome of a pending [`DepositChangeRequest`].
61pub trait OnDepositSet {
62 /// Called once `request` is applied, or refused with `Err`.
63 ///
64 /// The worst-case weight of this call is [`Self::weight_of_on_deposit_set`].
65 fn on_deposit_set(request: DepositChangeRequest, result: Result<(), DepositError>);
66
67 /// Worst-case weight of [`Self::on_deposit_set`] for an `action`.
68 fn weight_of_on_deposit_set(action: &DepositAction) -> Weight;
69}
70
71/// Why a provider refused a pending [`DepositChangeRequest`].
72#[derive(
73 Encode,
74 Decode,
75 DecodeWithMemTracking,
76 Clone,
77 Copy,
78 Eq,
79 PartialEq,
80 Debug,
81 TypeInfo,
82 MaxEncodedLen,
83)]
84pub enum DepositError {
85 /// A side cannot cover its deposit.
86 InsufficientFunds,
87 /// A reason of the provider's own.
88 Other,
89}
90
91/// A request to change the deposits of a channel, with the action to resume once they are
92/// changed.
93///
94/// It carries everything the action needs, so the requester keeps no pending state of its own:
95/// the request comes back unchanged in [`OnDepositSet::on_deposit_set`] and the action resumes
96/// from it.
97#[derive(Encode, Decode, Clone, Eq, PartialEq, Debug, TypeInfo, MaxEncodedLen)]
98pub struct DepositChangeRequest {
99 /// The channel whose deposits change.
100 pub channel_id: HrmpChannelId,
101 /// How the sender's deposit changes, or `None` to leave it as is.
102 pub sender: Option<DepositChange>,
103 /// How the recipient's deposit changes, or `None` to leave it as is.
104 pub recipient: Option<DepositChange>,
105 /// The action to resume once the deposits are changed.
106 pub action: DepositAction,
107}
108
109/// What one side of a channel holds before and after a [`DepositChangeRequest`].
110#[derive(Encode, Decode, Clone, Copy, Eq, PartialEq, Debug, TypeInfo, MaxEncodedLen)]
111pub struct DepositChange {
112 /// What the side holds now, by the requester's records. A provider with records of its own
113 /// goes by those and acts on `target` alone.
114 pub current: Balance,
115 /// What the side holds once the request is done.
116 pub target: Balance,
117}
118
119/// The provider's answer to a [`DepositChangeRequest`].
120#[derive(Clone, Copy, Eq, PartialEq, Debug)]
121pub enum DepositChangeResponse {
122 /// The request is applied. The action resumes right away.
123 Applied,
124 /// The request is accepted and its outcome is reported through [`OnDepositSet`].
125 Pending,
126}
127
128/// The action a [`DepositChangeRequest`] resumes once the deposits are changed.
129#[derive(Encode, Decode, Clone, Copy, Eq, PartialEq, Debug, TypeInfo, MaxEncodedLen)]
130pub enum DepositAction {
131 /// Record the open channel request of [`Pallet::init_open_channel`]. The request is only
132 /// recorded once the sender's deposit is taken, so the limits it was asked with travel here.
133 InitOpenChannel { max_capacity: u32, max_message_size: u32, max_total_size: u32 },
134 /// Record and accept the open channel request of [`Pallet::init_and_accept_open_channel`] once
135 /// both deposits are taken, so that it is opened whole or not at all.
136 InitAndAcceptOpenChannel { max_capacity: u32, max_message_size: u32, max_total_size: u32 },
137 /// Confirm the open channel request of [`Pallet::accept_open_channel`]. The request may be
138 /// canceled and made anew before the recipient's deposit is taken, so the limits it was
139 /// accepted with travel here: only a request with the same ones is confirmed.
140 AcceptOpenChannel { max_capacity: u32, max_message_size: u32 },
141 /// Record the deposits of [`Pallet::poke_channel_deposits`].
142 PokeChannelDeposits,
143 /// Deposits given back after their request or channel is already removed. Nothing to resume.
144 Release,
145}
146
147/// The in-pallet provider: holds the deposits in [`Config::Currency`] and applies every request
148/// within the call.
149impl<T: Config> ChannelDepositProvider for Pallet<T> {
150 type OnDepositSet = Self;
151
152 // The recipient's side may fail after the sender's is changed.
153 #[transactional]
154 fn try_set_deposit(
155 request: DepositChangeRequest,
156 ) -> Result<DepositChangeResponse, DispatchError> {
157 let DepositChangeRequest { channel_id, sender, recipient, .. } = request;
158 for (para, change) in [(channel_id.sender, sender), (channel_id.recipient, recipient)] {
159 let Some(DepositChange { current, target }) = change else { continue };
160 let account: T::AccountId = para.into_account_truncating();
161 if target > current {
162 T::Currency::reserve(&account, (target - current).unique_saturated_into())?;
163 } else {
164 T::Currency::unreserve(&account, (current - target).unique_saturated_into());
165 }
166 }
167 Ok(DepositChangeResponse::Applied)
168 }
169
170 fn weight_of_try_set_deposit() -> Weight {
171 // Measured by the calls' benchmarks.
172 Weight::zero()
173 }
174}
175
176impl<T: Config> OnDepositSet for Pallet<T> {
177 fn on_deposit_set(request: DepositChangeRequest, result: Result<(), DepositError>) {
178 let channel_id = request.channel_id.clone();
179 if let Err(error) = result {
180 Self::deposit_event(Event::DepositRefused { channel_id, error });
181 return;
182 }
183
184 // The state may have changed since the request was made. A failed check leaves nothing
185 // behind, so only what was just taken needs giving back.
186 if let Err(error) = Self::resume(&request) {
187 let (sender, recipient) = Self::recorded_deposits(&channel_id);
188 // Defensively check that the recorded deposits are 0, before giving back.
189 let give_back = |change: Option<DepositChange>, recorded: Balance, side: &str| {
190 let change = change?;
191 if recorded != 0 {
192 frame_support::defensive!("a failed resume left a deposit recorded", side);
193 return None;
194 }
195 Some(change.target)
196 };
197 Self::release_deposits(
198 &channel_id,
199 give_back(request.sender, sender, "sender"),
200 give_back(request.recipient, recipient, "recipient"),
201 );
202 Self::deposit_event(Event::DepositReturned { channel_id, error });
203 }
204 }
205
206 /// The action's call, then giving back what was taken if its checks no longer pass.
207 fn weight_of_on_deposit_set(action: &DepositAction) -> Weight {
208 let resume = match action {
209 DepositAction::InitOpenChannel { .. } => {
210 <T as Config>::WeightInfo::hrmp_init_open_channel()
211 },
212 DepositAction::InitAndAcceptOpenChannel { .. } => {
213 <T as Config>::WeightInfo::force_open_hrmp_channel(0)
214 },
215 DepositAction::AcceptOpenChannel { .. } => {
216 <T as Config>::WeightInfo::hrmp_accept_open_channel()
217 },
218 DepositAction::PokeChannelDeposits => {
219 <T as Config>::WeightInfo::poke_channel_deposits()
220 },
221 DepositAction::Release => Weight::zero(),
222 };
223 resume.saturating_add(T::DepositProvider::weight_of_try_set_deposit())
224 }
225}
226
227impl<T: Config> Pallet<T> {
228 /// What the sender and the recipient must each hold for `channel_id` at the prices in
229 /// `config`. Channels with or amongst the system are free.
230 pub(super) fn required_deposits(
231 channel_id: &HrmpChannelId,
232 config: &HostConfiguration<BlockNumberFor<T>>,
233 ) -> (Balance, Balance) {
234 if channel_id.sender.is_system() || channel_id.recipient.is_system() {
235 return (0, 0);
236 }
237 (config.hrmp_sender_deposit, config.hrmp_recipient_deposit)
238 }
239
240 /// What this pallet records as deposited by the sender and the recipient of `channel_id`: the
241 /// deposits of its channel or of its open request, or none. A confirmed request's recipient
242 /// deposit is the price of the current session, the one it was confirmed in.
243 fn recorded_deposits(channel_id: &HrmpChannelId) -> (Balance, Balance) {
244 if let Some(channel) = HrmpChannels::<T>::get(channel_id) {
245 return (channel.sender_deposit, channel.recipient_deposit);
246 }
247 match HrmpOpenChannelRequests::<T>::get(channel_id) {
248 Some(req) if req.confirmed => {
249 let config = configuration::ActiveConfig::<T>::get();
250 (req.sender_deposit, Self::required_deposits(channel_id, &config).1)
251 },
252 Some(req) => (req.sender_deposit, 0),
253 None => (0, 0),
254 }
255 }
256
257 /// Sends `request` to [`Config::DepositProvider`] and resumes its action if the provider
258 /// applied it right away. A pending request resumes in [`OnDepositSet::on_deposit_set`]
259 /// instead.
260 ///
261 /// Fails if the provider refuses the request right away, or if the action fails when it
262 /// resumes right away.
263 ///
264 /// A release request is always successful.
265 #[transactional]
266 pub(super) fn set_deposit(request: DepositChangeRequest) -> DispatchResult {
267 // Nothing to change, e.g. on a channel with the system, needs no provider.
268 let unchanged =
269 |change: Option<DepositChange>| change.is_none_or(|c| c.current == c.target);
270 if unchanged(request.sender) && unchanged(request.recipient) {
271 return Self::resume(&request);
272 }
273 match T::DepositProvider::try_set_deposit(request.clone())? {
274 DepositChangeResponse::Applied => Self::resume(&request),
275 DepositChangeResponse::Pending => Ok(()),
276 }
277 }
278
279 /// Gives back the deposits of `channel_id`: `sender` and `recipient` are what each side holds
280 /// by this pallet's records, or `None` to leave that side alone. A refused release is logged.
281 pub(super) fn release_deposits(
282 channel_id: &HrmpChannelId,
283 sender: Option<Balance>,
284 recipient: Option<Balance>,
285 ) {
286 let release = |current| DepositChange { current, target: 0 };
287 let request = DepositChangeRequest {
288 channel_id: channel_id.clone(),
289 sender: sender.map(release),
290 recipient: recipient.map(release),
291 action: DepositAction::Release,
292 };
293 if let Err(e) = Self::set_deposit(request.clone()) {
294 // A release request is always successful, per `set_deposit` doc.
295 frame_support::defensive!("giving back deposits failed", (e, &request));
296 }
297 }
298
299 /// Resumes the action of `request` now that its deposits are updated. Its checks run again,
300 /// since a pending request may come back after the state has changed.
301 ///
302 /// Writes nothing if it fails: every check runs before the first write.
303 ///
304 /// A release request always succeeds.
305 #[transactional] // checks are run first but kept as a safeguard.
306 fn resume(request: &DepositChangeRequest) -> DispatchResult {
307 let channel_id = &request.channel_id;
308 match request.action {
309 // Meanwhile a request may have been made, and a channel opened, with a 0 deposit, e.g.
310 // if the price dropped to 0. (With a non-zero deposit, the deposit provider blocks it:
311 // only one request per side can be pending at a time.) The paras may also have been
312 // offboarded, and the conditions to open a channel may have changed.
313 // So we check the conditions to open a channel again.
314 //
315 // On failure, this pallet storage has no or 0-deposit for the sender so caller gives
316 // back the taken deposit.
317 DepositAction::InitOpenChannel { max_capacity, max_message_size, max_total_size } => {
318 let config = configuration::ActiveConfig::<T>::get();
319 Self::check_init_open_channel(channel_id, max_capacity, max_message_size, &config)?;
320 // Always set by `init_open_channel`.
321 let sender_deposit = request.sender.map(|c| c.target).unwrap_or_default();
322 Self::finish_init_open_channel(
323 channel_id,
324 sender_deposit,
325 max_capacity,
326 max_message_size,
327 max_total_size,
328 );
329 Ok(())
330 },
331 // Same as `InitOpenChannel`, for both sides. But we also check the recipient's deposit
332 // has not changed, as the request does not record it and the channel is opened at the
333 // current price.
334 DepositAction::InitAndAcceptOpenChannel {
335 max_capacity,
336 max_message_size,
337 max_total_size,
338 } => {
339 let config = configuration::ActiveConfig::<T>::get();
340 Self::check_init_open_channel(channel_id, max_capacity, max_message_size, &config)?;
341 Self::check_accept_limit(channel_id.recipient, &config)?;
342 Self::check_recipient_deposit(request, &config)?;
343 // Always set by `init_and_accept_open_channel`.
344 let sender_deposit = request.sender.map(|c| c.target).unwrap_or_default();
345 Self::finish_init_open_channel(
346 channel_id,
347 sender_deposit,
348 max_capacity,
349 max_message_size,
350 max_total_size,
351 );
352 Self::finish_accept_open_channel(channel_id);
353 let HrmpChannelId { sender, recipient } = *channel_id;
354 Self::deposit_event(Event::HrmpChannelForceOpened {
355 sender,
356 recipient,
357 proposed_max_capacity: max_capacity,
358 proposed_max_message_size: max_message_size,
359 });
360 Ok(())
361 },
362 // Meanwhile the request may have been canceled, removed with an offboarded para, or
363 // made anew with other limits: these only touch the sender's side. It may also have
364 // been confirmed with a 0 deposit, e.g. if the price dropped to 0, and opened. (With a
365 // non-zero deposit, the deposit provider blocks it.) And the price may have changed.
366 // So we check the conditions to accept the request again, that it is the same request,
367 // and that the deposit taken is still the price.
368 //
369 // On failure, this pallet storage has no or 0-deposit for the recipient so caller gives
370 // back the taken deposit.
371 DepositAction::AcceptOpenChannel { max_capacity, max_message_size } => {
372 let config = configuration::ActiveConfig::<T>::get();
373 let channel_req = Self::check_accept_open_channel(channel_id, &config)?;
374 // The request may have been canceled and made anew with other limits meanwhile.
375 ensure!(
376 (channel_req.max_capacity, channel_req.max_message_size) ==
377 (max_capacity, max_message_size),
378 Error::<T>::AcceptHrmpChannelRequestChanged
379 );
380 Self::check_recipient_deposit(request, &config)?;
381 Self::finish_accept_open_channel(channel_id);
382 Ok(())
383 },
384 // Meanwhile the channel may have been closed, which gave back what it recorded (applied
385 // by the deposit provider after this poke), and re-opened with 0 deposits. (With
386 // non-zero deposits, the deposit provider blocks it.)
387 // So we check that the channel still records the deposits the poke set out from.
388 //
389 // On failure, this pallet storage has no or 0-deposits, given it can only happen after
390 // deposit price changed. The caller gives back the taken deposits.
391 DepositAction::PokeChannelDeposits => {
392 Self::finish_poke_channel_deposits(channel_id, request.sender, request.recipient)
393 },
394 // Never pending, nothing to resume.
395 DepositAction::Release => Ok(()),
396 }
397 }
398
399 /// Whether the recipient's deposit taken by `request` is still the price in `config`.
400 ///
401 /// The channel does not record the deposit its recipient paid: it is opened at the session
402 /// change with the price of `config`, which cannot change before then. But a pending request
403 /// may come back after a session change, with a deposit taken at an older price. This is not
404 /// expected often, as the price rarely changes.
405 fn check_recipient_deposit(
406 request: &DepositChangeRequest,
407 config: &HostConfiguration<BlockNumberFor<T>>,
408 ) -> DispatchResult {
409 let taken = request.recipient.map(|c| c.target).unwrap_or_default();
410 let (_, price) = Self::required_deposits(&request.channel_id, config);
411 ensure!(taken == price, Error::<T>::AcceptHrmpChannelDepositChanged);
412 Ok(())
413 }
414}