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
// Copyright (C) 2022-2023 Parity Technologies (UK) Ltd. (admin@parity.io)
// This file is a part of the scale-value 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::TypeId;
use crate::prelude::*;
use crate::value_type::{Composite, Primitive, Value, ValueDef, Variant};
use scale_decode::FieldIter;
use scale_info::{form::PortableForm, Path, PortableRegistry};

// This is emitted if something goes wrong decoding into a Value.
pub use scale_decode::visitor::DecodeError;

/// Decode data according to the [`TypeId`] provided.
/// The provided pointer to the data slice will be moved forwards as needed
/// depending on what was decoded.
pub fn decode_value_as_type(
    data: &mut &[u8],
    ty_id: TypeId,
    types: &PortableRegistry,
) -> Result<Value<TypeId>, DecodeError> {
    scale_decode::visitor::decode_with_visitor(data, ty_id, types, DecodeValueVisitor)
}

// Sequences, Tuples and Arrays all have the same methods, so decode them in the same way:
macro_rules! to_unnamed_composite {
    ($value:ident, $type_id:ident) => {{
        let mut vals = Vec::with_capacity($value.remaining());
        while let Some(val) = $value.decode_item(DecodeValueVisitor) {
            let val = val?;
            vals.push(val);
        }
        Ok(Value { value: ValueDef::Composite(Composite::Unnamed(vals)), context: $type_id.0 })
    }};
}

// We can't implement this on `Value<TypeId>` because we have no TypeId to assign to the value.
impl scale_decode::DecodeAsFields for Composite<TypeId> {
    fn decode_as_fields<'info>(
        input: &mut &[u8],
        fields: &mut dyn FieldIter<'info>,
        types: &'info PortableRegistry,
    ) -> Result<Self, scale_decode::Error> {
        // Build a Composite type to pass to a one-off visitor:
        static EMPTY_PATH: &Path<PortableForm> = &Path { segments: Vec::new() };
        let mut composite =
            scale_decode::visitor::types::Composite::new(input, EMPTY_PATH, fields, types, false);
        // Decode into a Composite value from this:
        let val = visit_composite(&mut composite);
        // Consume remaining bytes and update input cursor:
        composite.skip_decoding()?;
        *input = composite.bytes_from_undecoded();

        val.map_err(From::from)
    }
}

/// A [`scale_decode::Visitor`] implementation for decoding into [`Value`]s.
pub struct DecodeValueVisitor;

impl scale_decode::IntoVisitor for Value<TypeId> {
    type Visitor = scale_decode::visitor::VisitorWithCrateError<DecodeValueVisitor>;
    fn into_visitor() -> Self::Visitor {
        scale_decode::visitor::VisitorWithCrateError(DecodeValueVisitor)
    }
}

impl scale_decode::visitor::Visitor for DecodeValueVisitor {
    type Value<'scale, 'info> = Value<TypeId>;
    type Error = DecodeError;

