host-encoding 0.3.7

Pure codec and hash functions for DOTNS and statement-store — no I/O, WASM-safe
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
//! Substrate extrinsic signing payload decoder.
//!
//! Decodes the opaque `payload` bytes from a `NeedsSign` outcome (tag 36,
//! `sign_payload`) into structured fields: genesis hash, block hash,
//! spec version, transaction version, and optional metadata hash.
//!
//! # Layout
//!
//! A Substrate V4 extrinsic signing payload is:
//!
//! ```text
//! [call_data ++ signed_extensions_extra] | spec_version(4) | tx_version(4) | genesis_hash(32) | block_hash(32) [| metadata_hash_option(1 or 33)]
//! ```
//!
//! The "additional signed" tail has fixed sizes and is always at the end.
//! Everything before it (call data concatenated with extensions extra like
//! era, nonce, tip) is returned as an opaque blob — separating call data
//! from extensions requires runtime metadata.
//!
//! # Limitations
//!
//! - **Heuristic, not a security boundary.** A malicious app can craft raw
//!   bytes where the tail positions produce any `genesis_hash`. Use the
//!   decoded fields for display/hint purposes only — they are not a
//!   guarantee of what the signer will actually commit to.
//!
//! - **Substrate V4 only.** Future extrinsic format versions (V5+) may
//!   change the additional-signed layout. If decoding fails, callers should
//!   fall back to displaying the raw hex payload.
//!
//! - **Pre-hashed payloads.** When the original payload exceeds 256 bytes,
//!   the Substrate signing protocol hashes it (blake2b-256) to 32 bytes
//!   before signing. If the `payload` field in `NeedsSign` is already the
//!   32-byte hash, this function returns [`ExtrinsicError::PayloadHashed`].
//!
//! No I/O. No threads. WASM-safe.

use thiserror::Error;

/// Errors from extrinsic signing payload decoding.
#[derive(Debug, Error, PartialEq)]
pub enum ExtrinsicError {
    /// The payload is exactly 32 bytes, which strongly suggests it has already
    /// been blake2b-256 hashed (Substrate hashes payloads > 256 bytes before
    /// signing). A hash cannot be decoded into structured fields.
    #[error("signing payload appears to be pre-hashed (32 bytes); cannot decode")]
    PayloadHashed,

    /// The payload is too short or has an unrecognizable layout. None of the
    /// three known additional-signed tail interpretations (with metadata hash
    /// Some, with metadata hash None, or without CheckMetadataHash) produced
    /// a valid result with a non-empty call-data prefix.
    #[error("no valid extrinsic layout found ({actual} bytes); ensure it is a Substrate V4 signing payload and is not pre-hashed")]
    InvalidLayout { actual: usize },
}

/// Decoded fields from a Substrate extrinsic signing payload.
///
/// See [module documentation](self) for layout details and limitations.
#[derive(Debug, Clone, PartialEq)]
pub struct DecodedSignPayload {
    /// Genesis hash of the target chain (32 bytes).
    pub genesis_hash: [u8; 32],
    /// Block hash for the mortality window (32 bytes).
    /// For immortal transactions this equals `genesis_hash`.
    pub block_hash: [u8; 32],
    /// Runtime spec version.
    pub spec_version: u32,
    /// Transaction format version.
    pub tx_version: u32,
    /// Metadata hash from `CheckMetadataHash` extension, if active with mode=1.
    pub metadata_hash: Option<[u8; 32]>,
    /// Raw bytes containing call data concatenated with signed-extension extra
    /// data (era, nonce, tip, and any other extension-specific bytes).
    ///
    /// Splitting call data from extensions requires runtime metadata. Without
    /// metadata, this blob can still be displayed as hex for user confirmation.
    pub call_data_and_extra: Vec<u8>,
}

// Additional-signed tail sizes for each interpretation.
// spec_version(4) + tx_version(4) + genesis_hash(32) + block_hash(32) = 72
const TAIL_BASE: usize = 4 + 4 + 32 + 32;
// + Option::None (0x00) = 73
const TAIL_META_NONE: usize = TAIL_BASE + 1;
// + Option::Some(0x01) + hash(32) = 105
const TAIL_META_SOME: usize = TAIL_BASE + 1 + 32;

