-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathpreimage.rs
More file actions
444 lines (380 loc) Β· 13.6 KB
/
preimage.rs
File metadata and controls
444 lines (380 loc) Β· 13.6 KB
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
//! `quantus preimage` subcommand - preimage operations
use crate::{chain::quantus_subxt, error::QuantusError, log_error, log_print, log_verbose};
use clap::Subcommand;
use colored::Colorize;
use std::str::FromStr;
use subxt::utils::H256;
/// Preimage operations
#[derive(Subcommand, Debug)]
pub enum PreimageCommands {
/// Check if a preimage exists and get its status
#[command(name = "status")]
Status {
/// Preimage hash (hex format)
#[arg(long)]
hash: String,
},
/// Get preimage content
#[command(name = "get")]
Get {
/// Preimage hash (hex format)
#[arg(long)]
hash: String,
/// Preimage length (required for retrieval)
#[arg(long)]
len: u32,
},
/// List all preimages
#[command(name = "list")]
List,
/// Request a preimage (no deposit required)
#[command(name = "request")]
Request {
/// Preimage hash (hex format)
#[arg(long)]
hash: String,
/// Wallet to use for the request
#[arg(long)]
from: String,
},
/// Note a preimage (requires deposit)
#[command(name = "note")]
Note {
/// Preimage content (hex format)
#[arg(long)]
content: String,
/// Wallet to use for the note
#[arg(long)]
from: String,
},
/// Create a preimage from WASM file (like in tech-referenda)
#[command(name = "create")]
Create {
/// WASM file path
#[arg(long)]
wasm_file: std::path::PathBuf,
/// Wallet to use for the preimage
#[arg(long)]
from: String,
/// Password for wallet (optional)
#[arg(long)]
password: Option<String>,
/// Password file path (optional)
#[arg(long)]
password_file: Option<String>,
},
}
/// Handle preimage commands
pub async fn handle_preimage_command(
command: PreimageCommands,
node_url: &str,
execution_mode: crate::cli::common::ExecutionMode,
) -> crate::error::Result<()> {
let quantus_client = crate::chain::client::QuantusClient::new(node_url).await?;
match command {
PreimageCommands::Status { hash } => {
check_preimage_status(&quantus_client, &hash).await?;
},
PreimageCommands::Get { hash, len } => {
get_preimage_content(&quantus_client, &hash, len).await?;
},
PreimageCommands::List => {
list_preimages(&quantus_client).await?;
},
PreimageCommands::Request { hash, from } => {
request_preimage(&quantus_client, &hash, &from, execution_mode).await?;
},
PreimageCommands::Note { content, from } => {
note_preimage(&quantus_client, &content, &from, execution_mode).await?;
},
PreimageCommands::Create { wasm_file, from, password, password_file } => {
create_preimage(
&quantus_client,
wasm_file,
&from,
password,
password_file,
execution_mode,
)
.await?;
},
}
Ok(())
}
/// Check preimage status
async fn check_preimage_status(
quantus_client: &crate::chain::client::QuantusClient,
hash_str: &str,
) -> crate::error::Result<()> {
let preimage_hash = parse_hash(hash_str)?;
log_print!("π Checking preimage status for hash: {}", hash_str.bright_cyan());
let latest_block_hash = quantus_client.get_latest_block().await?;
let storage_at = quantus_client.client().storage().at(latest_block_hash);
// Check StatusFor (old format)
let status_addr = quantus_subxt::api::storage().preimage().status_for(preimage_hash);
let status_result = storage_at.fetch(&status_addr).await;
// Check RequestStatusFor (new format)
let request_status_addr =
quantus_subxt::api::storage().preimage().request_status_for(preimage_hash);
let request_status_result = storage_at.fetch(&request_status_addr).await;
log_print!("π Preimage Status Results:");
log_print!(" π Hash: {}", hash_str.bright_yellow());
match status_result {
Ok(Some(status)) => {
log_print!(" π StatusFor (Old): {:?}", status);
},
Ok(None) => {
log_print!(" π StatusFor (Old): Not found");
},
Err(e) => {
log_print!(" π StatusFor (Old): Error - {:?}", e);
},
}
match request_status_result {
Ok(Some(request_status)) => {
log_print!(" π RequestStatusFor (New): {:?}", request_status);
},
Ok(None) => {
log_print!(" π RequestStatusFor (New): Not found");
},
Err(e) => {
log_print!(" π RequestStatusFor (New): Error - {:?}", e);
},
}
// Check if preimage content exists (we need to know the length)
// For now, we'll try with a reasonable length
let preimage_addr =
quantus_subxt::api::storage().preimage().preimage_for((preimage_hash, 0u32));
let preimage_result = storage_at.fetch(&preimage_addr).await;
match preimage_result {
Ok(Some(_)) => {
log_print!(" π¦ PreimageFor: Content exists (length 0)");
},
Ok(None) => {
log_print!(" π¦ PreimageFor: No content found (length 0)");
},
Err(e) => {
log_print!(" π¦ PreimageFor: Error - {:?}", e);
},
}
Ok(())
}
/// Get preimage content
async fn get_preimage_content(
quantus_client: &crate::chain::client::QuantusClient,
hash_str: &str,
len: u32,
) -> crate::error::Result<()> {
let preimage_hash = parse_hash(hash_str)?;
log_print!("π¦ Getting preimage content for hash: {}", hash_str.bright_cyan());
log_print!(" π Length: {} bytes", len);
let latest_block_hash = quantus_client.get_latest_block().await?;
let storage_at = quantus_client.client().storage().at(latest_block_hash);
let preimage_addr = quantus_subxt::api::storage().preimage().preimage_for((preimage_hash, len));
let preimage_result = storage_at.fetch(&preimage_addr).await;
match preimage_result {
Ok(Some(bounded_vec)) => {
log_print!("β
Preimage content found!");
log_print!(" π Actual length: {} bytes", bounded_vec.0.len());
// Convert to Vec<u8> for display
let content: Vec<u8> = bounded_vec.0;
// Show first 100 bytes as hex
let preview_len = std::cmp::min(100, content.len());
let preview = &content[..preview_len];
log_print!(" π Preview (first {} bytes):", preview_len);
log_print!(" {}", hex::encode(preview).bright_green());
if content.len() > preview_len {
log_print!(" ... ({} more bytes)", content.len() - preview_len);
}
// Try to decode as call data
log_verbose!(" π§ Attempting to decode as call data...");
log_print!(" π Raw content preview (first 100 bytes):");
log_print!(
" {}",
hex::encode(&content[..std::cmp::min(100, content.len())]).bright_green()
);
},
Ok(None) => {
log_error!("β Preimage content not found for hash {} with length {}", hash_str, len);
},
Err(e) => {
log_error!("β Error fetching preimage content: {:?}", e);
},
}
Ok(())
}
/// List all preimages
async fn list_preimages(
quantus_client: &crate::chain::client::QuantusClient,
) -> crate::error::Result<()> {
log_print!("π Listing all preimages...");
let latest_block_hash = quantus_client.get_latest_block().await?;
let storage_at = quantus_client.client().storage().at(latest_block_hash);
let mut preimage_count = 0;
let mut unrequested_count = 0;
let mut requested_count = 0;
// Iterate PreimageFor keys; extract (hash, len) from key_bytes and optionally fetch status
let preimage_for_addr = quantus_subxt::api::storage().preimage().preimage_for_iter();
let mut image_stream = storage_at.iter(preimage_for_addr).await.map_err(|e| {
QuantusError::Generic(format!("Failed to iterate preimage contents: {:?}", e))
})?;
while let Some(result) = image_stream.next().await {
match result {
Ok(entry) => {
let key = entry.key_bytes;
if key.len() >= 36 {
let len_le = &key[key.len() - 4..];
let len = u32::from_le_bytes([len_le[0], len_le[1], len_le[2], len_le[3]]);
let hash = sp_core::H256::from_slice(&key[key.len() - 36..key.len() - 4]);
let status = storage_at
.fetch(&quantus_subxt::api::storage().preimage().request_status_for(hash))
.await
.ok()
.flatten();
preimage_count += 1;
match status {
Some(quantus_subxt::api::runtime_types::pallet_preimage::RequestStatus::Unrequested { ticket: _, len: status_len }) => {
unrequested_count += 1;
log_print!(" π {} (Unrequested, {} bytes)", hash, status_len);
},
Some(quantus_subxt::api::runtime_types::pallet_preimage::RequestStatus::Requested { maybe_ticket: _, count, maybe_len }) => {
requested_count += 1;
let len_str = match maybe_len { Some(l) => format!("{} bytes", l), None => format!("{} bytes (from key)", len) };
log_print!(" π {} (Requested, count: {}, {})", hash, count, len_str);
},
None => {
log_print!(" π {} (Unknown status, {} bytes)", hash, len);
},
}
}
},
Err(e) => log_verbose!("β οΈ Error reading preimage content entry: {:?}", e),
}
}
log_print!("");
log_print!("π Preimage Summary:");
log_print!(" π Total preimages: {}", preimage_count);
log_print!(" π Unrequested: {}", unrequested_count);
log_print!(" π Requested: {}", requested_count);
if preimage_count == 0 {
log_print!(" π‘ No preimages found on chain");
}
Ok(())
}
/// Request a preimage (no deposit required)
async fn request_preimage(
quantus_client: &crate::chain::client::QuantusClient,
hash_str: &str,
from_str: &str,
execution_mode: crate::cli::common::ExecutionMode,
) -> crate::error::Result<()> {
let preimage_hash = parse_hash(hash_str)?;
log_print!("π Requesting preimage for hash: {}", hash_str.bright_cyan());
log_print!(" π€ From: {}", from_str.bright_yellow());
// Load wallet keypair
let keypair = crate::wallet::load_keypair_from_wallet(from_str, None, None)?;
// Create request_preimage call
let request_call = quantus_subxt::api::tx().preimage().request_preimage(preimage_hash);
// Submit transaction
let tx_hash = crate::cli::common::submit_transaction(
quantus_client,
&keypair,
request_call,
None,
execution_mode,
)
.await?;
log_print!("β
Preimage request transaction submitted: {:?}", tx_hash);
// Wait for confirmation
log_print!("β³ Waiting for preimage request confirmation...");
log_print!("β
Preimage request confirmed!");
Ok(())
}
/// Note a preimage (requires deposit)
async fn note_preimage(
quantus_client: &crate::chain::client::QuantusClient,
content_str: &str,
from_str: &str,
execution_mode: crate::cli::common::ExecutionMode,
) -> crate::error::Result<()> {
let content = hex::decode(content_str.trim_start_matches("0x"))
.map_err(|e| QuantusError::Generic(format!("Invalid hex content: {}", e)))?;
log_print!("π Noting preimage for content length: {} bytes", content.len());
log_print!(" π€ From: {}", from_str.bright_yellow());
// Load wallet keypair
let keypair = crate::wallet::load_keypair_from_wallet(from_str, None, None)?;
// Create note_preimage call
let note_call = quantus_subxt::api::tx().preimage().note_preimage(content);
// Submit transaction
let tx_hash = crate::cli::common::submit_transaction(
quantus_client,
&keypair,
note_call,
None,
execution_mode,
)
.await?;
log_print!("β
Preimage note transaction submitted: {:?}", tx_hash);
// Wait for confirmation
log_print!("β³ Waiting for preimage note confirmation...");
log_print!("β
Preimage note confirmed!");
Ok(())
}
/// Create a preimage from WASM file (like in tech-referenda)
async fn create_preimage(
quantus_client: &crate::chain::client::QuantusClient,
wasm_file: std::path::PathBuf,
from_str: &str,
password: Option<String>,
password_file: Option<String>,
execution_mode: crate::cli::common::ExecutionMode,
) -> crate::error::Result<()> {
log_print!("π¦ Creating preimage from WASM file: {}", wasm_file.display());
log_print!(" π€ From: {}", from_str.bright_yellow());
if !wasm_file.exists() {
return Err(QuantusError::Generic(format!("WASM file not found: {}", wasm_file.display())));
}
// Read WASM file
let wasm_code = std::fs::read(&wasm_file)
.map_err(|e| QuantusError::Generic(format!("Failed to read WASM file: {}", e)))?;
log_print!("π WASM file size: {} bytes", wasm_code.len());
// Load wallet keypair
let keypair = crate::wallet::load_keypair_from_wallet(from_str, password, password_file)?;
// Build a static payload for System::set_code and encode full call data (pallet + call + args)
let set_code_payload = quantus_subxt::api::tx().system().set_code(wasm_code.clone());
let metadata = quantus_client.client().metadata();
let encoded_call = <_ as subxt::tx::Payload>::encode_call_data(&set_code_payload, &metadata)
.map_err(|e| QuantusError::Generic(format!("Failed to encode call data: {:?}", e)))?;
log_verbose!("π Encoded call size: {} bytes", encoded_call.len());
let preimage_hash: sp_core::H256 =
<sp_runtime::traits::BlakeTwo256 as sp_runtime::traits::Hash>::hash(&encoded_call);
log_print!("π Preimage hash: {:?}", preimage_hash);
// Submit Preimage::note_preimage with bounded bytes
type PreimageBytes = quantus_subxt::api::preimage::calls::types::note_preimage::Bytes;
let bounded_bytes: PreimageBytes = encoded_call.clone();
log_print!("π Submitting preimage...");
let note_preimage_tx = quantus_subxt::api::tx().preimage().note_preimage(bounded_bytes);
let preimage_tx_hash = crate::cli::common::submit_transaction(
quantus_client,
&keypair,
note_preimage_tx,
None,
execution_mode,
)
.await?;
log_print!("β
Preimage transaction submitted: {:?}", preimage_tx_hash);
// Wait for preimage transaction confirmation
log_print!("β³ Waiting for preimage transaction confirmation...");
log_print!("β
Preimage transaction confirmed!");
log_print!("π― Preimage created successfully!");
log_print!(" π Hash: {:?}", preimage_hash);
log_print!(" π Size: {} bytes", encoded_call.len());
Ok(())
}
/// Parse hash string to H256
fn parse_hash(hash_str: &str) -> crate::error::Result<H256> {
let hash_str = hash_str.trim_start_matches("0x");
H256::from_str(hash_str).map_err(|e| {
QuantusError::Generic(format!("Invalid hash format: {}. Expected 64 hex characters", e))
})
}