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
#![deny(unused_extern_crates)]
#![allow(dead_code)]

#[macro_use]
extern crate failure;
#[macro_use]
extern crate lazy_static;
#[macro_use]
extern crate serde;
#[macro_use]
extern crate serde_json;

use std::sync::Mutex;

use reqwest::r#async::Response;
use serde_json::Value;
use tokio::runtime::Runtime;

use iota_validation::input_validator;

mod add_neighbors;
mod attach_to_tangle;
mod broadcast_transactions;
mod check_consistency;
mod find_transactions;
mod get_balances;
mod get_inclusion_states;
mod get_neighbors;
mod get_node_info;
mod get_tips;
mod get_transactions_to_approve;
mod get_trytes;
mod interrupt_attaching_to_tangle;
mod remove_neighbors;
/// IRI responses are parsed into structs contained in this module
pub mod responses;
mod store_transactions;
mod were_addresses_spent_from;

use crate::responses::*;

pub use attach_to_tangle::{attach_to_tangle_local, AttachOptions};
pub use find_transactions::FindTransactionsOptions;
pub use get_balances::GetBalancesOptions;
pub use get_inclusion_states::GetInclusionStatesOptions;
pub use get_transactions_to_approve::GetTransactionsToApproveOptions;

type Result<T> = ::std::result::Result<T, failure::Error>;

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

lazy_static! {
    static ref CLIENT: reqwest::r#async::Client = { reqwest::r#async::Client::new() };
    static ref RT: Mutex<Runtime> = { Mutex::new(Runtime::new().unwrap()) };
}