    fn visit_bool<'scale, 'info>(
        self,
        value: bool,
        type_id: scale_decode::visitor::TypeId,
    ) -> Result<Self::Value<'scale, 'info>, Self::Error> {
        Ok(Value::bool(value).map_context(|_| type_id.0))
    }
    fn visit_char<'scale, 'info>(
        self,
        value: char,
        type_id: scale_decode::visitor::TypeId,
    ) -> Result<Self::Value<'scale, 'info>, Self::Error> {
        Ok(Value::char(value).map_context(|_| type_id.0))
    }
    fn visit_u8<'scale, 'info>(
        self,
        value: u8,
        type_id: scale_decode::visitor::TypeId,
    ) -> Result<Self::Value<'scale, 'info>, Self::Error> {
        self.visit_u128(value as u128, type_id)
    }
    fn visit_u16<'scale, 'info>(
        self,
        value: u16,
        type_id: scale_decode::visitor::TypeId,
    ) -> Result<Self::Value<'scale, 'info>, Self::Error> {
        self.visit_u128(value as u128, type_id)
    }
    fn visit_u32<'scale, 'info>(
        self,
        value: u32,
        type_id: scale_decode::visitor::TypeId,
    ) -> Result<Self::Value<'scale, 'info>, Self::Error> {
        self.visit_u128(value as u128, type_id)
    }
    fn visit_u64<'scale, 'info>(
        self,
        value: u64,
        type_id: scale_decode::visitor::TypeId,
    ) -> Result<Self::Value<'scale, 'info>, Self::Error> {
        self.visit_u128(value as u128, type_id)
    }
    fn visit_u128<'scale, 'info>(
        self,
        value: u128,
        type_id: scale_decode::visitor::TypeId,
    ) -> Result<Self::Value<'scale, 'info>, Self::Error> {
        Ok(Value::u128(value).map_context(|_| type_id.0))
    }
    fn visit_u256<'info>(
        self,
        value: &'_ [u8; 32],
        type_id: scale_decode::visitor::TypeId,
    ) -> Result<Self::Value<'_, 'info>, Self::Error> {
        Ok(Value { value: ValueDef::Primitive(Primitive::U256(*value)), context: type_id.0 })
    }
    fn visit_i8<'scale, 'info>(
        self,
        value: i8,
        type_id: scale_decode::visitor::TypeId,
    ) -> Result<Self::Value<'scale, 'info>, Self::Error> {
        self.visit_i128(value as i128, type_id)
    }
    fn visit_i16<'scale, 'info>(
        self,
        value: i16,
        type_id: scale_decode::visitor::TypeId,
    ) -> Result<Self::Value<'scale, 'info>, Self::Error> {
        self.visit_i128(value as i128, type_id)
    }
    fn visit_i32<'scale, 'info>(
        self,
        value: i32,
        type_id: scale_decode::visitor::TypeId,
    ) -> Result<Self::Value<'scale, 'info>, Self::Error> {
        self.visit_i128(value as i128, type_id)
    }
    fn visit_i64<'scale, 'info>(
        self,
        value: i64,
        type_id: scale_decode::visitor::TypeId,
    ) -> Result<Self::Value<'scale, 'info>, Self::Error> {
        self.visit_i128(value as i128, type_id)
    }
    fn visit_i128<'scale, 'info>(
        self,
        value: i128,
        type_id: scale_decode::visitor::TypeId,
    ) -> Result<Self::Value<'scale, 'info>, Self::Error> {
        Ok(Value::i128(value).map_context(|_| type_id.0))
    }
    fn visit_i256<'info>(
        self,
        value: &'_ [u8; 32],
        type_id: scale_decode::visitor::TypeId,
    ) -> Result<Self::Value<'_, 'info>, Self::Error> {
        Ok(Value { value: ValueDef::Primitive(Primitive::U256(*value)), context: type_id.0 })
    }
    fn visit_sequence<'scale, 'info>(
        self,
        value: &mut scale_decode::visitor::types::Sequence<'scale, 'info>,
        type_id: scale_decode::visitor::TypeId,
    ) -> Result<Self::Value<'scale, 'info>, Self::Error> {
        to_unnamed_composite!(value, type_id)
    }
    fn visit_tuple<'scale, 'info>(
        self,
        value: &mut scale_decode::visitor::types::Tuple<'scale, 'info>,
        type_id: scale_decode::visitor::TypeId,
    ) -> Result<Self::Value<'scale, 'info>, Self::Error> {
        to_unnamed_composite!(value, type_id)
    }
    fn visit_array<'scale, 'info>(
        self,
        value: &mut scale_decode::visitor::types::Array<'scale, 'info>,
        type_id: scale_decode::visitor::TypeId,
    ) -> Result<Self::Value<'scale, 'info>, Self::Error> {
        to_unnamed_composite!(value, type_id)
    }
    fn visit_bitsequence<'scale, 'info>(
        self,
        value: &mut scale_decode::visitor::types::BitSequence<'scale>,
        type_id: scale_decode::visitor::TypeId,
    ) -> Result<Self::Value<'scale, 'info>, Self::Error> {
        let bits: Result<_, _> = value.decode()?.collect();
        Ok(Value { value: ValueDef::BitSequence(bits?), context: type_id.0 })
    }
    fn visit_str<'scale, 'info>(
        self,
        value: &mut scale_decode::visitor::types::Str<'scale>,
        type_id: scale_decode::visitor::TypeId,
    ) -> Result<Self::Value<'scale, 'info>, Self::Error> {
        Ok(Value::string(value.as_str()?).map_context(|_| type_id.0))
    }
    fn visit_variant<'scale, 'info>(
        self,
        value: &mut scale_decode::visitor::types::Variant<'scale, 'info>,
        type_id: scale_decode::visitor::TypeId,
    ) -> Result<Self::Value<'scale, 'info>, Self::Error> {
        let values = visit_composite(value.fields())?;
        Ok(Value {
            value: ValueDef::Variant(Variant { name: value.name().to_owned(), values }),
            context: type_id.0,
        })
    }
    fn visit_composite<'scale, 'info>(
        self,
        value: &mut scale_decode::visitor::types::Composite<'scale, 'info>,
        type_id: scale_decode::visitor::TypeId,
    ) -> Result<Self::Value<'scale, 'info>, Self::Error> {
        Ok(Value { value: ValueDef::Composite(visit_composite(value)?), context: type_id.0 })
    }
}