/// Decode a Substrate extrinsic signing payload into its constituent fields.
///
/// Takes the raw `payload` bytes from a `NeedsSign` outcome where
/// `request_tag == 36` (sign_payload). Returns the decoded additional-signed
/// fields and the opaque call-data-plus-extra prefix.
///
/// # Errors
///
/// - [`ExtrinsicError::PayloadHashed`] if the payload is exactly 32 bytes
///   (likely a blake2b-256 hash).
/// - [`ExtrinsicError::InvalidLayout`] if the payload is too short or no
///   valid interpretation of the additional-signed tail succeeds.
pub fn decode_sign_payload(payload: &[u8]) -> Result<DecodedSignPayload, ExtrinsicError> {
    let len = payload.len();

    // Detect pre-hashed payloads (Substrate hashes payloads > 256 bytes to 32 bytes).
    if len == 32 {
        return Err(ExtrinsicError::PayloadHashed);
    }

    // Try interpretation 1: CheckMetadataHash with mode=1 (Some(hash)).
    // Tail = 105 bytes. The Option::Some tag byte is at offset len - 33 - 32 - 32 - 4 - 4 = len - 105 + 72.
    if len > TAIL_META_SOME {
        let option_offset = len - TAIL_META_SOME + TAIL_BASE;
        if payload[option_offset] == 0x01 {
            let prefix = &payload[..len - TAIL_META_SOME];
            if !prefix.is_empty() {
                return Ok(decode_tail(payload, prefix, len - TAIL_META_SOME, true));
            }
        }
    }

    // Try interpretation 2: CheckMetadataHash with mode=0 (None).
    // Tail = 73 bytes. The Option::None tag byte is at offset len - 1.
    if len > TAIL_META_NONE {
        let option_offset = len - TAIL_META_NONE + TAIL_BASE;
        if payload[option_offset] == 0x00 {
            let prefix = &payload[..len - TAIL_META_NONE];
            if !prefix.is_empty() {
                return Ok(decode_tail(payload, prefix, len - TAIL_META_NONE, false));
            }
        }
    }

    // Try interpretation 3: No CheckMetadataHash extension (legacy, 72-byte tail).
    if len > TAIL_BASE {
        let prefix = &payload[..len - TAIL_BASE];
        if !prefix.is_empty() {
            let tail_start = len - TAIL_BASE;
            // SAFETY: slices are exactly 4 bytes; bounds guaranteed by `len > TAIL_BASE`.
            let spec_version =
                u32::from_le_bytes(payload[tail_start..tail_start + 4].try_into().unwrap());
            let tx_version =
                u32::from_le_bytes(payload[tail_start + 4..tail_start + 8].try_into().unwrap());
            let mut genesis_hash = [0u8; 32];
            genesis_hash.copy_from_slice(&payload[tail_start + 8..tail_start + 40]);
            let mut block_hash = [0u8; 32];
            block_hash.copy_from_slice(&payload[tail_start + 40..tail_start + 72]);

            return Ok(DecodedSignPayload {
                genesis_hash,
                block_hash,
                spec_version,
                tx_version,
                metadata_hash: None,
                call_data_and_extra: prefix.to_vec(),
            });
        }
    }

    Err(ExtrinsicError::InvalidLayout { actual: len })
}

