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
// Copyright 2019-2024 Parity Technologies (UK) Ltd.
// This file is dual-licensed as Apache-2.0 or GPL-3.0.
// see LICENSE for license details.

//! Construct addresses to access custom values with.

use crate::dynamic::DecodedValueThunk;
use crate::metadata::DecodeWithMetadata;
use derive_where::derive_where;

/// Use this with [`Address::IsDecodable`].
pub use crate::utils::Yes;

/// This represents the address of a custom value in in the metadata.
/// Anything that implements it can be used to fetch custom values from the metadata.
/// The trait is implemented by [`str`] for dynamic lookup and [`StaticAddress`] for static queries.
pub trait Address {
    /// The type of the custom value.
    type Target: DecodeWithMetadata;
    /// Should be set to `Yes` for Dynamic values and static values that have a valid type.
    /// Should be `()` for custom values, that have an invalid type id.
    type IsDecodable;

    /// the name (key) by which the custom value can be accessed in the metadata.
    fn name(&self) -> &str;

    /// An optional hash which, if present, can be checked against node metadata.
    fn validation_hash(&self) -> Option<[u8; 32]> {
        None
    }
}

impl Address for str {
    type Target = DecodedValueThunk;
    type IsDecodable = Yes;

    fn name(&self) -> &str {
        self
    }
}

/// A static address to a custom value.
#[derive_where(Clone, Debug, PartialOrd, Ord, PartialEq, Eq)]
pub struct StaticAddress<ReturnTy, IsDecodable> {
    name: &'static str,
    hash: Option<[u8; 32]>,
    phantom: core::marker::PhantomData<(ReturnTy, IsDecodable)>,
}

impl<ReturnTy, IsDecodable> StaticAddress<ReturnTy, IsDecodable> {
    #[doc(hidden)]
    /// Creates a new StaticAddress.
    pub fn new_static(name: &'static str, hash: [u8; 32]) -> StaticAddress<ReturnTy, IsDecodable> {
        StaticAddress::<ReturnTy, IsDecodable> {
            name,
            hash: Some(hash),
            phantom: core::marker::PhantomData,
        }
    }

    /// Do not validate this custom value prior to accessing it.
    pub fn unvalidated(self) -> Self {
        Self {
            name: self.name,
            hash: None,
            phantom: self.phantom,
        }
    }
}

impl<R: DecodeWithMetadata, Y> Address for StaticAddress<R, Y> {
    type Target = R;
    type IsDecodable = Y;

    fn name(&self) -> &str {
        self.name
    }

    fn validation_hash(&self) -> Option<[u8; 32]> {
        self.hash
    }
}