frame-decode 0.17.2

Decode extrinsics and storage from Substrate based chains
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
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
// Copyright (C) 2022-2025 Parity Technologies (UK) Ltd. (admin@parity.io)
// This file is a part of the frame-decode crate.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//         http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use super::storage_type_info::{StorageHasher, StorageInfo, StorageTypeInfo};
use crate::methods::storage_type_info::StorageInfoError;
use crate::utils::{EncodableValues, IntoEncodableValues};
use alloc::vec::Vec;
use scale_type_resolver::TypeResolver;

/// An error returned trying to encode storage keys.
#[non_exhaustive]
#[allow(missing_docs)]
#[derive(Debug, thiserror::Error)]
pub enum StorageKeyEncodeError {
    #[error("Cannot get storage info: {0}")]
    CannotGetInfo(StorageInfoError<'static>),
    #[error("Failed to encode storage key: {0}")]
    EncodeError(#[from] scale_encode::Error),
    #[error("Too many keys provided: expected at most {max_keys_expected}")]
    TooManyKeysProvided {
        /// The maximum number of keys that were expected.
        max_keys_expected: usize,
    },
}

/// Encode a storage key prefix from a pallet name and storage entry name. This prefix
/// is the first 32 bytes of any storage key which comes from a pallet, and is essentially
/// `twox_128(pallet_name) + twox_128(storage_entry_name)`.
pub fn encode_storage_key_prefix(pallet_name: &str, storage_entry: &str) -> [u8; 32] {
    let mut prefix = [0u8; 32];

    let pallet_bytes = sp_crypto_hashing::twox_128(pallet_name.as_bytes());
    let entry_bytes = sp_crypto_hashing::twox_128(storage_entry.as_bytes());

    prefix[..16].copy_from_slice(&pallet_bytes);
    prefix[16..].copy_from_slice(&entry_bytes);

    prefix
}

/// Encode a complete storage key for a given pallet and storage entry and a set of keys that
/// are each able to be encoded via [`scale_encode::EncodeAsType`].
///
/// This is the same as [`encode_storage_key_to`], but returns the encoded key as a `Vec<u8>`, rather
/// than accepting a mutable output buffer.
///
/// # Example
///
/// ```rust
/// use frame_decode::storage::encode_storage_key;
/// use frame_metadata::RuntimeMetadata;
/// use parity_scale_codec::Decode;
///
/// let metadata_bytes = std::fs::read("artifacts/metadata_10000000_9180.scale").unwrap();
/// let RuntimeMetadata::V14(metadata) = RuntimeMetadata::decode(&mut &*metadata_bytes).unwrap() else { return };
///
/// let account_id = [0u8; 32];
///
/// // System.Account needs only one key to point at a specific value; the account ID.
/// // We just fake an account ID for this example  by providing 32 0 bytes, but anything
/// // which would `scale_encode::EncodeAsType` into 32 bytes would work.
/// let encoded_key = encode_storage_key(
///     "System",
///     "Account",
///     &[account_id],
///     &metadata,
///     &metadata.types,
/// ).unwrap();
/// ```
pub fn encode_storage_key<Info, Resolver, Keys>(
    pallet_name: &str,
    storage_entry: &str,
    keys: Keys,
    info: &Info,
    type_resolver: &Resolver,
) -> Result<Vec<u8>, StorageKeyEncodeError>
where
    Keys: IntoEncodableValues,
    Info: StorageTypeInfo,
    Info::TypeId: Clone + core::fmt::Debug,
    Resolver: TypeResolver<TypeId = Info::TypeId>,
{
    // pre-allocate at least as many bytes as we need for the root/prefix.
    let mut out = Vec::with_capacity(32);
    encode_storage_key_to(
        pallet_name,
        storage_entry,
        keys,
        info,
        type_resolver,
        &mut out,
    )?;
    Ok(out)
}

/// Encode a complete storage key for a given pallet and storage entry and a set of keys that
/// are each able to be encoded via [`scale_encode::EncodeAsType`].
///
/// # Example
///
/// ```rust
/// use frame_decode::storage::encode_storage_key_to;
/// use frame_metadata::RuntimeMetadata;
/// use parity_scale_codec::Decode;
///
/// let metadata_bytes = std::fs::read("artifacts/metadata_10000000_9180.scale").unwrap();
/// let RuntimeMetadata::V14(metadata) = RuntimeMetadata::decode(&mut &*metadata_bytes).unwrap() else { return };
///
/// let account_id = [0u8; 32];
///
/// // We'll encode the key to this.
/// let mut encoded_key = Vec::new();
///
/// // System.Account needs only one key to point at a specific value; the account ID.
/// // We just fake an account ID for this example  by providing 32 0 bytes, but anything
/// // which would `scale_encode::EncodeAsType` into 32 bytes would work.
/// encode_storage_key_to(
///     "System",
///     "Account",
///     &[account_id],
///     &metadata,
///     &metadata.types,
///     &mut encoded_key,
/// ).unwrap();
/// ```
pub fn encode_storage_key_to<Info, Resolver, Keys>(
    pallet_name: &str,
    storage_entry: &str,
    keys: Keys,
    info: &Info,
    type_resolver: &Resolver,
    out: &mut Vec<u8>,
) -> Result<(), StorageKeyEncodeError>
where
    Keys: IntoEncodableValues,
    Info: StorageTypeInfo,
    Info::TypeId: Clone + core::fmt::Debug,
    Resolver: TypeResolver<TypeId = Info::TypeId>,
{
    let storage_info = info
        .storage_info(pallet_name, storage_entry)
        .map_err(|e| StorageKeyEncodeError::CannotGetInfo(e.into_owned()))?;

    encode_storage_key_with_info_to(
        pallet_name,
        storage_entry,
        keys,
        &storage_info,
        type_resolver,
        out,
    )
}

/// Encode a complete storage key for a given pallet and storage entry and a set of keys that
/// are each able to be encoded via [`scale_encode::EncodeAsType`].
///
/// Unlike [`encode_storage_key`], which obtains the storage info internally given the pallet and storage entry names,
/// this function takes the storage info as an argument. This is useful if you already have the storage info available,
/// for example if you are encoding multiple keys for the same storage entry.
pub fn encode_storage_key_with_info<Resolver, Keys>(
    pallet_name: &str,
    storage_entry: &str,
    keys: Keys,
    storage_info: &StorageInfo<<Resolver as TypeResolver>::TypeId>,
    type_resolver: &Resolver,
) -> Result<Vec<u8>, StorageKeyEncodeError>
where
    Keys: IntoEncodableValues,
    Resolver: TypeResolver,
    <Resolver as TypeResolver>::TypeId: Clone + core::fmt::Debug,
{
    let mut out = Vec::with_capacity(32);
    encode_storage_key_with_info_to(
        pallet_name,
        storage_entry,
        keys,
        storage_info,
        type_resolver,
        &mut out,
    )?;
    Ok(out)
}

/// Encode a complete storage key for a given pallet and storage entry and a set of keys that
/// are each able to be encoded via [`scale_encode::EncodeAsType`]. Write the response to the provided `Vec`.
///
/// Unlike [`encode_storage_key`], which obtains the storage info internally given the pallet and storage entry names,
/// this function takes the storage info as an argument. This is useful if you already have the storage info available,
/// for example if you are encoding multiple keys for the same storage entry.
pub fn encode_storage_key_with_info_to<Resolver, Keys>(
    pallet_name: &str,
    storage_entry: &str,
    keys: Keys,
    storage_info: &StorageInfo<<Resolver as TypeResolver>::TypeId>,
    type_resolver: &Resolver,
    out: &mut Vec<u8>,
) -> Result<(), StorageKeyEncodeError>
where
    Keys: IntoEncodableValues,
    Resolver: TypeResolver,
    <Resolver as TypeResolver>::TypeId: Clone + core::fmt::Debug,
{
    let num_encodable_values = keys.num_encodable_values();

    // If we provide more encodable values than there are keys, bail.
    // If we provide less, that's ok and we just don't encode every part of the key
    // (useful if eg iterating a bunch of entries under some prefix of a key).
    if num_encodable_values > storage_info.keys.len() {
        return Err(StorageKeyEncodeError::TooManyKeysProvided {
            max_keys_expected: storage_info.keys.len(),
        });
    }

    // Encode the prefix:
    let prefix = encode_storage_key_prefix(pallet_name, storage_entry);
    out.extend_from_slice(&prefix);

    // Encode the keys:
    let mut keys = keys.into_encodable_values();
    let mut temp = Vec::with_capacity(32);
    let iter = (0..num_encodable_values)
        .zip(&*storage_info.keys)
        .map(|(_, k)| k);

    for key_info in iter {
        keys.encode_next_value_to(key_info.key_id.clone(), type_resolver, &mut temp)
            .map_err(StorageKeyEncodeError::EncodeError)?;

        match key_info.hasher {
            StorageHasher::Blake2_128 => {
                let hash = sp_crypto_hashing::blake2_128(&temp);
                out.extend_from_slice(&hash);
            }
            StorageHasher::Blake2_256 => {
                let hash = sp_crypto_hashing::blake2_256(&temp);
                out.extend_from_slice(&hash);
            }
            StorageHasher::Blake2_128Concat => {
                let hash = sp_crypto_hashing::blake2_128(&temp);
                out.extend_from_slice(&hash);
                out.extend_from_slice(&temp);
            }
            StorageHasher::Twox128 => {
                let hash = sp_crypto_hashing::twox_128(&temp);
                out.extend_from_slice(&hash);
            }
            StorageHasher::Twox256 => {
                let hash = sp_crypto_hashing::twox_256(&temp);
                out.extend_from_slice(&hash);
            }
            StorageHasher::Twox64Concat => {
                let hash = sp_crypto_hashing::twox_64(&temp);
                out.extend_from_slice(&hash);
                out.extend_from_slice(&temp);
            }
            StorageHasher::Identity => {
                out.extend_from_slice(&temp);
            }
        }

        // Clear our temp space ready for the next key.
        temp.clear();
    }

    Ok(())
}

/// Encode the end part of a storage key (ie everything except for the prefix that can be encoded
/// via [`encode_storage_key_prefix`]) for a given pallet and storage entry and a set of keys that are each
/// able to be encoded via [`scale_encode::EncodeAsType`].
///
/// This is the same as [`encode_storage_key_suffix_to`], but returns the encoded key as a `Vec<u8>`, rather
/// than accepting a mutable output buffer.
///
/// Prefer [`encode_storage_key`] if you need to encode the entire storage key at once and not just the suffix.
///
/// # Example
///
/// ```rust
/// use frame_decode::storage::{ encode_storage_key_prefix, encode_storage_key_suffix };
/// use frame_metadata::RuntimeMetadata;
/// use parity_scale_codec::Decode;
///
/// let metadata_bytes = std::fs::read("artifacts/metadata_10000000_9180.scale").unwrap();
/// let RuntimeMetadata::V14(metadata) = RuntimeMetadata::decode(&mut &*metadata_bytes).unwrap() else { return };
///
/// let account_id = [0u8; 32];
///
/// // System.Account needs only one key to point at a specific value; the account ID.
/// // We just fake an account ID for this example  by providing 32 0 bytes, but anything
/// // which would `scale_encode::EncodeAsType` into 32 bytes would work.
/// let encoded_key_suffix = encode_storage_key_suffix(
///     "System",
///     "Account",
///     &[account_id],
///     &metadata,
///     &metadata.types,
/// ).unwrap();
/// ```
pub fn encode_storage_key_suffix<Info, Resolver, Keys>(
    pallet_name: &str,
    storage_entry: &str,
    keys: Keys,
    info: &Info,
    type_resolver: &Resolver,
) -> Result<Vec<u8>, StorageKeyEncodeError>
where
    Keys: IntoEncodableValues,
    Info: StorageTypeInfo,
    Info::TypeId: Clone + core::fmt::Debug,
    Resolver: TypeResolver<TypeId = Info::TypeId>,
{
    // pre-allocate at least as many bytes as we need for the root/prefix.
    let mut out = Vec::with_capacity(32);
    encode_storage_key_suffix_to(
        pallet_name,
        storage_entry,
        keys,
        info,
        type_resolver,
        &mut out,
    )?;
    Ok(out)
}

/// Encode the end part of a storage key (ie everything except for the prefix that can be encoded
/// via [`encode_storage_key_prefix`]) for a given pallet and storage entry and a set of keys that are each
/// able to be encoded via [`scale_encode::EncodeAsType`].
///
/// This is the same as [`encode_storage_key_suffix`], but can be handed a `Vec` to encode the bytes to.
///
/// Prefer [`encode_storage_key_to`] if you need to encode the entire storage key at once and not just the suffix.
///
/// # Example
///
/// ```rust
/// use frame_decode::storage::{ encode_storage_key_prefix, encode_storage_key_suffix_to };
/// use frame_metadata::RuntimeMetadata;
/// use parity_scale_codec::Decode;
///
/// let metadata_bytes = std::fs::read("artifacts/metadata_10000000_9180.scale").unwrap();
/// let RuntimeMetadata::V14(metadata) = RuntimeMetadata::decode(&mut &*metadata_bytes).unwrap() else { return };
///
///
/// let account_id = [0u8; 32];
///
/// let mut key = Vec::new();
///
/// // Write the suffix to the provided vec:
/// let encoded_key_suffix = encode_storage_key_suffix_to(
///     "System",
///     "Account",
///     &[account_id],
///     &metadata,
///     &metadata.types,
///     &mut key
/// ).unwrap();
/// ```
pub fn encode_storage_key_suffix_to<Info, Resolver, Keys>(
    pallet_name: &str,
    storage_entry: &str,
    keys: Keys,
    info: &Info,
    type_resolver: &Resolver,
    out: &mut Vec<u8>,
) -> Result<(), StorageKeyEncodeError>
where
    Keys: IntoEncodableValues,
    Info: StorageTypeInfo,
    Info::TypeId: Clone + core::fmt::Debug,
    Resolver: TypeResolver<TypeId = Info::TypeId>,
{
    let storage_info = info
        .storage_info(pallet_name, storage_entry)
        .map_err(|e| StorageKeyEncodeError::CannotGetInfo(e.into_owned()))?;

    encode_storage_key_suffix_with_info_to(keys, &storage_info, type_resolver, out)
}

/// Encode the end part of a storage key (ie everything except for the prefix that can be encoded
/// via [`encode_storage_key_prefix`]) for a given pallet and storage entry and a set of keys that are each
/// able to be encoded via [`scale_encode::EncodeAsType`].
///
/// This is the same as [`encode_storage_key_suffix_to`], but is instead handed storage info that has been
/// pre-computed via [`StorageTypeInfo::storage_info`]. This avoids having to retrieve this information multiple
/// times if you'd like to encode many key suffixes for the same storage entry.
///
/// Prefer [`encode_storage_key_with_info_to`] if you need to encode the entire storage key at once and not
/// just the suffix.
pub fn encode_storage_key_suffix_with_info_to<Resolver, Keys>(
    keys: Keys,
    storage_info: &StorageInfo<<Resolver as TypeResolver>::TypeId>,
    type_resolver: &Resolver,
    out: &mut Vec<u8>,
) -> Result<(), StorageKeyEncodeError>
where
    Keys: IntoEncodableValues,
    Resolver: TypeResolver,
    <Resolver as TypeResolver>::TypeId: Clone + core::fmt::Debug,
{
    let num_encodable_values = keys.num_encodable_values();

    // If we provide more encodable values than there are keys, bail.
    // If we provide less, that's ok and we just don't encode every part of the key
    // (useful if eg iterating a bunch of entries under some prefix of a key).
    if num_encodable_values > storage_info.keys.len() {
        return Err(StorageKeyEncodeError::TooManyKeysProvided {
            max_keys_expected: storage_info.keys.len(),
        });
    }

    // Encode the keys:
    let mut keys = keys.into_encodable_values();
    let mut temp = Vec::with_capacity(32);
    let iter = (0..num_encodable_values)
        .zip(&*storage_info.keys)
        .map(|(_, k)| k);

    for key_info in iter {
        keys.encode_next_value_to(key_info.key_id.clone(), type_resolver, &mut temp)
            .map_err(StorageKeyEncodeError::EncodeError)?;

        match key_info.hasher {
            StorageHasher::Blake2_128 => {
                let hash = sp_crypto_hashing::blake2_128(&temp);
                out.extend_from_slice(&hash);
            }
            StorageHasher::Blake2_256 => {
                let hash = sp_crypto_hashing::blake2_256(&temp);
                out.extend_from_slice(&hash);
            }
            StorageHasher::Blake2_128Concat => {
                let hash = sp_crypto_hashing::blake2_128(&temp);
                out.extend_from_slice(&hash);
                out.extend_from_slice(&temp);
            }
            StorageHasher::Twox128 => {
                let hash = sp_crypto_hashing::twox_128(&temp);
                out.extend_from_slice(&hash);
            }
            StorageHasher::Twox256 => {
                let hash = sp_crypto_hashing::twox_256(&temp);
                out.extend_from_slice(&hash);
            }
            StorageHasher::Twox64Concat => {
                let hash = sp_crypto_hashing::twox_64(&temp);
                out.extend_from_slice(&hash);
                out.extend_from_slice(&temp);
            }
            StorageHasher::Identity => {
                out.extend_from_slice(&temp);
            }
        }

        // Clear our temp space ready for the next key.
        temp.clear();
    }

    Ok(())
}

#[cfg(test)]
mod test {
    use super::*;

    #[test]
    fn test_encode_storage_key() {
        use crate::storage::encode_storage_key;
        use frame_metadata::RuntimeMetadata;
        use parity_scale_codec::Decode;

        let metadata_bytes = std::fs::read("artifacts/metadata_10000000_9180.scale").unwrap();
        let RuntimeMetadata::V14(metadata) =
            RuntimeMetadata::decode(&mut &*metadata_bytes).unwrap()
        else {
            return;
        };

        let account_id = [0u8; 32];

        // System.Account needs only one key to point at a specific value; the account ID.
        // We just fake an account ID for this example by providing 32 0 bytes, but anything
        // which would `scale_encode::EncodeAsType` into 32 bytes should work.
        encode_storage_key(
            "System",
            "Account",
            &[account_id],
            &metadata,
            &metadata.types,
        )
        .expect("Encoding should work");
        encode_storage_key(
            "System",
            "Account",
            &(account_id,),
            &metadata,
            &metadata.types,
        )
        .expect("Encoding should work");

        // We provide no additional keys, so we should get the prefix only.
        let out = encode_storage_key("System", "Account", &(), &metadata, &metadata.types)
            .expect("Encoding should work");
        assert_eq!(&out, &encode_storage_key_prefix("System", "Account"));

        // We provide too many additional keys so should get an error.
        let err = encode_storage_key(
            "System",
            "Account",
            &(account_id, 123u16),
            &metadata,
            &metadata.types,
        );
        assert!(matches!(
            err,
            Err(StorageKeyEncodeError::TooManyKeysProvided {
                max_keys_expected: 1
            })
        ));
    }
}