smoldot-light 0.1.0

Browser bindings to a light client for Substrate-based blockchains
Documentation
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
// Smoldot
// Copyright (C) 2019-2022  Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0

// This program 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.

// This program 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 this program.  If not, see <http://www.gnu.org/licenses/>.

//! All JSON-RPC method handlers that relate to transactions.

use super::{Background, Platform, SubscriptionTy};

use crate::transactions_service;

use alloc::{borrow::ToOwned as _, boxed::Box, str, string::ToString as _, sync::Arc, vec::Vec};
use core::sync::atomic;
use futures::prelude::*;
use smoldot::json_rpc::{self, methods, requests_subscriptions};

impl<TPlat: Platform> Background<TPlat> {
    /// Handles a call to [`methods::MethodCall::author_pendingExtrinsics`].
    pub(super) async fn author_pending_extrinsics(
        self: &Arc<Self>,
        request_id: &str,
        state_machine_request_id: &requests_subscriptions::RequestId,
    ) {
        // Because multiple different chains ("chain" in the context of the public API of smoldot)
        // might share the same transactions service, it could be possible for chain A to submit
        // a transaction and then for chain B to read it by calling `author_pendingExtrinsics`.
        // This would make it possible for the API user of chain A to be able to communicate with
        // the API user of chain B. While the implications of permitting this are unclear, it is
        // not a bad idea to prevent this communication from happening. Consequently, we always
        // return an empty list of pending extrinsics.
        self.requests_subscriptions
            .respond(
                state_machine_request_id,
                methods::Response::author_pendingExtrinsics(Vec::new())
                    .to_json_response(request_id),
            )
            .await;
    }

    /// Handles a call to [`methods::MethodCall::author_submitExtrinsic`].
    pub(super) async fn author_submit_extrinsic(
        self: &Arc<Self>,
        request_id: &str,
        state_machine_request_id: &requests_subscriptions::RequestId,
        transaction: methods::HexString,
    ) {
        // Note that this function is misnamed. It should really be called
        // "author_submitTransaction".

        // In Substrate, `author_submitExtrinsic` returns the hash of the transaction. It
        // is unclear whether it has to actually be the hash of the transaction or if it
        // could be any opaque value. Additionally, there isn't any other JSON-RPC method
        // that accepts as parameter the value returned here. When in doubt, we return
        // the hash as well.

        let mut hash_context = blake2_rfc::blake2b::Blake2b::new(32);
        hash_context.update(&transaction.0);
        let mut transaction_hash: [u8; 32] = Default::default();
        transaction_hash.copy_from_slice(hash_context.finalize().as_bytes());
        self.transactions_service
            .submit_transaction(transaction.0)
            .await;
        self.requests_subscriptions
            .respond(
                state_machine_request_id,
                methods::Response::author_submitExtrinsic(methods::HashHexString(transaction_hash))
                    .to_json_response(request_id),
            )
            .await;
    }

    /// Handles a call to [`methods::MethodCall::author_unwatchExtrinsic`].
    pub(super) async fn author_unwatch_extrinsic(
        self: &Arc<Self>,
        request_id: &str,
        state_machine_request_id: &requests_subscriptions::RequestId,
        subscription: &str,
    ) {
        let state_machine_subscription = if let Some((abort_handle, state_machine_subscription)) =
            self.subscriptions
                .lock()
                .await
                .misc
                .remove(&(subscription.to_owned(), SubscriptionTy::TransactionLegacy))
        {
            abort_handle.abort();
            Some(state_machine_subscription)
        } else {
            None
        };
        if let Some(state_machine_subscription) = &state_machine_subscription {
            self.requests_subscriptions
                .stop_subscription(state_machine_subscription)
                .await;
        }
        self.requests_subscriptions
            .respond(
                state_machine_request_id,
                methods::Response::author_unwatchExtrinsic(state_machine_subscription.is_some())
                    .to_json_response(request_id),
            )
            .await;
    }

