referrerpolicy=no-referrer-when-downgrade

sc_statement_store/
subxt_client.rs

1// This file is part of Substrate.
2
3// Copyright (C) Parity Technologies (UK) Ltd.
4// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0
5
6// This program is free software: you can redistribute it and/or modify
7// it under the terms of the GNU General Public License as published by
8// the Free Software Foundation, either version 3 of the License, or
9// (at your option) any later version.
10
11// This program is distributed in the hope that it will be useful,
12// but WITHOUT ANY WARRANTY; without even the implied warranty of
13// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14// GNU General Public License for more details.
15
16// You should have received a copy of the GNU General Public License
17// along with this program. If not, see <https://www.gnu.org/licenses/>.
18
19//! Custom subxt configuration for runtimes interacting with statement-store, used only for tests
20//!
21//! The runtime uses `VerifyMultiSignature` instead of the standard
22//! `VerifySignature` transaction extension, and includes a `RestrictOrigins`
23//! extension that encodes as a bool (`false` = 0x00 to disable origin
24//! restrictions). These non-standard extensions cannot be auto-defaulted by
25//! frame-decode, so this module provides a `CustomConfig` that handles them
26//! explicitly.
27
28use scale_info::PortableRegistry;
29use sp_core::{sr25519, Pair};
30use subxt::{
31	config::{
32		substrate::SubstrateConfig,
33		transaction_extensions::{
34			ChargeAssetTxPayment, ChargeAssetTxPaymentParams, ChargeTransactionPayment,
35			ChargeTransactionPaymentParams, CheckGenesis, CheckMetadataHash, CheckMortality,
36			CheckMortalityParams, CheckNonce, CheckNonceParams, CheckSpecVersion, CheckTxVersion,
37			VerifySignature,
38		},
39		ClientState, Config, TransactionExtension, TransactionExtensions,
40	},
41	dynamic::Value,
42	ext::{frame_decode, scale_value::value},
43	transactions::Signer,
44	utils::H256,
45	OnlineClient,
46};
47
48/// Wrapper around `VerifySignature` that matches the runtime's `VerifyMultiSignature` name
49pub struct VerifyMultiSignature<T: Config>(VerifySignature<T>);
50
51impl<T: Config> frame_decode::extrinsics::TransactionExtension<PortableRegistry>
52	for VerifyMultiSignature<T>
53{
54	const NAME: &str = "VerifyMultiSignature";
55
56	fn encode_value_to(
57		&self,
58		type_id: u32,
59		type_resolver: &PortableRegistry,
60		v: &mut Vec<u8>,
61	) -> Result<(), frame_decode::extrinsics::TransactionExtensionError> {
62		self.0.encode_value_to(type_id, type_resolver, v)
63	}
64
65	fn is_authorization_extension(&self) -> bool {
66		self.0.is_authorization_extension()
67	}
68
69	fn encode_implicit_to(
70		&self,
71		type_id: u32,
72		type_resolver: &PortableRegistry,
73		v: &mut Vec<u8>,
74	) -> Result<(), frame_decode::extrinsics::TransactionExtensionError> {
75		self.0.encode_implicit_to(type_id, type_resolver, v)
76	}
77}
78
79impl<T: Config> TransactionExtension<T> for VerifyMultiSignature<T> {
80	type Decoded = <VerifySignature<T> as TransactionExtension<T>>::Decoded;
81	type Params = ();
82
83	fn new(
84		client: &ClientState<T>,
85		params: Self::Params,
86	) -> Result<Self, subxt::error::TransactionExtensionError> {
87		Ok(VerifyMultiSignature(VerifySignature::new(client, params)?))
88	}
89
90	fn inject_signature(&mut self, account_id: &T::AccountId, signature: &T::Signature) {
91		self.0.inject_signature(account_id, signature);
92	}
93}
94
95/// Custom transaction extension for `RestrictOrigins`
96///
97/// This extension encodes as `false` (0x00) to disable origin restrictions
98/// It is a `bool` in the runtime (not `Option<T>`), so frame-decode cannot
99/// auto-default it and it must be handled explicitly
100pub struct RestrictOrigins;
101
102impl frame_decode::extrinsics::TransactionExtension<PortableRegistry> for RestrictOrigins {
103	const NAME: &str = "RestrictOrigins";
104
105	fn encode_value_to(
106		&self,
107		_type_id: u32,
108		_type_resolver: &PortableRegistry,
109		v: &mut Vec<u8>,
110	) -> Result<(), frame_decode::extrinsics::TransactionExtensionError> {
111		// Encode `false` disables origin restriction
112		v.push(0x00);
113		Ok(())
114	}
115
116	fn encode_implicit_to(
117		&self,
118		_type_id: u32,
119		_type_resolver: &PortableRegistry,
120		_v: &mut Vec<u8>,
121	) -> Result<(), frame_decode::extrinsics::TransactionExtensionError> {
122		Ok(())
123	}
124}
125
126impl<T: Config> TransactionExtension<T> for RestrictOrigins {
127	type Decoded = u8;
128	type Params = ();
129
130	fn new(
131		_client: &ClientState<T>,
132		_params: Self::Params,
133	) -> Result<Self, subxt::error::TransactionExtensionError> {
134		Ok(RestrictOrigins)
135	}
136}
137
138/// Custom subxt `Config`
139///
140/// Registers the non-standard `VerifyMultiSignature` and `RestrictOrigins`
141/// transaction extensions so that subxt can correctly encode extrinsics
142#[derive(Debug, Clone)]
143pub struct CustomConfig(SubstrateConfig);
144
145impl Default for CustomConfig {
146	fn default() -> Self {
147		CustomConfig(SubstrateConfig::new())
148	}
149}
150
151impl Config for CustomConfig {
152	type AccountId = <SubstrateConfig as Config>::AccountId;
153	type Address = subxt::utils::MultiAddress<Self::AccountId, ()>;
154	type Signature = <SubstrateConfig as Config>::Signature;
155	type Hasher = <SubstrateConfig as Config>::Hasher;
156	type Header = <SubstrateConfig as Config>::Header;
157	type AssetId = <SubstrateConfig as Config>::AssetId;
158	type TransactionExtensions = (
159		VerifyMultiSignature<Self>,
160		CheckSpecVersion,
161		CheckTxVersion,
162		CheckNonce,
163		CheckGenesis<Self>,
164		CheckMortality<Self>,
165		ChargeAssetTxPayment<Self>,
166		ChargeTransactionPayment,
167		CheckMetadataHash,
168		RestrictOrigins,
169	);
170
171	fn genesis_hash(&self) -> Option<subxt::config::HashFor<Self>> {
172		self.0.genesis_hash()
173	}
174
175	fn spec_and_transaction_version_for_block_number(
176		&self,
177		block_number: u64,
178	) -> Option<(u32, u32)> {
179		self.0.spec_and_transaction_version_for_block_number(block_number)
180	}
181
182	fn metadata_for_spec_version(&self, spec_version: u32) -> Option<subxt::metadata::ArcMetadata> {
183		self.0.metadata_for_spec_version(spec_version)
184	}
185
186	fn set_metadata_for_spec_version(
187		&self,
188		spec_version: u32,
189		metadata: subxt::metadata::ArcMetadata,
190	) {
191		self.0.set_metadata_for_spec_version(spec_version, metadata)
192	}
193}
194
195/// Builds params for CustomConfig's transaction extensions (9 defaults + RestrictOrigins)
196fn build_params(
197	nonce: u64,
198) -> <<CustomConfig as Config>::TransactionExtensions as TransactionExtensions<CustomConfig>>::Params
199{
200	(
201		(),
202		(),
203		(),
204		CheckNonceParams::with_nonce(nonce),
205		(),
206		CheckMortalityParams::immortal(),
207		ChargeAssetTxPaymentParams::no_tip(),
208		ChargeTransactionPaymentParams::no_tip(),
209		(),
210		(),
211	)
212}
213
214/// Submits an extrinsic with an explicit nonce and waits for it to be finalized
215pub async fn submit_extrinsic<S: Signer<CustomConfig>>(
216	client: &OnlineClient<CustomConfig>,
217	call: &subxt::transactions::DynamicPayload<Vec<Value>>,
218	signer: &S,
219	nonce: u64,
220) -> Result<H256, anyhow::Error> {
221	let tx_in_block = client
222		.tx()
223		.await?
224		.sign_and_submit_then_watch(call, signer, build_params(nonce))
225		.await?
226		.wait_for_finalized()
227		.await?;
228
229	tx_in_block.wait_for_success().await?;
230	Ok(tx_in_block.block_hash())
231}
232
233/// Gets the current nonce for an account
234pub async fn get_account_nonce(
235	client: &OnlineClient<CustomConfig>,
236	account_id: &<CustomConfig as Config>::AccountId,
237) -> Result<u64, anyhow::Error> {
238	let nonce = client.tx().await?.account_nonce(account_id).await?;
239	Ok(nonce)
240}
241
242/// Matches `indiv_pallet_people_lite::MSG_PREFIX`
243pub const MSG_PREFIX: &[u8; 30] = b"pop:people-lite:register using";
244
245/// Builds a sudo call wrapping `PeopleLite::increase_attestation_allowance`
246pub fn create_increase_allowance_call(
247	who: Vec<u8>,
248	count: u32,
249) -> subxt::transactions::DynamicPayload<Vec<Value>> {
250	subxt::tx::dynamic(
251		"Sudo",
252		"sudo",
253		vec![value! {
254			PeopleLite(increase_attestation_allowance {
255				account: Value::from_bytes(who),
256				count: Value::u128(count as u128),
257			})
258		}],
259	)
260}
261
262/// Builds a `PeopleLite::attest` call
263pub fn create_attest_call(
264	candidate: Vec<u8>,
265	candidate_signature: Vec<u8>,
266	ring_vrf_key: Vec<u8>,
267	proof_of_ownership: Vec<u8>,
268	consumer_registration: Option<Value>,
269) -> subxt::transactions::DynamicPayload<Vec<Value>> {
270	let reg = match consumer_registration {
271		Some(v) => Value::unnamed_variant("Some", [v]),
272		None => Value::unnamed_variant("None", []),
273	};
274	subxt::tx::dynamic(
275		"PeopleLite",
276		"attest",
277		vec![
278			Value::from_bytes(candidate),
279			Value::unnamed_variant("Sr25519", [Value::from_bytes(candidate_signature)]),
280			Value::from_bytes(ring_vrf_key),
281			Value::from_bytes(proof_of_ownership),
282			reg,
283		],
284	)
285}
286
287/// Builds consumer registration parameters for `create_attest_call`
288///
289/// The `LiteConsumerRegistrationParams` struct has fields:
290///   signature: `MultiSignature`, account: `AccountId`,
291///   identifier_key: `CommunicationIdentifier` (`[u8; 65]`),
292///   username: `Username` (`BoundedVec<u8, 32>`), reserved_username: `Option<Username>`
293///
294/// The signing payload is `(account, verifier, identifier_key, username_prefix,
295/// reserved_username).encode()` where `verifier` is the attester (origin of the attest call)
296pub fn create_consumer_registration_params(
297	consumer_pair: &sr25519::Pair,
298	consumer_account: &[u8; 32],
299	verifier_account: &[u8; 32],
300) -> Value {
301	use sp_core::Encode;
302
303	let identifier_key = [0u8; 65];
304	let username = b"testuser.00";
305	let reserved_username: Option<Vec<u8>> = None;
306
307	// Build SCALE-encoded signing payload matching LiteConsumerRegistrationParams::signing_payload:
308	// (account, verifier, identifier_key, username[..separator], reserved_username).encode()
309	// The username prefix is the part before the '.' separator
310	let separator_idx = username.iter().position(|b| *b == b'.').unwrap_or(username.len());
311	let username_prefix = &username[..separator_idx];
312	let payload = (
313		consumer_account,
314		verifier_account,
315		&identifier_key,
316		&username_prefix.to_vec(),
317		&reserved_username,
318	)
319		.encode();
320
321	let sig = consumer_pair.sign(&payload);
322	value! {
323		{
324			signature: Value::unnamed_variant("Sr25519", [Value::from_bytes(sig.0.to_vec())]),
325			account: Value::from_bytes(consumer_account.to_vec()),
326			identifier_key: Value::from_bytes(identifier_key.to_vec()),
327			username: Value::from_bytes(username.to_vec()),
328			reserved_username: Value::unnamed_variant("None", []),
329		}
330	}
331}
332
333/// Sets statement allowances at runtime via a sudo extrinsic signed by Alice
334pub async fn set_allowances_via_sudo(
335	ws_uri: &str,
336	items: Vec<(Vec<u8>, Vec<u8>)>,
337) -> Result<(), anyhow::Error> {
338	log::info!("Setting {} statement allowances via sudo...", items.len());
339
340	let client = OnlineClient::<CustomConfig>::from_insecure_url_with_config(
341		CustomConfig::default(),
342		ws_uri,
343	)
344	.await?;
345	let alice = subxt_signer::sr25519::dev::alice();
346
347	let items_value: Vec<Value> = items
348		.into_iter()
349		.map(|(key, value)| value!((Value::from_bytes(key), Value::from_bytes(value))))
350		.collect();
351	let call = subxt::tx::dynamic(
352		"Sudo",
353		"sudo",
354		vec![value! {
355			System(set_storage { items: items_value })
356		}],
357	);
358
359	client
360		.tx()
361		.await?
362		.sign_and_submit_then_watch_default(&call, &alice)
363		.await?
364		.wait_for_finalized_success()
365		.await?;
366
367	Ok(())
368}