/// Extract the base additional-signed fields from the tail and optionally
/// the metadata hash.
fn decode_tail(
    payload: &[u8],
    prefix: &[u8],
    tail_start: usize,
    has_metadata_hash: bool,
) -> DecodedSignPayload {
    // SAFETY: slices are exactly 4 bytes; bounds guaranteed by caller's `len > TAIL_*` guard.
    let spec_version = u32::from_le_bytes(payload[tail_start..tail_start + 4].try_into().unwrap());
    let tx_version =
        u32::from_le_bytes(payload[tail_start + 4..tail_start + 8].try_into().unwrap());
    let mut genesis_hash = [0u8; 32];
    genesis_hash.copy_from_slice(&payload[tail_start + 8..tail_start + 40]);
    let mut block_hash = [0u8; 32];
    block_hash.copy_from_slice(&payload[tail_start + 40..tail_start + 72]);

    let metadata_hash = if has_metadata_hash {
        // Option::Some tag is at tail_start + 72, hash starts at tail_start + 73
        let mut h = [0u8; 32];
        h.copy_from_slice(&payload[tail_start + 73..tail_start + 105]);
        Some(h)
    } else {
        None
    };

    DecodedSignPayload {
        genesis_hash,
        block_hash,
        spec_version,
        tx_version,
        metadata_hash,
        call_data_and_extra: prefix.to_vec(),
    }
}

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

    // -- Test vector constants --

    const SPEC: u32 = 1_002_004;
    const TX: u32 = 26;
    const GENESIS: [u8; 32] = [0x91; 32];
    const BLOCK: [u8; 32] = [0xAB; 32];
    const META_HASH: [u8; 32] = [0xCC; 32];
    // Minimal realistic call prefix (5 bytes).
    const PREFIX: &[u8] = &[0x05, 0x03, 0x00, 0x00, 0x00];

    /// Build a synthetic signing payload with CheckMetadataHash mode=0 (None).
    fn make_mode_none(prefix: &[u8]) -> Vec<u8> {
        let mut v = prefix.to_vec();
        v.extend_from_slice(&SPEC.to_le_bytes());
        v.extend_from_slice(&TX.to_le_bytes());
        v.extend_from_slice(&GENESIS);
        v.extend_from_slice(&BLOCK);
        v.push(0x00); // Option::None
        v
    }

    /// Build a synthetic signing payload with CheckMetadataHash mode=1 (Some).
    fn make_mode_some(prefix: &[u8], hash: &[u8; 32]) -> Vec<u8> {
        let mut v = prefix.to_vec();
        v.extend_from_slice(&SPEC.to_le_bytes());
        v.extend_from_slice(&TX.to_le_bytes());
        v.extend_from_slice(&GENESIS);
        v.extend_from_slice(&BLOCK);
        v.push(0x01); // Option::Some
        v.extend_from_slice(hash);
        v
    }

    /// Build a synthetic signing payload without CheckMetadataHash (legacy).
    fn make_legacy(prefix: &[u8]) -> Vec<u8> {
        let mut v = prefix.to_vec();
        v.extend_from_slice(&SPEC.to_le_bytes());
        v.extend_from_slice(&TX.to_le_bytes());
        v.extend_from_slice(&GENESIS);
        v.extend_from_slice(&BLOCK);
        v
    }

    // -----------------------------------------------------------------------
    // Happy paths
    // -----------------------------------------------------------------------

    #[test]
    fn test_decodes_payload_with_metadata_hash_some() {
        let payload = make_mode_some(PREFIX, &META_HASH);
        let decoded = decode_sign_payload(&payload).unwrap();
        assert_eq!(decoded.genesis_hash, GENESIS);
        assert_eq!(decoded.block_hash, BLOCK);
        assert_eq!(decoded.spec_version, SPEC);
        assert_eq!(decoded.tx_version, TX);
        assert_eq!(decoded.metadata_hash, Some(META_HASH));
        assert_eq!(decoded.call_data_and_extra, PREFIX);
    }

    #[test]
    fn test_decodes_payload_with_metadata_hash_none() {
        let payload = make_mode_none(PREFIX);
        let decoded = decode_sign_payload(&payload).unwrap();
        assert_eq!(decoded.genesis_hash, GENESIS);
        assert_eq!(decoded.block_hash, BLOCK);
        assert_eq!(decoded.spec_version, SPEC);
        assert_eq!(decoded.tx_version, TX);
        assert_eq!(decoded.metadata_hash, None);
        assert_eq!(decoded.call_data_and_extra, PREFIX);
    }

    #[test]
    fn test_decodes_payload_without_checkmetadatahash_extension() {
        let payload = make_legacy(PREFIX);
        let decoded = decode_sign_payload(&payload).unwrap();
        assert_eq!(decoded.genesis_hash, GENESIS);
        assert_eq!(decoded.block_hash, BLOCK);
        assert_eq!(decoded.spec_version, SPEC);
        assert_eq!(decoded.tx_version, TX);
        assert_eq!(decoded.metadata_hash, None);
        assert_eq!(decoded.call_data_and_extra, PREFIX);
    }

    #[test]
    fn test_genesis_hash_and_block_hash_are_distinct() {
        let genesis = [0x91; 32];
        let block = [0xAB; 32];
        let mut v = PREFIX.to_vec();
        v.extend_from_slice(&SPEC.to_le_bytes());
        v.extend_from_slice(&TX.to_le_bytes());
        v.extend_from_slice(&genesis);
        v.extend_from_slice(&block);
        v.push(0x00);
        let decoded = decode_sign_payload(&v).unwrap();
        assert_eq!(decoded.genesis_hash, genesis);
        assert_eq!(decoded.block_hash, block);
        assert_ne!(decoded.genesis_hash, decoded.block_hash);
    }

    #[test]
    fn test_spec_and_tx_version_are_little_endian() {
        let payload = make_mode_none(PREFIX);
        let decoded = decode_sign_payload(&payload).unwrap();
        assert_eq!(decoded.spec_version, 1_002_004);
        assert_eq!(decoded.tx_version, 26);
    }

    #[test]
    fn test_decodes_minimum_valid_payload_mode_none() {
        // 1-byte prefix + 73-byte tail = 74 bytes
        let payload = make_mode_none(&[0xFF]);
        assert_eq!(payload.len(), 74);
        let decoded = decode_sign_payload(&payload).unwrap();
        assert_eq!(decoded.call_data_and_extra, vec![0xFF]);
    }

    #[test]
    fn test_decodes_minimum_valid_payload_legacy() {
        // 1-byte prefix + 72-byte tail = 73 bytes
        let payload = make_legacy(&[0xFF]);
        assert_eq!(payload.len(), 73);
        let decoded = decode_sign_payload(&payload).unwrap();
        assert_eq!(decoded.call_data_and_extra, vec![0xFF]);
    }

    #[test]
    fn test_call_data_and_extra_is_exact_prefix() {
        let prefix = vec![0x01, 0x02, 0x03, 0x04, 0x05];
        let payload = make_mode_none(&prefix);
        let decoded = decode_sign_payload(&payload).unwrap();
        assert_eq!(decoded.call_data_and_extra, prefix);
    }

    #[test]
    fn test_decodes_payload_with_large_call_data() {
        let prefix = vec![0xAA; 300];
        let payload = make_mode_none(&prefix);
        assert!(payload.len() > 256);
        let decoded = decode_sign_payload(&payload).unwrap();
        assert_eq!(decoded.call_data_and_extra.len(), 300);
        assert_eq!(decoded.genesis_hash, GENESIS);
    }

    #[test]
    fn test_prefers_metadata_hash_some_over_none_when_ambiguous() {
        // Build a mode=1 payload. The decoder should match mode=1 first
        // and not fall through to mode=0 or legacy.
        let payload = make_mode_some(PREFIX, &META_HASH);
        let decoded = decode_sign_payload(&payload).unwrap();
        assert_eq!(decoded.metadata_hash, Some(META_HASH));
    }

    #[test]
    fn test_heuristic_limitation_mode_none_with_spec_version_lsb_0x01() {
        // Documented heuristic limitation: if a mode-None payload has a
        // spec_version whose LSB is 0x01, the decoder may misclassify it as
        // mode-Some because the 0x01 byte at the option_offset position looks
        // like an Option::Some tag. We construct such a payload and verify
        // the decoder still returns a valid result (even if the interpretation
        // differs from the "true" layout). The important thing is that it does
        // not error — callers get a best-effort decode either way.
        let spec_with_lsb_01: u32 = 0x00_00_01_01; // LSB = 0x01
        let mut v = vec![0x05; 34]; // 34-byte prefix to hit the ambiguity window
        v.extend_from_slice(&spec_with_lsb_01.to_le_bytes());
        v.extend_from_slice(&TX.to_le_bytes());
        v.extend_from_slice(&GENESIS);
        v.extend_from_slice(&BLOCK);
        v.push(0x00); // Option::None
        let result = decode_sign_payload(&v);
        // The decoder should not error — it produces a valid (possibly
        // mode-Some) interpretation rather than failing.
        assert!(
            result.is_ok(),
            "heuristic edge case must not error: {result:?}"
        );
    }

    // -----------------------------------------------------------------------
    // Error paths — every ExtrinsicError variant exercised
    // -----------------------------------------------------------------------

    #[test]
    fn test_rejects_empty_payload() {
        let result = decode_sign_payload(&[]);
        assert_eq!(result, Err(ExtrinsicError::InvalidLayout { actual: 0 }));
    }

    #[test]
    fn test_rejects_payload_too_short() {
        let result = decode_sign_payload(&[0u8; 71]);
        assert_eq!(result, Err(ExtrinsicError::InvalidLayout { actual: 71 }));
    }

    #[test]
    fn test_rejects_hashed_payload() {
        let result = decode_sign_payload(&[0xAA; 32]);
        assert_eq!(result, Err(ExtrinsicError::PayloadHashed));
    }

    #[test]
    fn test_rejects_payload_with_empty_prefix() {
        // Exactly 72 bytes (TAIL_BASE) — the legacy tail fills the entire
        // payload, leaving an empty prefix. All interpretations fail because
        // we require at least 1 byte of call data.
        let result = decode_sign_payload(&[0u8; 72]);
        assert_eq!(result, Err(ExtrinsicError::InvalidLayout { actual: 72 }));
    }

    // -----------------------------------------------------------------------
    // Pinned regression vectors
    // -----------------------------------------------------------------------

    #[test]
    fn test_golden_polkadot_like_payload_mode_none() {
        let payload = make_mode_none(PREFIX);
        let decoded = decode_sign_payload(&payload).unwrap();
        // Pin every field to exact expected values.
        assert_eq!(decoded.spec_version, 1_002_004);
        assert_eq!(decoded.tx_version, 26);
        assert_eq!(decoded.genesis_hash, [0x91; 32]);
        assert_eq!(decoded.block_hash, [0xAB; 32]);
        assert_eq!(decoded.metadata_hash, None);
        assert_eq!(
            decoded.call_data_and_extra,
            vec![0x05, 0x03, 0x00, 0x00, 0x00]
        );
    }

    #[test]
    fn test_golden_polkadot_like_payload_mode_some() {
        let payload = make_mode_some(PREFIX, &META_HASH);
        let decoded = decode_sign_payload(&payload).unwrap();
        assert_eq!(decoded.spec_version, 1_002_004);
        assert_eq!(decoded.tx_version, 26);
        assert_eq!(decoded.genesis_hash, [0x91; 32]);
        assert_eq!(decoded.block_hash, [0xAB; 32]);
        assert_eq!(decoded.metadata_hash, Some([0xCC; 32]));
        assert_eq!(
            decoded.call_data_and_extra,
            vec![0x05, 0x03, 0x00, 0x00, 0x00]
        );
    }

    #[test]
    fn test_golden_legacy_payload() {
        let payload = make_legacy(&[0xFF]);
        let decoded = decode_sign_payload(&payload).unwrap();
        assert_eq!(decoded.spec_version, SPEC);
        assert_eq!(decoded.tx_version, TX);
        assert_eq!(decoded.genesis_hash, GENESIS);
        assert_eq!(decoded.block_hash, BLOCK);
        assert_eq!(decoded.metadata_hash, None);
        assert_eq!(decoded.call_data_and_extra, vec![0xFF]);
    }

    #[test]
    fn test_metadata_hash_all_zeros_is_some() {
        // A metadata hash of all-zeros must be decoded as Some([0x00;32]),
        // not confused with Option::None.
        let zero_hash = [0x00u8; 32];
        let payload = make_mode_some(PREFIX, &zero_hash);
        let decoded = decode_sign_payload(&payload).unwrap();
        assert_eq!(decoded.metadata_hash, Some(zero_hash));
    }
}