/// Extract a named/unnamed Composite type out of scale_decode's Composite.
fn visit_composite(
    value: &mut scale_decode::visitor::types::Composite<'_, '_>,
) -> Result<Composite<TypeId>, DecodeError> {
    let len = value.remaining();
    // if no fields, we'll always assume unnamed.
    let named = len > 0 && !value.has_unnamed_fields();

    if named {
        let mut vals = Vec::with_capacity(len);
        let mut name = value.peek_name();
        while let Some(v) = value.decode_item(DecodeValueVisitor) {
            let v = v?;
            vals.push((name.expect("all fields should be named; we have checked").to_owned(), v));
            // get the next field name now we've decoded one.
            name = value.peek_name();
        }
        Ok(Composite::Named(vals))
    } else {
        let mut vals = Vec::with_capacity(len);
        while let Some(v) = value.decode_item(DecodeValueVisitor) {
            let v = v?;
            vals.push(v);
        }
        Ok(Composite::Unnamed(vals))
    }
}

#[cfg(test)]
mod test {

    use crate::value;

    use super::*;
    use codec::{Compact, Encode};

    /// Given a type definition, return the PortableType and PortableRegistry
    /// that our decode functions expect.
    fn make_type<T: scale_info::TypeInfo + 'static>() -> (TypeId, PortableRegistry) {
        let m = scale_info::MetaType::new::<T>();
        let mut types = scale_info::Registry::new();
        let id = types.register_type(&m);
        let portable_registry: PortableRegistry = types.into();

