iota-client 0.4.0

Client to use Iota APIs
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
use reqwest::r#async::Response;
use serde_json::Value;
use tokio::prelude::*;
use tokio::runtime::Runtime;

use iota_validation::input_validator;

use crate::core::*;
use crate::options::*;
use crate::Result;

// TODO once async/await is stable, this file needs to be updated

/// An instance of the client using IRI URI
#[derive(Debug)]
pub struct Client<'a> {
    /// URI of IRI connection
    pub uri: &'a str,
    /// Handle to the Tokio runtime
    pub runtime: Runtime,
    /// A reqwest Client to make Requests with
    pub client: reqwest::r#async::Client,
}

impl<'a> Default for Client<'a> {
    fn default() -> Client<'a> {
        Client {
            uri: "",
            runtime: Runtime::new().unwrap(),
            client: reqwest::r#async::Client::new(),
        }
    }
}

impl<'a> Client<'a> {
    /// Create a new instance of Client
    pub fn new(uri: &str) -> Client<'_> {
        Client {
            uri: uri,
            runtime: Runtime::new().unwrap(),
            client: reqwest::r#async::Client::new(),
        }
    }

    /// Add a list of neighbors to your node. It should be noted that
    /// this is only temporary, and the added neighbors will be removed
    /// from your set of neighbors after you relaunch IRI.
    /// ```
    /// use iota_client;
    /// let mut client = iota_client::Client::new("https://node01.iotatoken.nl");
    /// let resp = client.add_neighbors(&vec!["".into()]).unwrap();
    /// println!("{:?}", resp);
    /// ```
    pub fn add_neighbors(&mut self, uris: &[String]) -> Result<AddNeighborsResponse> {
        let parsed_resp: AddNeighborsResponse = self
            .runtime
            .block_on(
                add_neighbors::add_neighbors(&self.client, self.uri, uris)
                    .and_then(|mut resp| resp.json()),
            )
            .unwrap();
        Ok(parsed_resp)
    }

    /// Performs proof of work
    ///
    /// * `uri` - the uri used to make the request
    /// * `trunk_transaction` - trunk transaction to confirm
    /// * `branch_transaction` - branch transaction to confirm
    /// * `min_weight_magnitude` - Difficulty of PoW
    /// * `trytes` - tryes to use for PoW
    pub fn attach_to_tangle(
        &mut self,
        options: AttachOptions<'_, '_, '_>,
    ) -> Result<AttachToTangleResponse> {
        ensure!(
            input_validator::is_hash(&options.trunk_transaction),
            "Provided trunk transaction is not valid: {:?}",
            options.trunk_transaction
        );
        ensure!(
            input_validator::is_hash(&options.branch_transaction),
            "Provided branch transaction is not valid: {:?}",
            options.branch_transaction
        );
        ensure!(
            input_validator::is_array_of_trytes(&options.trytes),
            "Provided trytes are not valid: {:?}",
            options.trytes
        );

        let attach_resp: AttachToTangleResponse = self
            .runtime
            .block_on(
                attach_to_tangle::attach_to_tangle(&self.client, self.uri, options)
                    .and_then(|mut resp| resp.json()),
            )
            .unwrap();

        if let Some(error) = attach_resp.error() {
            return Err(format_err!("{}", error));
        }
        if let Some(exception) = attach_resp.exception() {
            return Err(format_err!("{}", exception));
        }

        Ok(attach_resp)
    }

    /// Broadcast a list of transactions to all neighbors.
    /// The input trytes for this call are provided by attachToTangle.
    pub fn broadcast_transactions(
        &mut self,
        trytes: &[String],
    ) -> Result<BroadcastTransactionsResponse> {
        ensure!(
            input_validator::is_array_of_attached_trytes(&trytes),
            "Provided trytes are not valid: {:?}",
            trytes
        );

        let parsed_response: BroadcastTransactionsResponse = self
            .runtime
            .block_on(
                broadcast_transactions::broadcast_transactions(&self.client, self.uri, trytes)
                    .and_then(|mut resp| resp.json()),
            )
            .unwrap();
        // let parsed_response: BroadcastTransactionsResponse = self.runtime.block_on(resp.json()).unwrap();

        if let Some(error) = parsed_response.error() {
            return Err(format_err!("{}", error));
        }
        if let Some(exception) = parsed_response.exception() {
            return Err(format_err!("{}", exception));
        }

        Ok(parsed_response)
    }

    /// Checks for consistency of given hashes, not part of the public api
    pub fn check_consistency(&mut self, hashes: &[String]) -> Result<Value> {
        for hash in hashes {
            ensure!(
                input_validator::is_hash(hash),
                "Provided hash is not valid: {:?}",
                hash
            );
        }
        let parsed: Value = self
            .runtime
            .block_on(
                check_consistency::check_consistency(&self.client, self.uri, hashes)
                    .and_then(|mut resp| resp.json()),
            )
            .unwrap();
        Ok(parsed)
    }

    /// Finds transactions the match any of the provided parameters
    pub fn find_transactions(
        &mut self,
        options: FindTransactionsOptions,
    ) -> Result<FindTransactionsResponse> {
        let parsed_resp: FindTransactionsResponse = self
            .runtime
            .block_on(
                find_transactions::find_transactions(&self.client, self.uri, options)
                    .and_then(|mut resp| resp.json()),
            )
            .unwrap();
        if let Some(error) = parsed_resp.error() {
            return Err(format_err!("{}", error));
        }

        Ok(parsed_resp)
    }

    /// Returns the balance based on the latest confirmed milestone.
    /// In addition to the balances, it also returns the referencing tips (or milestone),
    /// as well as the index with which the confirmed balance was
    /// determined. The balances is returned as a list in the same
    /// order as the addresses were provided as input.
    pub fn get_balances(&mut self, options: GetBalancesOptions) -> Result<GetBalancesResponse> {
        ensure!(
            input_validator::is_array_of_hashes(&options.addresses),
            "Provided addresses are not valid: {:?}",
            options.addresses
        );
        let parsed_resp: GetBalancesResponse = self
            .runtime
            .block_on(
                get_balances::get_balances(&self.client, self.uri, options)
                    .and_then(|mut resp| resp.json()),
            )
            .unwrap();
        Ok(parsed_resp)
    }

    /// Get the inclusion states of a set of transactions. This is
    /// for determining if a transaction was accepted and confirmed
    /// by the network or not. You can search for multiple tips (and
    /// thus, milestones) to get past inclusion states of transactions.
    ///
    /// This API call simply returns a list of boolean values in the
    /// same order as the transaction list you submitted, thus you get
    /// a true/false whether a transaction is confirmed or not.
    pub fn get_inclusion_states(
        &mut self,
        options: GetInclusionStatesOptions,
    ) -> Result<GetInclusionStatesResponse> {
        ensure!(
            input_validator::is_array_of_hashes(&options.transactions),
            "Provided transactions are not valid: {:?}",
            options.transactions
        );
        if !options.tips.is_empty() {
            ensure!(
                input_validator::is_array_of_hashes(&options.tips),
                "Provided tips are not valid: {:?}",
                options.tips
            );
        }

        let parsed_resp: GetInclusionStatesResponse = self
            .runtime
            .block_on(
                get_inclusion_states::get_inclusion_states(&self.client, self.uri, options)
                    .and_then(|mut resp| resp.json()),
            )
            .unwrap();

        if let Some(error) = parsed_resp.error() {
            return Err(format_err!("{}", error));
        }

        Ok(parsed_resp)
    }

    /// Returns the set of neighbors you are connected with, as
    /// well as their activity count. The activity counter is reset
    /// after restarting IRI.
    pub fn get_neighbors(&mut self) -> Result<GetNeighborsResponse> {
        let parsed_resp: GetNeighborsResponse = self
            .runtime
            .block_on(
                get_neighbors::get_neighbors(&self.client, self.uri)
                    .and_then(|mut resp| resp.json()),
            )
            .unwrap();

        if let Some(error) = parsed_resp.error() {
            return Err(format_err!("{}", error));
        }

        Ok(parsed_resp)
    }

    /// Gets information about the specified node
    pub fn get_node_info(&mut self) -> Result<GetNodeInfoResponse> {
        let parsed_resp: GetNodeInfoResponse = self
            .runtime
            .block_on(
                get_node_info::get_node_info(&self.client, self.uri)
                    .and_then(|mut resp| resp.json()),
            )
            .unwrap();

        Ok(parsed_resp)
    }

    /// Returns the list of tips
    pub fn get_tips(&mut self) -> Result<GetTipsResponse> {
        let parsed_resp: GetTipsResponse = self
            .runtime
            .block_on(get_tips::get_tips(&self.client, self.uri).and_then(|mut resp| resp.json()))
            .unwrap();
        Ok(parsed_resp)
    }

    /// Tip selection which returns `trunkTransaction` and
    /// `branchTransaction`. The input value depth determines
    /// how many milestones to go back to for finding the
    /// transactions to approve. The higher your depth value,
    /// the more work you have to do as you are confirming more
    /// transactions. If the depth is too large (usually above 15,
    /// it depends on the node's configuration) an error will be
    /// returned. The reference is an optional hash of a transaction
    /// you want to approve. If it can't be found at the specified
    /// depth then an error will be returned.
    pub fn get_transactions_to_approve(
        &mut self,
        options: GetTransactionsToApproveOptions<'_>,
    ) -> Result<GetTransactionsToApprove> {
        let parsed_resp: GetTransactionsToApprove = self
            .runtime
            .block_on(
                get_transactions_to_approve::get_transactions_to_approve(
                    &self.client,
                    self.uri,
                    options,
                )
                .and_then(|mut resp| resp.json()),
            )
            .unwrap();

        if let Some(error) = parsed_resp.error() {
            return Err(format_err!("{}", error));
        }
        if let Some(exception) = parsed_resp.exception() {
            return Err(format_err!("{}", exception));
        }

        Ok(parsed_resp)
    }

    /// Returns the raw transaction data (trytes) of a specific
    /// transaction. These trytes can then be easily converted
    /// into the actual transaction object. See utility functions
    /// for more details.
    pub fn get_trytes(&mut self, hashes: &[String]) -> Result<GetTrytesResponse> {
        ensure!(
            input_validator::is_array_of_hashes(&hashes),
            "Provided hashes are not valid: {:?}",
            hashes
        );

        let parsed_resp: GetTrytesResponse = self
            .runtime
            .block_on(
                get_trytes::get_trytes(&self.client, self.uri, hashes)
                    .and_then(|mut resp| resp.json()),
            )
            .unwrap();
        Ok(parsed_resp)
    }

    /// Interupts an existing PoW request if you made one
    pub fn interrupt_attaching_to_tangle(&mut self) -> Result<Response> {
        let resp = self
            .runtime
            .block_on(
                interrupt_attaching_to_tangle::interrupt_attaching_to_tangle(
                    &self.client,
                    self.uri,
                ),
            )
            .unwrap();
        Ok(resp)
    }

    /// Removes a list of neighbors to your node.
    /// This is only temporary, and if you have your neighbors
    /// added via the command line, they will be retained after
    /// you restart your node.
    pub fn remove_neighbors(&mut self, uris: &[String]) -> Result<RemoveNeighborsResponse> {
        let parsed_resp: RemoveNeighborsResponse = self
            .runtime
            .block_on(
                remove_neighbors::remove_neighbors(&self.client, self.uri, uris)
                    .and_then(|mut resp| resp.json()),
            )
            .unwrap();
        Ok(parsed_resp)
    }

    /// Store transactions into the local storage.
    /// The trytes to be used for this call are
    /// returned by attachToTangle.
    pub fn store_transactions(&mut self, trytes: &[String]) -> Result<StoreTransactionsResponse> {
        ensure!(
            input_validator::is_array_of_attached_trytes(&trytes),
            "Provided trytes are not valid: {:?}",
            trytes
        );

        let parsed_resp: StoreTransactionsResponse = self
            .runtime
            .block_on(
                store_transactions::store_transactions(&self.client, self.uri, trytes)
                    .and_then(|mut resp| resp.json()),
            )
            .unwrap();
        Ok(parsed_resp)
    }

    /// Check if a list of addresses was ever spent from.
    pub fn were_addresses_spent_from(
        &mut self,
        addresses: &[String],
    ) -> Result<WereAddressesSpentFromResponse> {
        let addresses: Vec<String> = addresses
            .iter()
            .filter(|address| input_validator::is_address(address))
            .map(|address| iota_signing::checksum::remove_checksum(address))
            .collect();
        ensure!(!addresses.is_empty(), "No valid addresses provided.");

        let parsed_resp: WereAddressesSpentFromResponse = self
            .runtime
            .block_on(
                were_addresses_spent_from::were_addresses_spent_from(
                    &self.client,
                    self.uri,
                    &addresses,
                )
                .and_then(|mut resp| resp.json()),
            )
            .unwrap();
        Ok(parsed_resp)
    }
}