-
Notifications
You must be signed in to change notification settings - Fork 3
/
lib.rs
683 lines (585 loc) · 22.8 KB
/
lib.rs
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
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
//! Welcome to the Flow-Rust-SDK!
//! We're glad to have you here.
//! There are a few important items that we should cover real quick before you dive in.
//!
//! ## Signing Algorithms
//!
//! - Only `ECDSA_P256` is supported at this time
//!
//! ## Hashing
//!
//! - Only `SHA3_256` is supported at this time
//!
//! ## Security
//!
//! - The cryptography in this SDK is sourced from the public [`RustCrypto`] repositories. This is a very mature and widely used library, but the elliptic curve arithmetic contained in these crates has never been independently audited. *Use at your own risk.*
//! - Remember that you will be dealing with private keys, which can be more powerful and dangerous than passwords. Please treat them as such.
//! - Consider reading [`this whitepaper by Google`]
//!
//! ## Documentation
//!
//! See the [`docs.rs`] for full documentation.
//! Please open an issue in the [`GitHub repository`] if you find any bugs.
//! For general questions, please join the [`Flow Discord`]. There is a flow-rust channel which is an excellent place for discussion!
//!
//! ## Basic Usage
//!
//! In your Cargo.toml
//! ```
//! flow-rust-sdk = "*" // replace * with the highest version available
//! ```
//!
//! You may also wish to add
//! ```
//! tokio = { version = "1.11.0", features = ["full"] }
//! ```
//!
//! ```
//! use flow_rust_sdk::*;
//!
//! #[tokio::main]
//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
//! // check if testnet is available
//! check_availability(&"grpc://access.devnet.nodes.onflow.org:9000".to_string()).await?;
//! Ok(())
//! }
//! ```
//!
//! [`RustCrypto`]: https://github.com/RustCrypto
//! [this whitepaper by Google]: https://cloud.google.com/solutions/modern-password-security-for-system-designers.pdf
//! [docs.rs]: https://docs.rs/flow-rust-sdk/latest/flow_rust_sdk/
//! [GitHub repository]: https://github.com/MarshallBelles/flow-rust-sdk
//! [Flow Discord]: https://discord.com/invite/flow
// ****************************************************
// License: Apache V2.0 OR MIT, at your option
// ****************************************************
// ****************************************************
// External Dependencies
// ****************************************************
use std::error;
use flow::access_api_client::AccessApiClient;
use flow::{
AccountResponse, BlockResponse, CollectionResponse, EventsResponse,
ExecuteScriptAtLatestBlockRequest, ExecuteScriptResponse, GetAccountAtLatestBlockRequest,
GetBlockByHeightRequest, GetBlockByIdRequest, GetCollectionByIdRequest,
GetEventsForBlockIdsRequest, GetEventsForHeightRangeRequest, GetLatestBlockRequest,
GetTransactionRequest, PingRequest, SendTransactionRequest, SendTransactionResponse,
Transaction, TransactionProposalKey, TransactionResponse, TransactionResultResponse,
TransactionSignature,
};
pub mod flow {
//! `flow` is an exported module from the flow_rust_sdk.
//! It's types are generated directly from the gRPC API Protobufs
//! https://github.com/onflow/flow/tree/master/protobuf
tonic::include_proto!("flow.access");
}
// for signing transactions
use bytes::Bytes;
use p256_flow::ecdsa::{signature_flow::Signature, signature_flow::Signer, SigningKey};
use p256_flow::elliptic_curve_flow::SecretKey;
pub extern crate hex;
pub extern crate rlp;
use rlp::*;
// ****************************************************
// Public Methods
// ****************************************************
/// Checks the availability of the node at `network_address`
/// if this fails, it's probably because the endpoint is not available.
pub async fn check_availability(network_address: &String) -> Result<(), Box<dyn error::Error>> {
let mut client = AccessApiClient::connect(network_address.clone()).await?;
let request = tonic::Request::new(PingRequest {});
client.ping(request).await?;
Ok(())
}
/// get_account will return the `flow::AccountResponse` of `network_address`, else an error
/// if it could not be accessed.
pub async fn get_account(
network_address: &String,
account_address: String,
) -> Result<AccountResponse, Box<dyn error::Error>> {
let mut client = AccessApiClient::connect(network_address.clone()).await?;
let request = tonic::Request::new(GetAccountAtLatestBlockRequest {
address: hex::decode(account_address).unwrap(),
});
let response = client.get_account_at_latest_block(request).await?;
Ok(response.into_inner())
}
/// execute_script will attempt to run the provided script (as bytes) and return the `flow::ExecuteScriptResponse` or Error
pub async fn execute_script(
network_address: &String,
script: Vec<u8>,
) -> Result<ExecuteScriptResponse, Box<dyn error::Error>> {
let mut client = AccessApiClient::connect(network_address.clone()).await?;
let request = tonic::Request::new(ExecuteScriptAtLatestBlockRequest { script });
let response = client.execute_script_at_latest_block(request).await?;
Ok(response.into_inner())
}
/// build_transaction will construct a `flow::Transaction` with the provided script and arguments.
/// See the `Argument` struct for details on how to construct arguments.
pub async fn build_transaction(
script: Vec<u8>,
arguments: Vec<Vec<u8>>,
reference_block_id: Vec<u8>,
gas_limit: u64,
proposer: TransactionProposalKey,
authorizers: Vec<String>,
payer: String,
) -> Result<Transaction, Box<dyn error::Error>> {
Ok(Transaction {
script,
arguments: arguments,
reference_block_id: reference_block_id,
gas_limit: gas_limit,
proposal_key: Some(proposer),
authorizers: authorizers
.iter()
.map(|x| hex::decode(x).unwrap())
.collect(),
payload_signatures: vec![],
envelope_signatures: vec![],
payer: hex::decode(payer).unwrap(),
})
}
/// Construct a signature object. Pass this into the payload
/// or envelope signatures when signing a transaction.
pub struct Sign {
pub address: String,
pub key_id: u32,
pub private_key: String,
}
fn envelope_from_transaction(
transaction: Transaction,
payload_signatures: &Vec<TransactionSignature>,
) -> Vec<u8> {
let proposal_key = transaction.proposal_key.unwrap();
let mut proposal_address = proposal_key.address;
padding(&mut proposal_address, 8);
let mut ref_block = transaction.reference_block_id;
padding(&mut ref_block, 32);
let mut stream = RlpStream::new_list(2);
stream.begin_list(9);
stream.append(&Bytes::from(transaction.script).to_vec());
stream.begin_list(transaction.arguments.len());
for (_i, arg) in transaction.arguments.into_iter().enumerate() {
stream.append(&Bytes::from(arg).to_vec());
}
stream.append(&Bytes::from(ref_block).to_vec());
stream.append(&transaction.gas_limit);
stream.append(&Bytes::from(proposal_address).to_vec());
stream.append(&proposal_key.key_id);
stream.append(&proposal_key.sequence_number);
stream.append(&Bytes::from(transaction.payer).to_vec());
stream.begin_list(transaction.authorizers.len());
for (_i, auth) in transaction.authorizers.into_iter().enumerate() {
stream.append(&Bytes::from(auth).to_vec());
}
stream.begin_list(payload_signatures.len());
for (i, sig) in payload_signatures.into_iter().enumerate() {
let signature = sig.signature.to_vec();
stream.begin_list(3);
stream.append(&(i as u32));
stream.append(&sig.key_id);
stream.append(&signature);
}
let out = stream.out().to_vec();
return out;
}
fn payload_from_transaction(transaction: Transaction) -> Vec<u8> {
let proposal_key = transaction.proposal_key.unwrap();
let mut proposal_address = proposal_key.address;
padding(&mut proposal_address, 8);
let mut ref_block = transaction.reference_block_id;
padding(&mut ref_block, 32);
let mut stream = RlpStream::new_list(9);
stream.append(&Bytes::from(transaction.script).to_vec());
stream.begin_list(transaction.arguments.len());
for (_i, arg) in transaction.arguments.into_iter().enumerate() {
stream.append(&Bytes::from(arg).to_vec());
}
stream.append(&Bytes::from(ref_block).to_vec());
stream.append(&transaction.gas_limit);
stream.append(&Bytes::from(proposal_address).to_vec());
stream.append(&proposal_key.key_id);
stream.append(&proposal_key.sequence_number);
stream.append(&Bytes::from(transaction.payer).to_vec());
stream.begin_list(transaction.authorizers.len());
for (_i, auth) in transaction.authorizers.into_iter().enumerate() {
stream.append(&Bytes::from(auth).to_vec());
}
let out = stream.out().to_vec();
return out;
}
fn sign(message: Vec<u8>, private_key: String) -> Result<Vec<u8>, Box<dyn error::Error>> {
let secret_key = SecretKey::from_be_bytes(&hex::decode(private_key)?)?;
let sig_key = SigningKey::from(secret_key);
let signature = sig_key.sign(&message);
println!("msg {}", hex::encode(message));
println!("sig {}", hex::encode(signature.as_bytes()));
Ok(signature.as_bytes().to_vec())
}
fn padding(vec: &mut Vec<u8>, count: usize) {
let mut i: usize = count;
i = i - vec.len();
while i > 0 {
vec.push(0);
i = i - 1;
}
}
/// Sign the provided transaction.
/// You will first need to `build_transaction`.
pub async fn sign_transaction(
built_transaction: Transaction,
payload_signatures: Vec<&Sign>,
envelope_signatures: Vec<&Sign>,
) -> Result<Option<Transaction>, Box<dyn error::Error>> {
let mut payload: Vec<TransactionSignature> = vec![];
let mut envelope: Vec<TransactionSignature> = vec![];
// for each of the payload private keys, sign the transaction
for signer in payload_signatures {
let encoded_payload: &[u8] = &payload_from_transaction(built_transaction.clone());
let mut domain_tag: Vec<u8> = b"FLOW-V0.0-transaction".to_vec();
// we need to pad 0s at the end of the domain_tag
padding(&mut domain_tag, 32);
let fully_encoded: Vec<u8> = [&domain_tag, encoded_payload].concat();
let mut addr = hex::decode(signer.address.clone()).unwrap();
padding(&mut addr, 8);
payload.push(TransactionSignature {
address: addr,
key_id: signer.key_id,
signature: sign(fully_encoded, signer.private_key.clone())?,
});
}
// for each of the envelope private keys, sign the transaction
for signer in envelope_signatures {
let encoded_payload: &[u8] =
&envelope_from_transaction(built_transaction.clone(), &payload);
let mut domain_tag: Vec<u8> = b"FLOW-V0.0-transaction".to_vec();
// we need to pad 0s at the end of the domain_tag
padding(&mut domain_tag, 32);
let fully_encoded: Vec<u8> = [&domain_tag, encoded_payload].concat();
let mut addr = hex::decode(signer.address.clone()).unwrap();
padding(&mut addr, 8);
envelope.push(TransactionSignature {
address: addr,
key_id: signer.key_id,
signature: sign(fully_encoded, signer.private_key.clone())?,
});
}
let signed_transaction = Some(Transaction {
script: built_transaction.script,
arguments: built_transaction.arguments,
reference_block_id: built_transaction.reference_block_id,
gas_limit: built_transaction.gas_limit,
proposal_key: built_transaction.proposal_key,
authorizers: built_transaction.authorizers,
payload_signatures: payload,
envelope_signatures: envelope,
payer: built_transaction.payer,
});
Ok(signed_transaction)
}
/// Sends the transaction to the blockchain.
/// Make sure you signed the transactionsign_transaction first.
pub async fn send_transaction(
network_address: &String,
transaction: Option<Transaction>,
) -> Result<SendTransactionResponse, Box<dyn error::Error>> {
// send to blockchain
let mut client = AccessApiClient::connect(network_address.clone()).await?;
let request = tonic::Request::new(SendTransactionRequest { transaction });
let response = client.send_transaction(request).await?;
Ok(response.into_inner())
}
/// get transaction result
pub async fn get_transaction_result(
network_address: &String,
id: Vec<u8>,
) -> Result<TransactionResultResponse, Box<dyn error::Error>> {
// send to blockchain
let mut client = AccessApiClient::connect(network_address.clone()).await?;
let request = tonic::Request::new(GetTransactionRequest { id });
let response = client.get_transaction_result(request).await?;
Ok(response.into_inner())
}
/// get transaction result
pub async fn get_transaction(
network_address: &String,
id: Vec<u8>,
) -> Result<TransactionResponse, Box<dyn error::Error>> {
// send to blockchain
let mut client = AccessApiClient::connect(network_address.clone()).await?;
let request = tonic::Request::new(GetTransactionRequest { id });
let response = client.get_transaction(request).await?;
Ok(response.into_inner())
}
/// get_block accepts either the block_id or block_height. If neither are defined it returns the latest block.
pub async fn get_block(
network_address: &String,
block_id: Option<String>,
block_height: Option<u64>,
is_sealed: Option<bool>,
) -> Result<BlockResponse, Box<dyn error::Error>> {
if block_id.is_some() {
// IF block_id, use this
let mut client = AccessApiClient::connect(network_address.clone()).await?;
let request = tonic::Request::new(GetBlockByIdRequest {
id: block_id.unwrap().as_bytes().to_vec(),
});
let response = client.get_block_by_id(request).await?;
Ok(response.into_inner())
} else if block_height.is_some() {
// else IF block_height, use that
let mut client = AccessApiClient::connect(network_address.clone()).await?;
let request = tonic::Request::new(GetBlockByHeightRequest {
height: block_height.unwrap(),
});
let response = client.get_block_by_height(request).await?;
Ok(response.into_inner())
} else {
// else, just get latest block
if is_sealed.is_some() {
let mut client = AccessApiClient::connect(network_address.clone()).await?;
let request = tonic::Request::new(GetLatestBlockRequest {
is_sealed: is_sealed.unwrap(),
});
let response = client.get_latest_block(request).await?;
Ok(response.into_inner())
} else {
let mut client = AccessApiClient::connect(network_address.clone()).await?;
let request = tonic::Request::new(GetLatestBlockRequest { is_sealed: false });
let response = client.get_latest_block(request).await?;
Ok(response.into_inner())
}
}
}
/// retrieve the specified events by type for the given height range
pub async fn get_events_for_height_range(
network_address: &String,
event_type: String,
start_height: u64,
end_height: u64,
) -> Result<EventsResponse, Box<dyn error::Error>> {
let mut client = AccessApiClient::connect(network_address.clone()).await?;
let request = tonic::Request::new(GetEventsForHeightRangeRequest {
r#type: event_type,
start_height,
end_height,
});
let response = client.get_events_for_height_range(request).await?;
Ok(response.into_inner())
}
/// retrieve the specified events by type for the given blocks
pub async fn get_events_for_block_ids(
network_address: &String,
event_type: String,
ids: Vec<Vec<u8>>,
) -> Result<EventsResponse, Box<dyn error::Error>> {
let mut client = AccessApiClient::connect(network_address.clone()).await?;
let request = tonic::Request::new(GetEventsForBlockIdsRequest {
r#type: event_type,
block_ids: ids,
});
let response = client.get_events_for_block_i_ds(request).await?;
Ok(response.into_inner())
}
/// retrieve the specified collections
pub async fn get_collection(
network_address: &String,
collection_id: Vec<u8>,
) -> Result<CollectionResponse, Box<dyn error::Error>> {
let mut client = AccessApiClient::connect(network_address.clone()).await?;
let request = tonic::Request::new(GetCollectionByIdRequest { id: collection_id });
let response = client.get_collection_by_id(request).await?;
Ok(response.into_inner())
}
// ****************************************************
// Utility Functionality
// ****************************************************
use serde::Serialize;
use serde_json::{json, Value};
use tokio::time::{sleep, Duration};
#[derive(Serialize)]
pub struct Argument<T> {
r#type: String,
value: T,
}
impl Argument<Vec<Value>> {
pub fn array(values: Vec<Value>) -> Argument<Vec<Value>> {
return Argument {
r#type: "Array".to_string(),
value: values,
};
}
pub fn dictionary(values: Vec<(String, String)>) -> Argument<Vec<Value>> {
return Argument {
r#type: "Dictionary".to_string(),
value: values
.into_iter()
.map(|(x, y)| json!({"Key":x, "Value":y}))
.collect(),
};
}
}
impl Argument<String> {
pub fn string(value: String) -> Argument<String> {
return Argument {
r#type: "String".to_string(),
value,
};
}
}
fn process_keys_args(account_keys: Vec<String>) -> Argument<Vec<Value>> {
// do special processing for the keys, wrapping with algo, hash, and weight information:
// algo: ECDSA_P256
// hash: SHA3_256
// weight: 1000
return Argument::array(
account_keys
.into_iter()
.map(|x| json!(Argument::string(format!("f847b840{}02038203e8", x))))
.collect::<Vec<Value>>(),
);
}
pub async fn create_account(
network_address: &String,
account_keys: Vec<String>,
payer: &String,
payer_private_key: &String,
key_id: u32,
) -> Result<flow::Account, Box<dyn error::Error>> {
let create_account_template = b"
transaction(publicKeys: [String], contracts: {String: String}) {
prepare(signer: AuthAccount) {
let acct = AuthAccount(payer: signer)
for key in publicKeys {
acct.addPublicKey(key.decodeHex())
}
for contract in contracts.keys {
acct.contracts.add(name: contract, code: contracts[contract]!.decodeHex())
}
}
}";
let latest_block: BlockResponse = get_block(network_address, None, None, Some(false)).await?;
let account: flow::Account = get_account(network_address, payer.clone())
.await?
.account
.unwrap();
let proposer = TransactionProposalKey {
address: hex::decode(payer).unwrap(),
key_id,
sequence_number: account.keys[key_id as usize].sequence_number as u64,
};
let keys_arg = process_keys_args(account_keys);
// empty contracts for now - will implement in the future
let contracts_arg = Argument::dictionary(vec![]);
let keys_arg = json!(keys_arg);
let contracts_arg = json!(contracts_arg);
let transaction: Transaction = build_transaction(
create_account_template.to_vec(),
vec![
serde_json::to_vec(&keys_arg)?,
serde_json::to_vec(&contracts_arg)?,
],
latest_block.block.unwrap().id,
1000,
proposer,
vec![payer.clone()],
payer.clone(),
)
.await?;
let signature = Sign {
address: payer.clone(),
key_id,
private_key: payer_private_key.clone(),
};
let transaction: Option<Transaction> =
sign_transaction(transaction, vec![], vec![&signature]).await?;
let transaction: SendTransactionResponse =
send_transaction(network_address, transaction).await?;
// poll for transaction completion
let mut time: u64 = 50;
let mut i = 0;
println!("{}", hex::encode(transaction.id.to_vec()));
while i < 50 {
i = i + 1;
sleep(Duration::from_millis(time)).await;
let res = get_transaction_result(network_address, transaction.id.to_vec()).await?;
match res.status {
0 | 1 | 2 | 3 => {
time = time + 200;
}
4 => {
if res.status_code == 1 {
// stop execution, error.
assert_ne!(res.error_message, res.error_message);
}
let new_account_address: flow::Event = res
.events
.into_iter()
.filter(|x| x.r#type == "flow.AccountCreated")
.collect::<Vec<flow::Event>>()
.pop()
.unwrap();
let payload: Value = serde_json::from_slice(&new_account_address.payload)?;
let address: String = payload["value"]["fields"][0]["value"]["value"]
.to_string()
.split_at(3)
.1
.to_string()
.split_at(16)
.0
.to_string();
let acct: flow::Account = get_account(network_address, address)
.await?
.account
.expect("could not get newly created account");
return Ok(acct);
}
_ => {
return Err("Cadence Runtime Error")?;
}
}
}
return Err("Could not produce result")?;
}
// ****************************************************
// Testing
// ****************************************************
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
async fn comprehensive_usage_case() {
let service_account = std::env::vars().filter(|kv| kv.0 == "SERVICE_ACCT").map(|kv| kv.1).collect::<Vec<String>>();
let private_key = std::env::vars().filter(|kv| kv.0 == "PRIV_K").map(|kv| kv.1).collect::<Vec<String>>();
let public_key = std::env::vars().filter(|kv| kv.0 == "PUB_K").map(|kv| kv.1).collect::<Vec<String>>();
// let's first create an account
// create the public and private keys
// TODO
// create the account
let network_address = "https://access.devnet.nodes.onflow.org:9000".to_string();
let payer = &service_account[0];
let payer_private_key = &private_key[0];
let public_keys = vec![public_key[0].to_owned()];
let acct = create_account(
&network_address,
public_keys.to_vec(),
&payer,
&payer_private_key,
0,
)
.await
.expect("Could not create account");
println!("{:?}", acct);
// create a token contract
// TODO
// add contract to the newly created account
// TODO
// execute minting transaction
// TODO
// trade token for flow transaction
// TODO
// verify new balances
// TODO
}
}