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
// Copyright 2023 Axiom-Team
//
// This file is part of Duniter-v2S.
//
// Duniter-v2S is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, version 3 of the License.
//
// Duniter-v2S is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with Duniter-v2S. If not, see <https://www.gnu.org/licenses/>.

#![allow(clippy::type_complexity)]

use crate::runtime;
use log::debug;

use sp_core::H256;

pub type Client = subxt::OnlineClient<crate::RuntimeConfig>;
pub type AccountId = subxt::utils::AccountId32;
pub type IdtyIndex = u32;

pub async fn client(rpc_url: String) -> Client {
    Client::from_insecure_url(rpc_url)
        .await
        .expect("Cannot create RPC client")
}

pub async fn parent_hash(client: &Client) -> H256 {
    client
        .blocks()
        .at_latest()
        .await
        .expect("Cannot fetch latest block hash")
        .hash()
}

pub async fn current_pool_index(client: &Client, parent_hash: H256) -> u32 {
    client
        .storage()
        .at(parent_hash)
        .fetch(&runtime::storage().distance().current_pool_index())
        .await
        .expect("Cannot fetch current pool index")
        .unwrap_or_default()
}

pub async fn current_pool(
    client: &Client,
    parent_hash: H256,
    current_pool_index: u32,
) -> Option<runtime::runtime_types::pallet_distance::types::EvaluationPool<AccountId, IdtyIndex>> {
    client
        .storage()
        .at(parent_hash)
        .fetch(&match current_pool_index {
            0 => {
                debug!("Looking at Pool1 for pool index {}", current_pool_index);
                runtime::storage().distance().evaluation_pool1()
            }
            1 => {
                debug!("Looking at Pool2 for pool index {}", current_pool_index);
                runtime::storage().distance().evaluation_pool2()
            }
            2 => {
                debug!("Looking at Pool0 for pool index {}", current_pool_index);
                runtime::storage().distance().evaluation_pool0()
            }
            _ => unreachable!("n<3"),
        })
        .await
        .expect("Cannot fetch current pool")
}

pub async fn evaluation_block(client: &Client, parent_hash: H256) -> H256 {
    client
        .storage()
        .at(parent_hash)
        .fetch(&runtime::storage().distance().evaluation_block())
        .await
        .expect("Cannot fetch evaluation block")
        .expect("No evaluation block")
}

pub async fn max_referee_distance(client: &Client) -> u32 {
    client
        .constants()
        .at(&runtime::constants().distance().max_referee_distance())
        .expect("Cannot fetch referee distance")
}

pub async fn member_iter(client: &Client, evaluation_block: H256) -> MemberIter {
    MemberIter(
        client
            .storage()
            .at(evaluation_block)
            .iter(runtime::storage().membership().membership_iter())
            .await
            .expect("Cannot fetch memberships"),
    )
}

pub struct MemberIter(
    subxt::backend::StreamOfResults<
        subxt::storage::StorageKeyValuePair<
            subxt::storage::Address<
                (),
                runtime::runtime_types::sp_membership::MembershipData<u32>,
                (),
                (),
                subxt::storage::address::Yes,
            >,
        >,
    >,
);

impl MemberIter {
    pub async fn next(&mut self) -> Result<Option<IdtyIndex>, subxt::error::Error> {
        self.0
            .next()
            .await
            .transpose()
            .map(|i| i.map(|j| idty_id_from_storage_key(&j.key_bytes)))
    }
}

pub async fn cert_iter(client: &Client, evaluation_block: H256) -> CertIter {
    CertIter(
        client
            .storage()
            .at(evaluation_block)
            .iter(runtime::storage().certification().certs_by_receiver_iter())
            .await
            .expect("Cannot fetch certifications"),
    )
}

pub struct CertIter(
    subxt::backend::StreamOfResults<
        subxt::storage::StorageKeyValuePair<
            subxt::storage::Address<
                (),
                Vec<(u32, u32)>,
                (),
                subxt::storage::address::Yes,
                subxt::storage::address::Yes,
            >,
        >,
    >,
);

impl CertIter {
    pub async fn next(
        &mut self,
    ) -> Result<Option<(IdtyIndex, Vec<(IdtyIndex, u32)>)>, subxt::error::Error> {
        self.0
            .next()
            .await
            .transpose()
            .map(|i| i.map(|j| (idty_id_from_storage_key(&j.key_bytes), j.value)))
    }
}

fn idty_id_from_storage_key(storage_key: &[u8]) -> IdtyIndex {
    u32::from_le_bytes(
        storage_key[40..44]
            .try_into()
            .expect("Cannot convert StorageKey to IdtyIndex"),
    )
}