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
// Copyright 2021 IOTA Stiftung
// SPDX-License-Identifier: Apache-2.0

use std::ops::Range;

use bee_block::address::Address;
use serde::Deserialize;

use crate::{
    api::types::{Bech32Addresses, RawAddresses},
    constants::{SHIMMER_COIN_TYPE, SHIMMER_TESTNET_BECH32_HRP},
    secret::{GenerateAddressMetadata, SecretManage, SecretManager},
    Client, Result,
};

/// Builder of get_addresses API
#[must_use]
pub struct GetAddressesBuilder<'a> {
    client: Option<&'a Client>,
    secret_manager: &'a SecretManager,
    coin_type: u32,
    account_index: u32,
    range: Range<u32>,
    internal: bool,
    bech32_hrp: Option<String>,
    metadata: GenerateAddressMetadata,
}

/// Get address builder from string
#[derive(Clone, Debug, Default, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct GetAddressesBuilderOptions {
    /// Coin type
    pub coin_type: Option<u32>,
    /// Account index
    pub account_index: Option<u32>,
    /// Range
    pub range: Option<Range<u32>>,
    /// Internal addresses
    pub internal: Option<bool>,
    /// Bech32 human readable part
    pub bech32_hrp: Option<String>,
    /// Metadata
    pub metadata: Option<GenerateAddressMetadata>,
}

impl<'a> GetAddressesBuilder<'a> {
    /// Create get_addresses builder
    pub fn new(manager: &'a SecretManager) -> Self {
        Self {
            client: None,
            secret_manager: manager,
            coin_type: SHIMMER_COIN_TYPE,
            account_index: 0,
            range: 0..super::ADDRESS_GAP_RANGE,
            internal: false,
            bech32_hrp: None,
            metadata: GenerateAddressMetadata { syncing: true },
        }
    }

    /// Provide a client to get the bech32_hrp from the node
    pub fn with_client(mut self, client: &'a Client) -> Self {
        self.client.replace(client);
        self
    }

    /// Set the coin type
    pub fn with_coin_type(mut self, coin_type: u32) -> Self {
        self.coin_type = coin_type;
        self
    }

    /// Set the account index
    pub fn with_account_index(mut self, account_index: u32) -> Self {
        self.account_index = account_index;
        self
    }

    /// Set range to the builder
    pub fn with_range(mut self, range: Range<u32>) -> Self {
        self.range = range;
        self
    }

    /// Set if internal or public addresses should be generated
    pub fn with_internal_addresses(mut self, internal: bool) -> Self {
        self.internal = internal;
        self
    }

    /// Set bech32 human readable part (hrp)
    pub fn with_bech32_hrp<T: Into<String>>(mut self, bech32_hrp: T) -> Self {
        self.bech32_hrp.replace(bech32_hrp.into());
        self
    }

    /// Set the metadata for the address generation (used for ledger to display addresses or not)
    pub fn with_generate_metadata(mut self, metadata: GenerateAddressMetadata) -> Self {
        self.metadata = metadata;
        self
    }

    /// Set multiple options from address builder options type
    /// Useful for bindings
    pub fn set_options(mut self, options: GetAddressesBuilderOptions) -> Result<Self> {
        if let Some(coin_type) = options.coin_type {
            self = self.with_coin_type(coin_type);
        };

        if let Some(account_index) = options.account_index {
            self = self.with_account_index(account_index);
        }

        if let Some(range) = options.range {
            self = self.with_range(range);
        };

        if let Some(internal) = options.internal {
            self = self.with_internal_addresses(internal);
        };

        if let Some(bech32_hrp) = options.bech32_hrp {
            self = self.with_bech32_hrp(bech32_hrp);
        };

        Ok(self)
    }

    /// Consume the builder and get a vector of public addresses bech32 encoded
    pub async fn finish(self) -> Result<Vec<String>> {
        let bech32_hrp = match self.bech32_hrp.clone() {
            Some(bech32_hrp) => bech32_hrp,
            None => match self.client {
                Some(client) => client.get_bech32_hrp()?,
                None => SHIMMER_TESTNET_BECH32_HRP.to_string(),
            },
        };

        let addresses = self
            .secret_manager
            .generate_addresses(
                self.coin_type,
                self.account_index,
                self.range,
                self.internal,
                self.metadata.clone(),
            )
            .await?
            .into_iter()
            .map(|a| a.to_bech32(&bech32_hrp))
            .collect();

        Ok(addresses)
    }
    /// Consume the builder and get a vector of public addresses
    pub async fn get_raw(self) -> Result<Vec<Address>> {
        self.secret_manager
            .generate_addresses(
                self.coin_type,
                self.account_index,
                self.range,
                false,
                self.metadata.clone(),
            )
            .await
    }

    /// Consume the builder and get the vector of public and internal addresses bech32 encoded
    pub async fn get_all(self) -> Result<Bech32Addresses> {
        let bech32_hrp = match self.bech32_hrp.clone() {
            Some(bech32_hrp) => bech32_hrp,
            None => match self.client {
                Some(client) => client.get_bech32_hrp()?,
                None => SHIMMER_TESTNET_BECH32_HRP.to_string(),
            },
        };
        let addresses = self.get_all_raw().await?;

        Ok(Bech32Addresses {
            public: addresses.public.into_iter().map(|a| a.to_bech32(&bech32_hrp)).collect(),
            internal: addresses
                .internal
                .into_iter()
                .map(|a| a.to_bech32(&bech32_hrp))
                .collect(),
        })
    }

    /// Consume the builder and get the vector of public and internal addresses
    pub async fn get_all_raw(self) -> Result<RawAddresses> {
        let public_addresses = self
            .secret_manager
            .generate_addresses(
                self.coin_type,
                self.account_index,
                self.range.clone(),
                false,
                self.metadata.clone(),
            )
            .await?;

        let internal_addresses = self
            .secret_manager
            .generate_addresses(
                self.coin_type,
                self.account_index,
                self.range,
                true,
                self.metadata.clone(),
            )
            .await?;

        Ok(RawAddresses {
            public: public_addresses,
            internal: internal_addresses,
        })
    }
}

/// Function to find the index and public (false) or internal (true) type of an Bech32 encoded address
pub async fn search_address(
    secret_manager: &SecretManager,
    bech32_hrp: &str,
    coin_type: u32,
    account_index: u32,
    range: Range<u32>,
    address: &Address,
) -> Result<(u32, bool)> {
    let addresses = GetAddressesBuilder::new(secret_manager)
        .with_coin_type(coin_type)
        .with_account_index(account_index)
        .with_range(range.clone())
        .get_all_raw()
        .await?;
    for index in 0..addresses.public.len() {
        if addresses.public[index] == *address {
            return Ok((range.start + index as u32, false));
        }
        if addresses.internal[index] == *address {
            return Ok((range.start + index as u32, true));
        }
    }
    Err(crate::error::Error::InputAddressNotFound(
        address.to_bech32(bech32_hrp),
        format!("{:?}", range),
    ))
}