    /// Handles a call to [`methods::MethodCall::author_submitAndWatchExtrinsic`] (if `is_legacy`
    /// is `true`) or to [`methods::MethodCall::transaction_unstable_submitAndWatch`] (if
    /// `is_legacy` is `false`).
    pub(super) async fn submit_and_watch_transaction(
        self: &Arc<Self>,
        request_id: &str,
        state_machine_request_id: &requests_subscriptions::RequestId,
        transaction: methods::HexString,
        is_legacy: bool,
    ) {
        let state_machine_subscription = match self
            .requests_subscriptions
            .start_subscription(state_machine_request_id, 16)
            .await
        {
            Ok(v) => v,
            Err(requests_subscriptions::StartSubscriptionError::LimitReached) => {
                self.requests_subscriptions
                    .respond(
                        state_machine_request_id,
                        json_rpc::parse::build_error_response(
                            request_id,
                            json_rpc::parse::ErrorResponse::ServerError(
                                -32000,
                                "Too many active subscriptions",
                            ),
                            None,
                        ),
                    )
                    .await;
                return;
            }
        };

        let subscription_id = self
            .next_subscription_id
            .fetch_add(1, atomic::Ordering::Relaxed)
            .to_string();

        let abort_registration = {
            let (abort_handle, abort_registration) = future::AbortHandle::new_pair();
            let mut subscriptions_list = self.subscriptions.lock().await;
            let ty = if is_legacy {
                SubscriptionTy::TransactionLegacy
            } else {
                SubscriptionTy::Transaction
            };
            subscriptions_list.misc.insert(
                (subscription_id.clone(), ty),
                (abort_handle, state_machine_subscription.clone()),
            );
            abort_registration
        };

        self.requests_subscriptions
            .respond(
                &state_machine_request_id,
                if is_legacy {
                    methods::Response::author_submitAndWatchExtrinsic((&subscription_id).into())
                        .to_json_response(request_id)
                } else {
                    methods::Response::transaction_unstable_submitAndWatch(
                        (&subscription_id).into(),
                    )
                    .to_json_response(request_id)
                },
            )
            .await;

        // Spawn a separate task for the transaction updates.
        let task = {
            let mut transaction_updates = self
                .transactions_service
                .submit_and_watch_transaction(transaction.0, 16)
                .await;
            let me = self.clone();
            async move {
                let mut included_block = None;
                let mut num_broadcasted_peers = 0;

                // TODO: doesn't reported `validated` events

                loop {
                    match transaction_updates.next().await {
                        Some(update) => {
                            let update = match (update, is_legacy) {
                                (transactions_service::TransactionStatus::Broadcast(peers), false) => {
                                    methods::ServerToClient::author_extrinsicUpdate {
                                        subscription: (&subscription_id).into(),
                                        result: methods::TransactionStatus::Broadcast(
                                            peers.into_iter().map(|peer| peer.to_base58()).collect(),
                                        )
                                    }
                                    .to_json_call_object_parameters(None)
                                }
                                (transactions_service::TransactionStatus::Broadcast(peers), true) => {
                                    num_broadcasted_peers += peers.len();
                                    methods::ServerToClient::transaction_unstable_watchEvent {
                                        subscription: (&subscription_id).into(),
                                        result: methods::TransactionWatchEvent::Broadcasted {
                                            num_peers: u32::try_from(num_broadcasted_peers).unwrap_or(u32::max_value()),
                                        }
                                    }
                                    .to_json_call_object_parameters(None)
                                }

                                (transactions_service::TransactionStatus::IncludedBlockUpdate {
                                    block_hash: Some((block_hash, _)),
                                }, true) => {
                                    included_block = Some(block_hash);
                                    methods::ServerToClient::author_extrinsicUpdate {
                                        subscription: (&subscription_id).into(),
                                        result: methods::TransactionStatus::InBlock(methods::HashHexString(
                                            block_hash,
                                        ))
                                    }
                                    .to_json_call_object_parameters(None)
                                }
                                (transactions_service::TransactionStatus::IncludedBlockUpdate {
                                    block_hash: None,
                                }, true) => {
                                    if let Some(block_hash) = included_block.take() {
                                        methods::ServerToClient::author_extrinsicUpdate {
                                            subscription: (&subscription_id).into(),
                                            result: methods::TransactionStatus::Retracted(
                                                methods::HashHexString(block_hash),
                                            )
                                        }
                                        .to_json_call_object_parameters(None)

                                    } else {
                                        continue;
                                    }
                                }
                                (transactions_service::TransactionStatus::IncludedBlockUpdate {
                                    block_hash: Some((block_hash, index)),
                                }, false) => {
                                    included_block = Some(block_hash);
                                    methods::ServerToClient::transaction_unstable_watchEvent {
                                        subscription: (&subscription_id).into(),
                                        result: methods::TransactionWatchEvent::BestChainBlockIncluded {
                                            block: Some(methods::TransactionWatchEventBlock {
                                                hash: methods::HashHexString(block_hash),
                                                index: methods::NumberAsString(index),
                                            })
                                        }
                                    }
                                    .to_json_call_object_parameters(None)
                                }
                                (transactions_service::TransactionStatus::IncludedBlockUpdate {
                                    block_hash: None,
                                }, false) => {
                                    methods::ServerToClient::transaction_unstable_watchEvent {
                                        subscription: (&subscription_id).into(),
                                        result: methods::TransactionWatchEvent::BestChainBlockIncluded {
                                            block: None,
                                        }
                                    }
                                    .to_json_call_object_parameters(None)
                                }

                                (transactions_service::TransactionStatus::Dropped(
                                    transactions_service::DropReason::GapInChain,
                                ), true)
                                | (transactions_service::TransactionStatus::Dropped(
                                    transactions_service::DropReason::MaxPendingTransactionsReached,
                                ), true)
                                | (transactions_service::TransactionStatus::Dropped(
                                    transactions_service::DropReason::Invalid(_),
                                ), true)
                                | (transactions_service::TransactionStatus::Dropped(
                                    transactions_service::DropReason::ValidateError(_),
                                ), true) => {
                                    methods::ServerToClient::author_extrinsicUpdate {
                                        subscription: (&subscription_id).into(),
                                        result: methods::TransactionStatus::Dropped,
                                    }
                                    .to_json_call_object_parameters(None)
                                },
                                (transactions_service::TransactionStatus::Dropped(
                                    transactions_service::DropReason::GapInChain,
                                ), false) => {
                                    methods::ServerToClient::transaction_unstable_watchEvent {
                                        subscription: (&subscription_id).into(),
                                        result: methods::TransactionWatchEvent::Dropped {
                                            error: "gap in chain of blocks".into(),
                                            broadcasted: num_broadcasted_peers != 0,
                                        }
                                    }
                                    .to_json_call_object_parameters(None)
                                },
                                (transactions_service::TransactionStatus::Dropped(
                                    transactions_service::DropReason::MaxPendingTransactionsReached,
                                ), false) => {
                                    methods::ServerToClient::transaction_unstable_watchEvent {
                                        subscription: (&subscription_id).into(),
                                        result: methods::TransactionWatchEvent::Dropped {
                                            error: "transactions pool full".into(),
                                            broadcasted: num_broadcasted_peers != 0,
                                        }
                                    }
                                    .to_json_call_object_parameters(None)
                                },
                                (transactions_service::TransactionStatus::Dropped(
                                    transactions_service::DropReason::Invalid(error),
                                ), false) => {
                                    methods::ServerToClient::transaction_unstable_watchEvent {
                                        subscription: (&subscription_id).into(),
                                        result: methods::TransactionWatchEvent::Invalid {
                                            error: error.to_string().into(),
                                        }
                                    }
                                    .to_json_call_object_parameters(None)
                                },
                                (transactions_service::TransactionStatus::Dropped(
                                    transactions_service::DropReason::ValidateError(error),
                                ), false) => {
                                    methods::ServerToClient::transaction_unstable_watchEvent {
                                        subscription: (&subscription_id).into(),
                                        result: methods::TransactionWatchEvent::Error {
                                            error: error.to_string().into(),
                                        }
                                    }
                                    .to_json_call_object_parameters(None)
                                },

                                (transactions_service::TransactionStatus::Dropped(
                                    transactions_service::DropReason::Finalized { block_hash, .. },
                                ), true) => {
                                    methods::ServerToClient::author_extrinsicUpdate {
                                        subscription: (&subscription_id).into(),
                                        result: methods::TransactionStatus::Finalized(methods::HashHexString(
                                            block_hash,
                                        ))
                                    }
                                    .to_json_call_object_parameters(None)
                                }
                                (transactions_service::TransactionStatus::Dropped(
                                    transactions_service::DropReason::Finalized { block_hash, index },
                                ), false) => {
                                    methods::ServerToClient::transaction_unstable_watchEvent {
                                        subscription: (&subscription_id).into(),
                                        result: methods::TransactionWatchEvent::Finalized {
                                            block: methods::TransactionWatchEventBlock {
                                                hash: methods::HashHexString(block_hash),
                                                index: methods::NumberAsString(index),
                                            },
                                        }
                                    }
                                    .to_json_call_object_parameters(None)
                                }
                            };

                            // TODO: handle situation where buffer is full
                            let _ = me
                                .requests_subscriptions
                                .try_push_notification(&state_machine_subscription, update)
                                .await;
                        }
                        None => {
                            // Channel from the transactions service has been closed.
                            // Stop the task.
                            // There is nothing more that can be done except hope that the
                            // client understands that no new notification is expected and
                            // unsubscribes.
                            break;
                        }
                    }
                }
            }
        };

        self.new_child_tasks_tx
            .lock()
            .await
            .unbounded_send(Box::pin(
                future::Abortable::new(task, abort_registration).map(|_| ()),
            ))
            .unwrap();
    }

    /// Handles a call to [`methods::MethodCall::transaction_unstable_unwatch`].
    pub(super) async fn transaction_unstable_unwatch(
        self: &Arc<Self>,
        request_id: &str,
        state_machine_request_id: &requests_subscriptions::RequestId,
        subscription: &str,
    ) {
        let state_machine_subscription = if let Some((abort_handle, state_machine_subscription)) =
            self.subscriptions
                .lock()
                .await
                .misc
                .remove(&(subscription.to_owned(), SubscriptionTy::Transaction))
        {
            abort_handle.abort();
            Some(state_machine_subscription)
        } else {
            None
        };

        if let Some(state_machine_subscription) = &state_machine_subscription {
            self.requests_subscriptions
                .stop_subscription(state_machine_subscription)
                .await;
        }

        self.requests_subscriptions
            .respond(
                state_machine_request_id,
                methods::Response::transaction_unstable_unwatch(()).to_json_response(request_id),
            )
            .await;
    }
}