Newer
Older
use anyhow::{anyhow, Context, Result};
use clap::Parser;
use codec::Encode;
use sp_core::{
crypto::{AccountId32, DeriveJunction, Pair as _},
sr25519::Pair,
};
use subxt::{
extrinsic::{BaseExtrinsicParams, BaseExtrinsicParamsBuilder},
ClientBuilder, DefaultConfig, PairSigner,
};
pub type Api = gdev_300::RuntimeApi<DefaultConfig, BaseExtrinsicParams<DefaultConfig, Tip>>;
#[derive(Copy, Clone, Debug, Default, Encode)]
pub struct Tip {
#[codec(compact)]
tip: u64,
}
impl Tip {
pub fn new(amount: u64) -> Self {
Tip { tip: amount }
}
}
impl From<u64> for Tip {
fn from(n: u64) -> Self {
Self::new(n)
}
}
#[derive(Parser, Debug)]
#[clap(author, version, about, long_about = None)]
struct Args {
#[clap(subcommand)]
pub subcommand: Subcommand,
/// Indexer URL
#[clap(short, long, default_value = "https://idx.gdev.cgeek.fr/v1/graphql")]
indexer: String,
/// Do not use indexer
#[clap(long)]
no_indexer: bool,
/// Secret key or BIP39 mnemonic
/// (eventually followed by derivation path)
#[clap(short, long)]
secret: String,
/// Websocket RPC endpoint
#[clap(short, long, default_value = "ws://localhost:9944")]
url: String,
}
#[derive(Debug, clap::Subcommand)]
pub enum Subcommand {
CreateOneshot {
balance: u64,
dest: sp_core::crypto::AccountId32,
},
ConsumeOneshot {
dest: sp_core::crypto::AccountId32,
#[clap(long = "oneshot")]
dest_oneshot: bool,
},
ConsumeOneshotWithRemaining {
balance: u64,
dest: sp_core::crypto::AccountId32,
#[clap(long = "one")]
dest_oneshot: bool,
remaining_to: sp_core::crypto::AccountId32,
#[clap(long = "rem-one")]
remaining_to_oneshot: bool,
},
/// List upcoming expirations that require an action
Expire {
/// Show certs that expire within less than this number of blocks
#[clap(short, long, default_value_t = 100800)]
blocks: u32,
/// Show authorities that should rotate keys within less than this number of sessions
#[clap(short, long, default_value_t = 100)]
sessions: u32,
},
/// Generate a revocation document for the provided account
GenRevocDoc,
OneshotBalance {
account: sp_core::crypto::AccountId32,
},
#[clap(hide = true)]
Repart {
// Number of transactions per block to target
target: u32,
#[clap(short = 'o', long = "old-repart")]
// Old/actual repartition
actual_repart: Option<u32>,
},
#[clap(hide = true)]
SpamRoll { actual_repart: usize },
Transfer {
balance: u64,
dest: sp_core::crypto::AccountId32,
#[clap(short = 'k')]
keep_alive: bool,
},
}
#[tokio::main(flavor = "current_thread")]
async fn main() -> Result<()> {
env_logger::init();
let args = Args::parse();
let pair = Pair::from_string(&args.secret, None)
.map_err(|_| anyhow!("Invalid secret {}", args.secret))?;
let client: Client = ClientBuilder::new()
.set_url(&args.url)
.build()
.await
.with_context(|| "fail to connect to node")?;
let api = client.clone().to_runtime_api::<Api>();
let gql_client = reqwest::Client::builder()
.user_agent("gcli/0.1.0")
.build()?;
let account_id: sp_core::crypto::AccountId32 = pair.public().into();
let account = api.storage().system().account(&account_id, None).await?;
logs::info!("Account free balance: {}", account.data.free);
match args.subcommand {
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
Subcommand::CreateOneshot { balance, dest } => {
api.tx()
.oneshot_account()
.create_oneshot_account(dest.into(), balance)?
.sign_and_submit_then_watch(
&PairSigner::new(pair),
BaseExtrinsicParamsBuilder::new(),
)
.await?;
}
Subcommand::ConsumeOneshot { dest, dest_oneshot } => {
let number = api.storage().system().number(None).await?;
api.tx()
.oneshot_account()
.consume_oneshot_account(
number,
if dest_oneshot {
gdev_300::runtime_types::pallet_oneshot_account::types::Account::Oneshot(
dest.into(),
)
} else {
gdev_300::runtime_types::pallet_oneshot_account::types::Account::Normal(
dest.into(),
)
},
)?
.sign_and_submit_then_watch(
&PairSigner::new(pair),
BaseExtrinsicParamsBuilder::new(),
)
.await?;
}
Subcommand::ConsumeOneshotWithRemaining {
balance,
dest,
dest_oneshot,
remaining_to,
remaining_to_oneshot,
} => {
let number = api.storage().system().number(None).await?;
api.tx()
.oneshot_account()
.consume_oneshot_account_with_remaining(
number,
if dest_oneshot {
gdev_300::runtime_types::pallet_oneshot_account::types::Account::Oneshot(
dest.into(),
)
} else {
gdev_300::runtime_types::pallet_oneshot_account::types::Account::Normal(
dest.into(),
)
},
if remaining_to_oneshot {
gdev_300::runtime_types::pallet_oneshot_account::types::Account::Oneshot(
remaining_to.into(),
)
} else {
gdev_300::runtime_types::pallet_oneshot_account::types::Account::Normal(
remaining_to.into(),
)
},
balance,
)?
.sign_and_submit_then_watch(
&PairSigner::new(pair),
BaseExtrinsicParamsBuilder::new(),
)
.await?;
}
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
Subcommand::Expire { blocks, sessions } => {
let parent_hash = api.storage().system().parent_hash(None).await?;
let current_block = api.storage().system().number(Some(parent_hash)).await?;
let current_session = api
.storage()
.session()
.current_index(Some(parent_hash))
.await?;
let end_block = current_block + blocks;
let end_session = current_session + sessions;
let mut identity_cache = cache::IdentityCache::new(
&api,
if args.no_indexer {
None
} else {
Some((&gql_client, &args.indexer))
},
);
// Rotate keys
let mut must_rotate_keys_before_iter = client
.storage()
.iter::<gdev_300::authority_members::storage::MustRotateKeysBefore>(Some(
parent_hash,
))
.await?;
let mut must_rotate_keys_before = BTreeMap::new();
while let Some((k, v)) = must_rotate_keys_before_iter.next().await? {
let session_index = u32::from_le_bytes(k.as_ref()[40..44].try_into().unwrap());
if session_index < end_session {
must_rotate_keys_before.insert(session_index - current_session, v);
}
}
println!("\nAuthority members:");
for (sessions_left, identity_ids) in must_rotate_keys_before {
println!("Must rotate keys before {} sessions:", sessions_left);
for identity_id in identity_ids {
println!(
" {} ({})",
identity_cache
.fetch_identity(identity_id, parent_hash)
.await
.unwrap_or_else(|_| "?".into()),
identity_id
);
}
}
// Certifications
let mut basic_certs_iter = client
.storage()
.iter::<gdev_300::cert::storage::StorageCertsRemovableOn>(Some(parent_hash))
.await?;
let mut basic_certs = BTreeMap::new();
while let Some((k, v)) = basic_certs_iter.next().await? {
let block_number = u32::from_le_bytes(k.as_ref()[40..44].try_into().unwrap());
if block_number < end_block {
basic_certs.insert(block_number - current_block, v);
}
}
let mut smith_certs_iter = client
.storage()
.iter::<gdev_300::smiths_cert::storage::StorageCertsRemovableOn>(Some(parent_hash))
.await?;
let mut smith_certs = BTreeMap::new();
while let Some((k, v)) = smith_certs_iter.next().await? {
let block_number = u32::from_le_bytes(k.as_ref()[40..44].try_into().unwrap());
if block_number < end_block {
smith_certs.insert(block_number - current_block, v);
}
}
for (title, certs) in [
("Certifications", basic_certs),
("Smith certifications", smith_certs),
] {
println!("\n{}:", title);
for (blocks_left, certs) in certs {
println!("{} blocks before expiration:", blocks_left);
for (issuer_id, receiver_id) in certs {
println!(
" {} ({}) -> {} ({})",
identity_cache
.fetch_identity(issuer_id, parent_hash)
.await
.unwrap_or_else(|_| "?".into()),
issuer_id,
identity_cache
.fetch_identity(receiver_id, parent_hash)
.await
.unwrap_or_else(|_| "?".into()),
receiver_id,
);
}
}
}
// Memberships
let mut basic_membership_iter = client
.storage()
.iter::<gdev_300::membership::storage::MembershipsExpireOn>(Some(parent_hash))
.await?;
let mut basic_memberships = BTreeMap::new();
while let Some((k, v)) = basic_membership_iter.next().await? {
let block_number = u32::from_le_bytes(k.as_ref()[40..44].try_into().unwrap());
if block_number < end_block {
basic_memberships.insert(block_number - current_block, v);
}
}
let mut smith_membership_iter = client
.storage()
.iter::<gdev_300::smiths_membership::storage::MembershipsExpireOn>(Some(
parent_hash,
))
.await?;
let mut smith_memberships = BTreeMap::new();
while let Some((k, v)) = smith_membership_iter.next().await? {
let block_number = u32::from_le_bytes(k.as_ref()[40..44].try_into().unwrap());
if block_number < end_block {
smith_memberships.insert(block_number - current_block, v);
}
}
for (title, memberships) in [
("Memberships", basic_memberships),
("Smith memberships", smith_memberships),
] {
println!("\n{}:", title);
for (blocks_left, membership) in memberships {
println!("{} blocks before expiration:", blocks_left);
for identity_id in membership {
println!(
" {} ({})",
identity_cache
.fetch_identity(identity_id, parent_hash)
.await
.unwrap_or_else(|_| "?".into()),
identity_id,
);
}
}
}
}
Subcommand::OneshotBalance { account } => {
logs::info!(
"{}",
api.storage()
.oneshot_account()
.oneshot_accounts(&account, None)
.await?
.unwrap_or(0)
);
}
Subcommand::Repart {
target,
actual_repart,
} => {
let mut pairs = Vec::new();
for i in actual_repart.unwrap_or_default()..target {
let pair_i = pair
.derive(std::iter::once(DeriveJunction::hard::<u32>(i)), None)
.map_err(|_| anyhow!("Fail to derive //{}", i))?
.0;
pairs.push((i, pair_i));
}
for (i, pair_i) in &pairs {
/*let _ = api
.tx()
.balances()
.transfer(MultiAddress::Id(pair_i.public().into()), 501)?
.sign_and_submit_then_watch(&signer, BaseExtrinsicParamsBuilder::new())
.await?
.wait_for_in_block()
.await?;
signer.increment_nonce();*/
let pair_i_account = api
.storage()
.system()
.await?;
logs::info!("account //{} balance: {}", i, pair_i_account.data.free);
}
}
Subcommand::SpamRoll { actual_repart } => {
let mut pairs =
Vec::<(PairSigner<DefaultConfig, Pair>, AccountId32)>::with_capacity(actual_repart);
for i in 0..actual_repart {
let pair_i = pair
.derive(std::iter::once(DeriveJunction::hard::<u32>(i as u32)), None)
.map_err(|_| anyhow!("Fail to derive //{}", i))?
.0;
let account_id_i = pair_i.public().into();
pairs.push((PairSigner::new(pair_i), account_id_i));
}
loop {
let mut watchers = Vec::with_capacity(actual_repart);
for i in 0..(actual_repart - 1) {
let dest: AccountId32 = pairs[i + 1].1.clone();
let watcher = api
.tx()
.balances()
.transfer(MultiAddress::Id(dest), 1)?
.sign_and_submit_then_watch(&pairs[i].0, BaseExtrinsicParamsBuilder::new())
.await?;
pairs[i].0.increment_nonce();
logs::info!("send 1 cent from //{} to //{}", i, i + 1);
watchers.push(watcher);
}
let dest: AccountId32 = pairs[0].1.clone();
let watcher = api
.tx()
.balances()
.transfer(MultiAddress::Id(dest), 1)?
.sign_and_submit_then_watch(
&pairs[actual_repart - 1].0,
BaseExtrinsicParamsBuilder::new(),
)
.await?;
pairs[actual_repart - 1].0.increment_nonce();
logs::info!("send 1 cent from //{} to //0", actual_repart - 1);
watchers.push(watcher);
// Wait all transactions
for watcher in watchers {
watcher.wait_for_in_block().await?;
}
}
}
Subcommand::Transfer {
balance,
dest,
keep_alive,
} => {
if keep_alive {
api.tx()
.balances()
.transfer(dest.into(), balance)?
.sign_and_submit_then_watch(
&PairSigner::new(pair),
BaseExtrinsicParamsBuilder::new(),
)
.await?;
} else {
api.tx()
.balances()
.transfer_keep_alive(dest.into(), balance)?
.sign_and_submit_then_watch(
&PairSigner::new(pair),
BaseExtrinsicParamsBuilder::new(),
)
.await?;
}
}
}
Ok(())
}
async fn gen_revoc_doc(api: &Api, pair: &Pair) -> Result<()> {
let account_id: sp_core::crypto::AccountId32 = pair.public().into();
let genesis_hash = api.storage().system().block_hash(&0, None).await?;