        (id.id, portable_registry)
    }

    /// Given a value to encode, and a representation of the decoded value, check that our decode functions
    /// successfully decodes the type to the expected value, based on the implicit SCALE type info that the type
    /// carries
    fn encode_decode_check<T: Encode + scale_info::TypeInfo + 'static>(val: T, exp: Value<()>) {
        encode_decode_check_explicit_info::<T, _>(val, exp)
    }

    /// Given a value to encode, a type to decode it back into, and a representation of
    /// the decoded value, check that our decode functions successfully decodes as expected.
    fn encode_decode_check_explicit_info<Ty: scale_info::TypeInfo + 'static, T: Encode>(
        val: T,
        ex: Value<()>,
    ) {
        let encoded = val.encode();
        let encoded = &mut &*encoded;

        let (id, portable_registry) = make_type::<Ty>();

        // Can we decode?
        let val = decode_value_as_type(encoded, id, &portable_registry).expect("decoding failed");
        // Is the decoded value what we expected?
        assert_eq!(val.remove_context(), ex, "decoded value does not look like what we expected");
        // Did decoding consume all of the encoded bytes, as expected?
        assert_eq!(encoded.len(), 0, "decoding did not consume all of the encoded bytes");
    }

    #[test]
    fn decode_primitives() {
        encode_decode_check(true, Value::bool(true));
        encode_decode_check(false, Value::bool(false));
        encode_decode_check_explicit_info::<char, _>('a' as u32, Value::char('a'));
        encode_decode_check("hello", Value::string("hello"));
        encode_decode_check(
            "hello".to_string(), // String or &str (above) decode OK
            Value::string("hello"),
        );
        encode_decode_check(123u8, Value::u128(123));
        encode_decode_check(123u16, Value::u128(123));
        encode_decode_check(123u32, Value::u128(123));
        encode_decode_check(123u64, Value::u128(123));
        encode_decode_check(123u128, Value::u128(123));
        //// Todo [jsdw]: Can we test this if we need a TypeInfo param?:
        // encode_decode_check_explicit_info(
        //     [123u8; 32], // Anything 32 bytes long will do here
        //     Value::u256([123u8; 32]),
        // );
        encode_decode_check(123i8, Value::i128(123));
        encode_decode_check(123i16, Value::i128(123));
        encode_decode_check(123i32, Value::i128(123));
        encode_decode_check(123i64, Value::i128(123));
        encode_decode_check(123i128, Value::i128(123));
        //// Todo [jsdw]: Can we test this if we need a TypeInfo param?:
        // encode_decode_check_explicit_info(
        //     [123u8; 32], // Anything 32 bytes long will do here
        //     Value::i256([123u8; 32]),
        // );
    }

    #[test]
    fn decode_compact_primitives() {
        encode_decode_check(Compact(123u8), Value::u128(123));
        encode_decode_check(Compact(123u16), Value::u128(123));
        encode_decode_check(Compact(123u32), Value::u128(123));
        encode_decode_check(Compact(123u64), Value::u128(123));
        encode_decode_check(Compact(123u128), Value::u128(123));
    }

    #[test]
    fn decode_compact_named_wrapper_struct() {
        // A struct that can be compact encoded:
        #[derive(Encode, scale_info::TypeInfo)]
        struct MyWrapper {
            inner: u32,
        }
        impl From<Compact<MyWrapper>> for MyWrapper {
            fn from(val: Compact<MyWrapper>) -> MyWrapper {
                val.0
            }
        }
        impl codec::CompactAs for MyWrapper {
            type As = u32;

            fn encode_as(&self) -> &Self::As {
                &self.inner
            }
            fn decode_from(inner: Self::As) -> Result<Self, codec::Error> {
                Ok(MyWrapper { inner })
            }
        }

        encode_decode_check(
            Compact(MyWrapper { inner: 123 }),
            Value::named_composite(vec![("inner", Value::u128(123))]),
        );
    }

    #[test]
    fn decode_compact_unnamed_wrapper_struct() {
        // A struct that can be compact encoded:
        #[derive(Encode, scale_info::TypeInfo)]
        struct MyWrapper(u32);
        impl From<Compact<MyWrapper>> for MyWrapper {
            fn from(val: Compact<MyWrapper>) -> MyWrapper {
                val.0
            }
        }
        impl codec::CompactAs for MyWrapper {
            type As = u32;

            // Node the requirement to return something with a lifetime tied
            // to self here. This means that we can't implement this for things
            // more complex than wrapper structs (eg `Foo(u32,u32,u32,u32)`) without
            // shenanigans, meaning that (hopefully) supporting wrapper struct
            // decoding and nothing fancier is sufficient.
            fn encode_as(&self) -> &Self::As {
                &self.0
            }
            fn decode_from(inner: Self::As) -> Result<Self, codec::Error> {
                Ok(MyWrapper(inner))
            }
        }

        encode_decode_check(
            Compact(MyWrapper(123)),
            Value::unnamed_composite(vec![Value::u128(123)]),
        );
    }

    #[test]
    fn decode_sequence_array_tuple_types() {
        encode_decode_check(vec![1i32, 2, 3], value!((1, 2, 3)));
        encode_decode_check(
            [1i32, 2, 3], // compile-time length known
            Value::unnamed_composite(vec![Value::i128(1), Value::i128(2), Value::i128(3)]),
        );
        encode_decode_check(
            (1i32, true, 123456u128),
            Value::unnamed_composite(vec![Value::i128(1), Value::bool(true), Value::u128(123456)]),
        );
    }

    #[test]
    fn decode_variant_types() {
        #[derive(Encode, scale_info::TypeInfo)]
        enum MyEnum {
            Foo(bool),
            Bar { hi: String, other: u128 },
        }

        encode_decode_check(
            MyEnum::Foo(true),
            Value::unnamed_variant("Foo", vec![Value::bool(true)]),
        );
        encode_decode_check(
            MyEnum::Bar { hi: "hello".to_string(), other: 123 },
            value!(Bar { hi: "hello", other: 123u32 }),
        );
    }

    #[test]
    fn decode_composite_types() {
        #[derive(Encode, scale_info::TypeInfo)]
        struct Unnamed(bool, String, Vec<u8>);

        #[derive(Encode, scale_info::TypeInfo)]
        struct Named {
            is_valid: bool,
            name: String,
            bytes: Vec<u8>,
        }

        encode_decode_check(
            Unnamed(true, "James".into(), vec![1, 2, 3]),
            value!((true, "James", (1u8, 2u8, 3u8))),
        );
        encode_decode_check(
            Named { is_valid: true, name: "James".into(), bytes: vec![1, 2, 3] },
            value!({is_valid: true, name: "James", bytes: (1u8, 2u8, 3u8)}),
        );
    }

    #[test]
    fn decoding_zero_length_composites_always_unnamed() {
        // The scale-info repr is just a composite, so we don't really track
        // whether the thing was named or not. either Value will convert back ok anyway.
        #[derive(Encode, scale_info::TypeInfo)]
        struct Named {}
        #[derive(Encode, scale_info::TypeInfo)]
        struct Unnamed();

        encode_decode_check(Unnamed(), Value::unnamed_composite(vec![]));
        encode_decode_check(Named {}, Value::unnamed_composite(vec![]));
    }

    #[test]
    fn decode_bit_sequence() {
        use scale_bits::bits;

        // scale-decode already tests this more thoroughly:
        encode_decode_check(bits![0, 1, 1, 0, 1, 0], Value::bit_sequence(bits![0, 1, 1, 0, 1, 0]));
    }

    #[test]
    fn decode_composite_fields() {
        use codec::Encode;
        use scale_decode::DecodeAsFields;

        #[derive(Encode, scale_decode::DecodeAsType, scale_info::TypeInfo)]
        struct Foo {
            a: String,
            b: bool,
            c: u16,
        }

        // Get the fields we want to decode:
        let (id, types) = make_type::<Foo>();
        let scale_info::TypeDef::Composite(c) = &types.resolve(id).unwrap().type_def else {
            panic!("Couldn't get fields");
        };
        let mut fields =
            c.fields.iter().map(|f| scale_decode::Field::new(f.ty.id, f.name.as_deref()));

        // get some bytes to decode from:
        let foo = Foo { a: "Hello".to_owned(), b: true, c: 123 };
        let foo_bytes = foo.encode();
        let foo_bytes_cursor = &mut &*foo_bytes;

        // Decode and check that things line up:
        let out = Composite::decode_as_fields(foo_bytes_cursor, &mut fields, &types)
            .expect("can decode as fields")
            .map_context(|_| ());
        assert_eq!(
            out,
            Composite::named([
                ("a", Value::string("Hello")),
                ("b", Value::bool(true)),
                ("c", Value::u128(123))
            ])
        );
        assert_eq!(foo_bytes_cursor.len(), 0, "all bytes should have been consumed");
    }
}