/// 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 resp = iota_client::add_neighbors("https://node01.iotatoken.nl", &vec!["".into()]).unwrap();
/// println!("{:?}", resp);
/// ```
pub fn add_neighbors(uri: &str, uris: &[String]) -> Result<AddNeighborsResponse> {
    let mut runtime = RT.lock().unwrap();
    let mut resp = runtime
        .block_on(add_neighbors::add_neighbors(&*CLIENT, uri, uris))
        .unwrap();
    let parsed_resp: AddNeighborsResponse = runtime.block_on(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(uri: &str, 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 mut runtime = RT.lock().unwrap();
    let mut resp = runtime
        .block_on(attach_to_tangle::attach_to_tangle(&*CLIENT, uri, options))
        .unwrap();
    let attach_resp: AttachToTangleResponse = runtime.block_on(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(
    uri: &str,
    trytes: &[String],
) -> Result<BroadcastTransactionsResponse> {
    ensure!(
        input_validator::is_array_of_attached_trytes(&trytes),
        "Provided trytes are not valid: {:?}",
        trytes
    );

    let mut runtime = RT.lock().unwrap();
    let mut resp = runtime
        .block_on(broadcast_transactions::broadcast_transactions(
            &*CLIENT, uri, trytes,
        ))
        .unwrap();
    let parsed_response: BroadcastTransactionsResponse = 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(uri: &str, hashes: &[String]) -> Result<Value> {
    for hash in hashes {
        ensure!(
            input_validator::is_hash(hash),
            "Provided hash is not valid: {:?}",
            hash
        );
    }
    let mut runtime = RT.lock().unwrap();
    let mut resp = runtime
        .block_on(check_consistency::check_consistency(&*CLIENT, uri, hashes))
        .unwrap();
    let parsed: Value = runtime.block_on(resp.json()).unwrap();
    Ok(parsed)
}

/// Finds transactions the match any of the provided parameters
pub fn find_transactions(
    uri: &str,
    options: FindTransactionsOptions,
) -> Result<FindTransactionsResponse> {
    let mut runtime = RT.lock().unwrap();
    let mut resp = runtime
        .block_on(find_transactions::find_transactions(&*CLIENT, uri, options))
        .unwrap();
    let parsed_resp: FindTransactionsResponse = runtime.block_on(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(uri: &str, options: GetBalancesOptions) -> Result<GetBalancesResponse> {
    let mut runtime = RT.lock().unwrap();
    let mut resp = runtime
        .block_on(get_balances::get_balances(&*CLIENT, uri, options))
        .unwrap();
    let parsed_resp: GetBalancesResponse = runtime.block_on(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(
    uri: &str,
    options: GetInclusionStatesOptions,
) -> Result<GetInclusionStatesResponse> {
    ensure!(
        input_validator::is_array_of_hashes(&options.transactions),
        "Provided transactions are not valid: {:?}",
        options.transactions
    );
    ensure!(
        input_validator::is_array_of_hashes(&options.tips),
        "Provided tips are not valid: {:?}",
        options.tips
    );

    let mut runtime = RT.lock().unwrap();
    let mut resp = runtime
        .block_on(get_inclusion_states::get_inclusion_states(
            &*CLIENT, uri, options,
        ))
        .unwrap();
    let parsed_resp: GetInclusionStatesResponse = runtime.block_on(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(uri: &str) -> Result<GetNeighborsResponse> {
    let mut runtime = RT.lock().unwrap();
    let mut resp = runtime
        .block_on(get_neighbors::get_neighbors(&*CLIENT, uri))
        .unwrap();
    let parsed_resp: GetNeighborsResponse = runtime.block_on(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(uri: &str) -> Result<GetNodeInfoResponse> {
    let mut runtime = RT.lock().unwrap();
    let mut resp = runtime
        .block_on(get_node_info::get_node_info(&*CLIENT, uri))
        .unwrap();
    let parsed_resp: GetNodeInfoResponse = runtime.block_on(resp.json()).unwrap();

    Ok(parsed_resp)
}

/// Returns the list of tips
pub fn get_tips(uri: &str) -> Result<GetTipsResponse> {
    let mut runtime = RT.lock().unwrap();
    let mut resp = runtime.block_on(get_tips::get_tips(&*CLIENT, uri)).unwrap();
    let parsed_resp: GetTipsResponse = runtime.block_on(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(
    uri: &str,
    options: GetTransactionsToApproveOptions,
) -> Result<GetTransactionsToApprove> {
    let mut runtime = RT.lock().unwrap();
    let mut resp = runtime
        .block_on(get_transactions_to_approve::get_transactions_to_approve(
            &*CLIENT, uri, options,
        ))
        .unwrap();
    let parsed_resp: GetTransactionsToApprove = runtime.block_on(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(uri: &str, hashes: &[String]) -> Result<GetTrytesResponse> {
    ensure!(
        input_validator::is_array_of_hashes(&hashes),
        "Provided hashes are not valid: {:?}",
        hashes
    );
    let mut runtime = RT.lock().unwrap();
    let mut resp = runtime
        .block_on(get_trytes::get_trytes(&*CLIENT, uri, hashes))
        .unwrap();
    let parsed_resp: GetTrytesResponse = runtime.block_on(resp.json()).unwrap();
    Ok(parsed_resp)
}

/// Interupts an existing PoW request if you made one
pub fn interrupt_attaching_to_tangle(uri: &str) -> Result<Response> {
    let mut runtime = RT.lock().unwrap();
    let resp = runtime
        .block_on(interrupt_attaching_to_tangle::interrupt_attaching_to_tangle(&*CLIENT, 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(uri: &str, uris: &[String]) -> Result<RemoveNeighborsResponse> {
    let mut runtime = RT.lock().unwrap();
    let mut resp = runtime
        .block_on(remove_neighbors::remove_neighbors(&*CLIENT, uri, uris))
        .unwrap();
    let parsed_resp: RemoveNeighborsResponse = runtime.block_on(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(uri: &str, trytes: &[String]) -> Result<StoreTransactionsResponse> {
    let mut runtime = RT.lock().unwrap();
    let mut resp = runtime
        .block_on(store_transactions::store_transactions(
            &*CLIENT, uri, trytes,
        ))
        .unwrap();
    let parsed_resp: StoreTransactionsResponse = runtime.block_on(resp.json()).unwrap();
    Ok(parsed_resp)
}

/// Check if a list of addresses was ever spent from.
pub fn were_addresses_spent_from(
    uri: &str,
    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 mut runtime = RT.lock().unwrap();
    let mut resp = runtime
        .block_on(were_addresses_spent_from::were_addresses_spent_from(
            &*CLIENT, uri, &addresses,
        ))
        .unwrap();
    let parsed_resp: WereAddressesSpentFromResponse = runtime.block_on(resp.json()).unwrap();
    Ok(parsed_resp)
}