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
use crate::AleoAPIClient;
use snarkvm_console::{
account::{PrivateKey, ViewKey},
program::{Ciphertext, Network, ProgramID, Record},
types::Field,
};
use snarkvm_synthesizer::{Block, Program, Transaction};
use anyhow::{anyhow, bail, ensure, Result};
use std::{convert::TryInto, ops::Range};
#[cfg(not(feature = "async"))]
#[allow(clippy::type_complexity)]
impl<N: Network> AleoAPIClient<N> {
pub fn latest_height(&self) -> Result<u32> {
let url = format!("{}/{}/latest/height", self.base_url, self.network_id);
match self.client.get(&url).call()?.into_json() {
Ok(height) => Ok(height),
Err(error) => bail!("Failed to parse the latest block height: {error}"),
}
}
pub fn latest_hash(&self) -> Result<N::BlockHash> {
let url = format!("{}/{}/latest/hash", self.base_url, self.network_id);
match self.client.get(&url).call()?.into_json() {
Ok(hash) => Ok(hash),
Err(error) => bail!("Failed to parse the latest block hash: {error}"),
}
}
pub fn latest_block(&self) -> Result<Block<N>> {
let url = format!("{}/{}/latest/block", self.base_url, self.network_id);
match self.client.get(&url).call()?.into_json() {
Ok(block) => Ok(block),
Err(error) => bail!("Failed to parse the latest block: {error}"),
}
}
pub fn get_block(&self, height: u32) -> Result<Block<N>> {
let url = format!("{}/{}/block/{height}", self.base_url, self.network_id);
match self.client.get(&url).call()?.into_json() {
Ok(block) => Ok(block),
Err(error) => bail!("Failed to parse block {height}: {error}"),
}
}
pub fn get_blocks(&self, start_height: u32, end_height: u32) -> Result<Vec<Block<N>>> {
if start_height >= end_height {
bail!("Start height must be less than end height");
} else if end_height - start_height > 50 {
bail!("Cannot request more than 50 blocks at a time");
}
let url = format!("{}/{}/blocks?start={start_height}&end={end_height}", self.base_url, self.network_id);
match self.client.get(&url).call()?.into_json() {
Ok(blocks) => Ok(blocks),
Err(error) => {
bail!("Failed to parse blocks {start_height} (inclusive) to {end_height} (exclusive): {error}")
}
}
}
pub fn get_transaction(&self, transaction_id: N::TransactionID) -> Result<Transaction<N>> {
let url = format!("{}/{}/transaction/{transaction_id}", self.base_url, self.network_id);
match self.client.get(&url).call()?.into_json() {
Ok(transaction) => Ok(transaction),
Err(error) => bail!("Failed to parse transaction '{transaction_id}': {error}"),
}
}
pub fn get_memory_pool_transactions(&self) -> Result<Vec<Transaction<N>>> {
let url = format!("{}/{}/memoryPool/transactions", self.base_url, self.network_id);
match self.client.get(&url).call()?.into_json() {
Ok(transactions) => Ok(transactions),
Err(error) => bail!("Failed to parse memory pool transactions: {error}"),
}
}
pub fn get_program(&self, program_id: impl TryInto<ProgramID<N>>) -> Result<Program<N>> {
let program_id = program_id.try_into().map_err(|_| anyhow!("Invalid program ID"))?;
let url = format!("{}/{}/program/{program_id}", self.base_url, self.network_id);
match self.client.get(&url).call()?.into_json() {
Ok(program) => Ok(program),
Err(error) => bail!("Failed to parse program {program_id}: {error}"),
}
}
pub fn find_block_hash(&self, transaction_id: N::TransactionID) -> Result<N::BlockHash> {
let url = format!("{}/{}/find/blockHash/{transaction_id}", self.base_url, self.network_id);
match self.client.get(&url).call()?.into_json() {
Ok(hash) => Ok(hash),
Err(error) => bail!("Failed to parse block hash: {error}"),
}
}
pub fn find_transition_id(&self, input_or_output_id: Field<N>) -> Result<N::TransitionID> {
let url = format!("{}/{}/find/transitionID/{input_or_output_id}", self.base_url, self.network_id);
match self.client.get(&url).call()?.into_json() {
Ok(transition_id) => Ok(transition_id),
Err(error) => bail!("Failed to parse transition ID: {error}"),
}
}
pub fn scan(
&self,
view_key: impl TryInto<ViewKey<N>>,
block_heights: Range<u32>,
max_records: Option<usize>,
) -> Result<Vec<(Field<N>, Record<N, Ciphertext<N>>)>> {
let view_key = view_key.try_into().map_err(|_| anyhow!("Invalid view key"))?;
let address_x_coordinate = view_key.to_address().to_x_coordinate();
let start_block_height = block_heights.start - (block_heights.start % 50);
let end_block_height = block_heights.end + (50 - (block_heights.end % 50));
let mut records = Vec::new();
for start_height in (start_block_height..end_block_height).step_by(50) {
println!("Searching blocks {} to {} for records...", start_height, end_block_height);
if start_height >= block_heights.end {
break;
}
let end = start_height + 50;
let end_height = if end > block_heights.end { block_heights.end } else { end };
let records_iter =
self.get_blocks(start_height, end_height)?.into_iter().flat_map(|block| block.into_records());
records.extend(records_iter.filter_map(|(commitment, record)| {
match record.is_owner_with_address_x_coordinate(&view_key, &address_x_coordinate) {
true => Some((commitment, record)),
false => None,
}
}));
if records.len() >= max_records.unwrap_or(usize::MAX) {
break;
}
}
Ok(records)
}
pub fn get_unspent_records(
&self,
private_key: &PrivateKey<N>,
block_heights: Range<u32>,
max_gates: Option<u64>,
specified_amounts: Option<&Vec<u64>>,
) -> Result<Vec<(Field<N>, Record<N, Ciphertext<N>>)>> {
let view_key = ViewKey::try_from(private_key)?;
let address_x_coordinate = view_key.to_address().to_x_coordinate();
ensure!(
block_heights.start < block_heights.end,
"The start block height must be less than the end block height"
);
let mut records = Vec::new();
let mut total_gates = 0u64;
let mut end_height = block_heights.end;
let mut start_height = block_heights.end.saturating_sub(50);
for _ in (block_heights.start..block_heights.end).step_by(50) {
println!("Searching blocks {} to {} for records...", start_height, end_height);
let records_iter =
self.get_blocks(start_height, end_height)?.into_iter().flat_map(|block| block.into_records());
end_height = start_height;
start_height = start_height.saturating_sub(50);
if start_height < block_heights.start {
start_height = block_heights.start
};
records.extend(records_iter.filter_map(|(commitment, record)| {
match record.is_owner_with_address_x_coordinate(&view_key, &address_x_coordinate) {
true => {
let sn = Record::<N, Ciphertext<N>>::serial_number(*private_key, commitment).ok()?;
if self.find_transition_id(sn).is_err() {
if max_gates.is_some() {
let _ = record
.decrypt(&view_key)
.map(|record| {
total_gates += ***record.gates();
record
})
.ok();
}
Some((commitment, record))
} else {
None
}
}
false => None,
}
}));
if max_gates.is_some() && total_gates > max_gates.unwrap() {
break;
}
if let Some(specified_amounts) = specified_amounts {
let found_records = specified_amounts
.iter()
.filter_map(|amount| {
let position = records.iter().position(|(_, record)| {
if let Ok(decrypted_record) = record.decrypt(&view_key) {
***decrypted_record.gates() > *amount
} else {
false
}
});
position.map(|index| records.remove(index))
})
.collect::<Vec<_>>();
if found_records.len() >= specified_amounts.len() {
return Ok(found_records);
}
}
}
Ok(records)
}
pub fn transaction_broadcast(&self, transaction: Transaction<N>) -> Result<String> {
let url = format!("{}/{}/transaction/broadcast", self.base_url, self.network_id);
match self.client.post(&url).send_json(&transaction) {
Ok(response) => match response.into_string() {
Ok(success_response) => Ok(success_response),
Err(error) => bail!("❌ Transaction response was malformed {}", error),
},
Err(error) => {
let error_message = match error {
ureq::Error::Status(code, response) => {
format!("(status code {code}: {:?})", response.into_string()?)
}
ureq::Error::Transport(err) => format!("({err})"),
};
match transaction {
Transaction::Deploy(..) => {
bail!("❌ Failed to deploy program to {}: {}", &url, error_message)
}
Transaction::Execute(..) => {
bail!("❌ Failed to broadcast execution to {}: {}", &url, error_message)
}
}
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use snarkvm_console::{account::PrivateKey, network::Testnet3};
use std::{convert::TryFrom, str::FromStr};
type N = Testnet3;
#[test]
fn test_api_get_blocks() {
let client = AleoAPIClient::<Testnet3>::testnet3();
let blocks = client.get_blocks(0, 3).unwrap();
assert_eq!(blocks[0].height(), 0);
assert_eq!(blocks[1].height(), 1);
assert_eq!(blocks[2].height(), 2);
assert_eq!(blocks[1].previous_hash(), blocks[0].hash());
assert_eq!(blocks[2].previous_hash(), blocks[1].hash());
}
#[test]
fn test_scan() {
let client = AleoAPIClient::<Testnet3>::testnet3();
let private_key =
PrivateKey::<N>::from_str("APrivateKey1zkp5fCUVzS9b7my34CdraHBF9XzB58xYiPzFJQvjhmvv7A8").unwrap();
let view_key = ViewKey::<N>::try_from(&private_key).unwrap();
let records = client.scan(private_key, 14200..14250, None).unwrap();
assert_eq!(records.len(), 1);
let (commitment, record) = records[0].clone();
assert_eq!(
commitment.to_string(),
"310298409899964034200900546312426933043797406211272306332560156413249565239field"
);
let record = record.decrypt(&view_key).unwrap();
let expected = r"{
owner: aleo18x0yenrkceapvt85e6aqw2v8hq37hpt4ew6k6cgum6xlpmaxt5xqwnkuja.private,
gates: 1099999999999864u64.private,
_nonce: 3859911413360468505092363429199432421222291175370483298628506550397056121761group.public
}";
assert_eq!(record.to_string(), expected);
}
}