-
Notifications
You must be signed in to change notification settings - Fork 23
/
lib.rs
1914 lines (1696 loc) · 66.1 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
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! SDK for uploading files in bulk to [Arweave](https://www.arweave.org/).
//!
//! ## CLI
//! See [README.md](https://crates.io/crates/arloader) for usage instructions.
//!
//! The main cli application is all in `main` and follows a pattern of specifying arguments,
//! matching them, and then in turn passing them to commands, all of which are included
//! in the [`commands`] module in order to facilitate their use as library functions and
//! re-use in other command line applications.
//!
//! ## Library
//!
//! #### Overview
//! The library is focused on uploading files as efficiently as possible. Arweave has
//! two different transaction formats and two different upload formats. Transactions can either
//! be normal, single data item transactions (see [transaction format](https://docs.arweave.org/developers/server/http-api#transaction-format)
//! for details), or bundle transactions (see [bundle format](https://github.com/joshbenaron/arweave-standards/blob/ans104/ans/ANS-104.md)
//! for details). The bundle format, introduced mid-2021, bundles together individual data items
//! into larger transactions, making uploading much more efficient and reducing network congestion.
//! The library supports both formats, with the recommended approach being to use the bundle format.
//!
//! There are also two upload formats, whole transactions, which if they are less than 12 MB can be
//! uploaded to the `tx/` endpoint, and chunked transactions, which get uploaded in 256 KB chunks
//! to the `chunk/`endpoint. Arloader includes functionality for both formats.
//!
//! #### Transactions and DataItems
//! Both transaction formats start with chunking file data and creating merkle trees from the chunks.
//! The merkle tree logic can be found in the [`merkle`] module. All of the hashing functions and other crypto
//! operations are in the [`crypto`] module. Once the data is chunked, hashed, and a merkle root
//! calculated for it, it gets incorporated into either a [`Transaction`], which can be found in the
//! [`transaction`] module, or if it is going to be included in a bundle format transaction, a [`DataItem`],
//! which can be found in the [`bundle`] module.
//!
//! #### Tags
//! [`Tag`]s are structs with `name` and `value` properties that can be included with either [`Transaction`]s or
//! [`DataItem`]s. One subtlety is that for [`Transaction`]s, Arweave expects the content at each key to be a base64 url
//! encoded string, whereas for [`DataItem`]s, Arweave expects utf8-encoded strings. [`Tag`]s have been implemented for
//! for both types as [`Tag<Base64>`] and [`Tag<String>`]. Another subtlety is that [`Tag`]s for [`DataItem`]s are serialized
//! and deserialized using [`avro_rs`], the schema of which is implemented in [`bundle::get_tags_schema`].
//!
//! A [`Tag`] with a name property of `Content-Type` is used by the Arweave gateways to communicate the mime type of
//! the related content to browsers. Arloader creates a content type tag based on file extension if one is provided
//! or from the bytes of the data using [magic numbers](https://en.wikipedia.org/wiki/File_format#Magic_number) if not.
//!
//! #### Bytes and Base64Url Data
//! The library stores all data, signatures and addresses as a [`Base64`] struct with methods implemented for
//! serializing and deserializing the underlying bytes to and from the base64 url format required for uploading
//! to Arweave.
//!
//! #### Signing
//! A key part of constructing transactions is signing them. Arweave has a specific algorithm for generating the
//! digest that gets signed and then hashed to serve as a transaction id, called [deepHash](https://github.com/ArweaveTeam/arweave-js/blob/92d690a52ed0b647f36d58a6eba28542ef609b18/src/common/lib/deepHash.ts#L8).
//! It takes various [`Transaction`] or [`DataItem`] elements, including nested arrays of [`Tag`]s, and successively
//! hashes and concatenates them together. Arloader assembles the required elements via the [`ToItems`] trait, which
//! is implemented separately as [`Transaction::to_deep_hash_item`] and [`DataItem::to_deep_hash_item`] for each transaction
//! format. [`crypto::Provider::deep_hash`] is Arloader's implementation of the deep hash algorithm.
//!
//! #### Higher Level Functions
//! The functions for creating [`Transaction`]s and bundles of [`DataItem`]s are all consolidated on the [`Arweave`] struct.
//! In general, there are lower level functions for creating single items from data that are then composed in successively
//! higher level functions to allow multiple items to be created from collections of file paths and ultimately upload streams
//! of transactions to Arweave.
//!
//! #### Status Tracking
//! The library includes additional functionality to track and report on transaction statuses. There are two status structs,
//! [`Status`] and [`BundleStatus`] used for these purposes. They are essentially the same format, except that
//! [`BundleStatus`] is modified to include references to all of the included [`DataItem`]s instead of just a
//! single [`Transaction`] for [`Status`].
//!
//! #### Solana
//! The functions for allowing payment to be made in SOL can be found in the [`solana`] module.
#![feature(derive_default_enum)]
use blake3;
use chrono::Utc;
use futures::{
future::{try_join, try_join_all},
stream, Stream, StreamExt,
};
use glob::glob;
use infer;
use log::debug;
use num_bigint::BigUint;
use rayon::prelude::*;
use reqwest::{
self,
header::{ACCEPT, CONTENT_TYPE},
StatusCode as ResponseStatusCode,
};
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use solana_sdk::signer::keypair::Keypair;
use std::{
collections::HashMap,
fmt::Write,
path::{Path, PathBuf},
str::FromStr,
};
use tokio::{
fs,
time::{sleep, Duration},
};
use url::Url;
pub mod bundle;
pub mod commands;
pub mod crypto;
pub mod error;
pub mod merkle;
pub mod solana;
pub mod status;
pub mod transaction;
pub mod utils;
use bundle::DataItem;
use error::Error;
use merkle::{generate_data_root, generate_leaves, resolve_proofs};
use solana::{create_sol_transaction, get_sol_ar_signature, SigResponse, FLOOR, RATE};
use status::{BundleStatus, Filterable, Status, StatusCode};
use transaction::{Base64, Chunk, FromUtf8Strs, Tag, ToItems, Transaction};
const VERSION: &'static str = env!("CARGO_PKG_VERSION");
/// Winstons are a sub unit of the native Arweave network token, AR. There are 10<sup>12</sup> Winstons per AR.
pub const WINSTONS_PER_AR: u64 = 1_000_000_000_000;
/// Block size used for pricing calculations = 256 KB
pub const BLOCK_SIZE: u64 = 1024 * 256;
/// Maximum data size to send to `tx/` endpoint. Sent to `chunk/` endpoint above this.
pub const MAX_TX_DATA: u64 = 10_000_000;
/// Multiplier applied to the buffer argument from the cli to determine the maximum number
/// of simultaneous request to the `chunk/ endpoint`.
pub const CHUNKS_BUFFER_FACTOR: usize = 20;
/// Number of times to retry posting chunks if not successful.
pub const CHUNKS_RETRIES: u16 = 10;
/// Number of seconds to wait between retying to post a failed chunk.
pub const CHUNKS_RETRY_SLEEP: u64 = 1;
//=========================
// Streams
//=========================
/// Uploads a stream of bundles from [`Vec<PathsChunk>`]s.
///
/// Buffers bundles if using the tx/ endpoint, else buffers chunks with bundles processed serially.
pub fn upload_bundles_stream<'a>(
arweave: &'a Arweave,
paths_chunks: Vec<PathsChunk>,
tags: Vec<Tag<String>>,
price_terms: (u64, u64),
buffer: usize,
) -> impl Stream<Item = Result<BundleStatus, Error>> + 'a {
let bundle_size = paths_chunks[0].1;
let (bundles_buffer, chunks_buffer) = if bundle_size > MAX_TX_DATA {
(1, buffer * CHUNKS_BUFFER_FACTOR)
} else {
(buffer, 1)
};
stream::iter(paths_chunks)
.map(move |p| {
arweave.post_bundle_transaction_from_file_paths(
p,
tags.clone(),
price_terms,
chunks_buffer,
)
})
.buffer_unordered(bundles_buffer)
}
/// Queries network and updates locally stored [`BundleStatus`] structs.
pub fn update_bundle_statuses_stream<'a, IP>(
arweave: &'a Arweave,
paths_iter: IP,
buffer: usize,
) -> impl Stream<Item = Result<BundleStatus, Error>> + 'a
where
IP: Iterator<Item = PathBuf> + Send + Sync + 'a,
{
stream::iter(paths_iter)
.map(move |p| arweave.update_bundle_status(p))
.buffer_unordered(buffer)
}
/// Uploads a stream of bundles from [`Vec<PathsChunk>`]s, paying with SOL.
pub fn upload_bundles_stream_with_sol<'a>(
arweave: &'a Arweave,
paths_chunks: Vec<PathsChunk>,
tags: Vec<Tag<String>>,
price_terms: (u64, u64),
buffer: usize,
solana_url: Url,
sol_ar_url: Url,
from_keypair: &'a Keypair,
) -> impl Stream<Item = Result<BundleStatus, Error>> + 'a {
let bundle_size = paths_chunks[0].1;
let (bundles_buffer, chunks_buffer) = if bundle_size > MAX_TX_DATA {
(1, buffer * CHUNKS_BUFFER_FACTOR)
} else {
(buffer, 1)
};
stream::iter(paths_chunks)
.map(move |p| {
arweave.post_bundle_transaction_from_file_paths_with_sol(
p,
tags.clone(),
price_terms,
chunks_buffer,
solana_url.clone(),
sol_ar_url.clone(),
from_keypair,
)
})
.buffer_unordered(bundles_buffer)
}
/// Uploads a stream of chunks from [`Vec<Chunk>`]s.
pub fn upload_transaction_chunks_stream<'a>(
arweave: &'a Arweave,
signed_transaction: Transaction,
buffer: usize,
) -> impl Stream<Item = Result<usize, Error>> + 'a {
stream::iter(0..signed_transaction.chunks.len())
.map(move |i| {
let chunk = signed_transaction.get_chunk(i).unwrap();
arweave.post_chunk_with_retries(chunk)
})
.buffer_unordered(buffer)
}
/// Uploads files matching glob pattern, returning a stream of [`Status`] structs.
pub fn upload_files_stream<'a, IP>(
arweave: &'a Arweave,
paths_iter: IP,
tags: Option<Vec<Tag<Base64>>>,
log_dir: Option<PathBuf>,
last_tx: Option<Base64>,
price_terms: (u64, u64),
buffer: usize,
) -> impl Stream<Item = Result<Status, Error>> + 'a
where
IP: Iterator<Item = PathBuf> + Send + Sync + 'a,
{
stream::iter(paths_iter)
.map(move |p| {
arweave.upload_file_from_path(
p,
log_dir.clone(),
tags.clone(),
last_tx.clone(),
price_terms,
)
})
.buffer_unordered(buffer)
}
/// Uploads files matching glob pattern, returning a stream of [`Status`] structs, paying with SOL.
pub fn upload_files_with_sol_stream<'a, IP>(
arweave: &'a Arweave,
paths_iter: IP,
tags: Option<Vec<Tag<Base64>>>,
log_dir: Option<PathBuf>,
last_tx: Option<Base64>,
price_terms: (u64, u64),
solana_url: Url,
sol_ar_url: Url,
from_keypair: &'a Keypair,
buffer: usize,
) -> impl Stream<Item = Result<Status, Error>> + 'a
where
IP: Iterator<Item = PathBuf> + Send + Sync + 'a,
{
stream::iter(paths_iter)
.map(move |p| {
arweave.upload_file_from_path_with_sol(
p,
log_dir.clone(),
tags.clone(),
last_tx.clone(),
price_terms,
solana_url.clone(),
sol_ar_url.clone(),
from_keypair,
)
})
.buffer_unordered(buffer)
}
/// Queries network and updates locally stored [`Status`] structs.
pub fn update_statuses_stream<'a, IP>(
arweave: &'a Arweave,
paths_iter: IP,
log_dir: PathBuf,
buffer: usize,
) -> impl Stream<Item = Result<Status, Error>> + 'a
where
IP: Iterator<Item = PathBuf> + Send + Sync + 'a,
{
stream::iter(paths_iter)
.map(move |p| arweave.update_status(p, log_dir.clone()))
.buffer_unordered(buffer)
}
//=========================
// Helpers
//=========================
#[derive(Serialize, Deserialize, Debug)]
pub struct OraclePrice {
pub arweave: OraclePricePair,
pub solana: OraclePricePair,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct OraclePricePair {
pub usd: f32,
}
/// Tuple struct includes two elements: chunk of paths and aggregatge data size of paths.
#[derive(Clone, Debug)]
pub struct PathsChunk(Vec<PathBuf>, u64);
/// Used in updating [`BundleStatus`]s to determine whether a file stem includes a valid transaction id.
pub fn file_stem_is_valid_txid(file_path: &PathBuf) -> bool {
match Base64::from_str(file_path.file_stem().unwrap().to_str().unwrap()) {
Ok(txid) => match txid.0.len() {
32 => true,
_ => false,
},
Err(_) => false,
}
}
//=========================
// Arweave
//=========================
/// Struct with methods for interacting with the Arweave network.
pub struct Arweave {
pub name: String,
pub units: String,
pub base_url: Url,
pub crypto: crypto::Provider,
}
impl Default for Arweave {
fn default() -> Self {
Self {
name: String::from("arweave"),
units: String::from("winstons"),
base_url: Url::from_str("https://arweave.net/").unwrap(),
crypto: crypto::Provider::default(),
}
}
}
impl Arweave {
pub async fn from_keypair_path(keypair_path: PathBuf, base_url: Url) -> Result<Arweave, Error> {
let crypto = crypto::Provider::from_keypair_path(keypair_path).await?;
let arweave = Arweave {
base_url,
crypto,
..Default::default()
};
Ok(arweave)
}
pub fn from_keypair_path_sync(keypair_path: PathBuf, base_url: Url) -> Result<Arweave, Error> {
let crypto = crypto::Provider::from_keypair_path_sync(keypair_path)?;
let arweave = Arweave {
base_url,
crypto,
..Default::default()
};
Ok(arweave)
}
//-------------------------
// Get Request
//-------------------------
/// Get pending network transaction count.
pub async fn get_pending_count(&self) -> Result<usize, Error> {
let url = self.base_url.join("tx/pending")?;
let tx_ids: Vec<String> = reqwest::get(url).await?.json().await?;
Ok(tx_ids.len())
}
/// Returns price of uploading data to the network in winstons and USD per AR and USD per SOL
/// as a BigUint with two decimals.
pub async fn get_price(&self, bytes: &u64) -> Result<(BigUint, BigUint, BigUint), Error> {
let url = self.base_url.join("price/")?.join(&bytes.to_string())?;
let winstons_per_bytes = reqwest::get(url)
.await
.map_err(|e| Error::ArweaveGetPriceError(e))?
.json::<u64>()
.await?;
let winstons_per_bytes = BigUint::from(winstons_per_bytes);
let oracle_url =
"https://api.coingecko.com/api/v3/simple/price?ids=arweave,solana&vs_currencies=usd";
let prices = reqwest::get(oracle_url)
.await
.map_err(|e| Error::OracleGetPriceError(e))?
.json::<OraclePrice>()
.await?;
let usd_per_ar: BigUint = BigUint::from((prices.arweave.usd * 100.0).floor() as u32);
let usd_per_sol: BigUint = BigUint::from((prices.solana.usd * 100.0).floor() as u32);
Ok((winstons_per_bytes, usd_per_ar, usd_per_sol))
}
/// Gets base and incremental prices for a 256 KB block of data.
pub async fn get_price_terms(&self, reward_mult: f32) -> Result<(u64, u64), Error> {
let (prices1, prices2) = try_join(
self.get_price(&(256 * 1024)),
self.get_price(&(256 * 1024 * 2)),
)
.await?;
let base = (prices1.0.to_u64_digits()[0] as f32 * reward_mult) as u64;
let incremental = (prices2.0.to_u64_digits()[0] as f32 * reward_mult) as u64 - &base;
Ok((base, incremental))
}
/// Gets transaction from the network.
pub async fn get_transaction(&self, id: &Base64) -> Result<Transaction, Error> {
let url = self.base_url.join("tx/")?.join(&id.to_string())?;
let resp = reqwest::get(url).await?.json::<Transaction>().await?;
Ok(resp)
}
/// Returns the balance of the wallet.
pub async fn get_wallet_balance(
&self,
wallet_address: Option<String>,
) -> Result<BigUint, Error> {
let wallet_address = if let Some(wallet_address) = wallet_address {
wallet_address
} else {
self.crypto.wallet_address()?.to_string()
};
let url = self
.base_url
.join(&format!("wallet/{}/balance", &wallet_address))?;
let winstons = reqwest::get(url).await?.json::<u64>().await?;
Ok(BigUint::from(winstons))
}
//-------------------------
// Bundle
//-------------------------
pub fn chunk_file_paths<IP>(
&self,
paths_iter: IP,
data_size: u64,
) -> Result<Vec<PathsChunk>, Error>
where
IP: Iterator<Item = PathBuf> + Send,
{
let (mut paths_chunks, last_chunk, last_data_len) = paths_iter.fold(
(Vec::<PathsChunk>::new(), Vec::<PathBuf>::new(), 0u64),
|(mut ip, mut i, data_len), p| {
let p_len = p.metadata().unwrap().len();
if data_len + p_len > data_size {
ip.push(PathsChunk(i, data_len));
(ip, vec![p], p_len)
} else {
i.push(p);
(ip, i, data_len + p_len)
}
},
);
if last_chunk.len() > 0 {
paths_chunks.push(PathsChunk(last_chunk, last_data_len));
}
Ok(paths_chunks)
}
pub fn create_bundle_from_data_items(
&self,
data_items: Vec<(DataItem, Status)>,
) -> Result<(Vec<u8>, Value), Error> {
let data_items_len = (data_items.len()) as u64;
let ((headers, binaries), statuses): ((Vec<Vec<u8>>, Vec<Vec<u8>>), Vec<Status>) =
data_items
.into_iter()
.map(|(d, s)| (d.to_bundle_item().unwrap(), s))
.unzip();
let manifest = self.create_manifest(statuses)?;
let binary: Vec<_> = data_items_len
.to_le_bytes()
.into_par_iter()
.chain([0u8; 24].into_par_iter())
.chain(headers.into_par_iter().flatten())
.chain(binaries.into_par_iter().flatten())
.collect();
Ok((binary, manifest))
}
pub async fn create_bundle_transaction_from_file_paths(
&self,
paths_iter: Vec<PathBuf>,
tags: Vec<Tag<String>>,
price_terms: (u64, u64),
) -> Result<(Transaction, Value), Error> {
let data_items = self
.create_data_items_from_file_paths(paths_iter, tags)
.await?;
let (bundle, manifest_object) = self.create_bundle_from_data_items(data_items)?;
let other_tags = Some(vec![
Tag::<Base64>::from_utf8_strs("Bundle-Format", "binary")?,
Tag::<Base64>::from_utf8_strs("Bundle-Version", "2.0.0")?,
]);
let transaction = self
.create_transaction(bundle, other_tags, None, price_terms, true)
.await?;
Ok((transaction, manifest_object))
}
// Create [`data_item::DataItem`] for bundle.
pub fn create_data_item(
&self,
data: Vec<u8>,
mut tags: Vec<Tag<String>>,
auto_content_tag: bool,
) -> Result<DataItem, Error> {
tags.push(Tag::<String>::from_utf8_strs(
"User-Agent",
&format!("arloader/{}", VERSION),
)?);
// Get content type from [magic numbers](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types)
// and include additional tags if any.
if auto_content_tag {
let content_type = if let Some(kind) = infer::get(&data) {
kind.mime_type()
} else {
"application/octet-stream"
};
tags.push(Tag::<String>::from_utf8_strs("Content-Type", content_type)?)
}
// let mut anchor = Base64(Vec::with_capacity(32));
// self.crypto.fill_rand(&mut anchor.0)?;
Ok(DataItem {
data: Base64(data),
tags,
// anchor,
..DataItem::default()
})
}
pub async fn create_data_item_from_file_path(
&self,
file_path: PathBuf,
mut tags: Vec<Tag<String>>,
) -> Result<(DataItem, Status), Error> {
let mut auto_content_tag = true;
let mut status_content_type = mime_guess::mime::OCTET_STREAM.to_string();
if let Some(content_type) = mime_guess::from_path(file_path.clone()).first() {
status_content_type = content_type.to_string();
auto_content_tag = false;
let content_tag: Tag<String> =
Tag::from_utf8_strs("Content-Type", &content_type.to_string())?;
tags.push(content_tag);
}
let data = fs::read(&file_path).await?;
let data_item = self.create_data_item(data, tags, auto_content_tag)?;
let data_item = self.sign_data_item(data_item)?;
let status = Status {
id: data_item.id.clone(),
file_path: Some(file_path),
content_type: status_content_type,
..Status::default()
};
Ok((data_item, status))
}
pub async fn create_data_items_from_file_paths(
&self,
paths: Vec<PathBuf>,
tags: Vec<Tag<String>>,
) -> Result<Vec<(DataItem, Status)>, Error> {
try_join_all(
paths
.into_iter()
.map(|p| self.create_data_item_from_file_path(p, tags.clone())),
)
.await
}
// Tested here instead of data_item to verify signature as well - crytpo on data_item.
pub fn deserialize_bundle(&self, bundle: Vec<u8>) -> Result<Vec<DataItem>, Error> {
let mut bundle_iter = bundle.into_iter();
let result = [(); 8].map(|_| bundle_iter.next().unwrap());
let number_of_data_items = u64::from_le_bytes(result) as usize;
(0..24).for_each(|_| {
bundle_iter.next().unwrap();
});
// Parse headers.
let mut bytes_lens = Vec::<u64>::with_capacity(number_of_data_items);
let mut ids = vec![Vec::<u8>::with_capacity(32); number_of_data_items];
(0..number_of_data_items).for_each(|i| {
let result = [(); 8].map(|_| bundle_iter.next().unwrap());
bytes_lens.push(u64::from_le_bytes(result));
(0..24).for_each(|_| {
bundle_iter.next().unwrap();
});
(0..32).for_each(|_| {
ids[i].push(bundle_iter.next().unwrap());
});
});
// Parse data_items - data_item verified during deserialization - signatures verified
// TODO: verify signature against data_item id.
let mut bytes_lens_iter = bytes_lens.into_iter();
let mut ids_iter = ids.into_iter();
let data_items: Result<Vec<DataItem>, _> = (0..number_of_data_items)
.map(|_| {
let bytes_len = bytes_lens_iter.next().unwrap() as usize;
let mut bytes_vec = Vec::<u8>::with_capacity(bytes_len);
(0..bytes_len).for_each(|_| bytes_vec.push(bundle_iter.next().unwrap()));
let mut data_item = DataItem::deserialize(bytes_vec)?;
let deep_hash = self
.crypto
.deep_hash(data_item.to_deep_hash_item()?)
.unwrap();
self.crypto
.verify(&data_item.signature.0, &deep_hash)
.unwrap();
data_item.id.0 = ids_iter.next().unwrap();
Ok(data_item)
})
.collect();
data_items
}
pub async fn post_bundle_transaction_from_file_paths(
&self,
paths_chunk: PathsChunk,
tags: Vec<Tag<String>>,
price_terms: (u64, u64),
buffer: usize,
) -> Result<BundleStatus, Error> {
let number_of_files = paths_chunk.0.len() as u64;
let data_items = self
.create_data_items_from_file_paths(paths_chunk.0, tags)
.await?;
let (bundle, manifest) = self.create_bundle_from_data_items(data_items)?;
let other_tags = Some(vec![
Tag::<Base64>::from_utf8_strs("Bundle-Format", "binary")?,
Tag::<Base64>::from_utf8_strs("Bundle-Version", "2.0.0")?,
]);
let transaction = self
.create_transaction(bundle, other_tags, None, price_terms, true)
.await?;
let signed_transaction = self.sign_transaction(transaction)?;
let (id, reward) = if paths_chunk.1 > MAX_TX_DATA {
self.post_transaction_chunks(signed_transaction, buffer)
.await?
} else {
self.post_transaction(&signed_transaction).await?
};
let status = BundleStatus {
id,
reward,
number_of_files,
data_size: paths_chunk.1,
file_paths: manifest["paths"].clone(),
..Default::default()
};
Ok(status)
}
pub async fn post_bundle_transaction_from_file_paths_with_sol(
&self,
paths_chunk: PathsChunk,
tags: Vec<Tag<String>>,
price_terms: (u64, u64),
chunks_buffer: usize,
solana_url: Url,
sol_ar_url: Url,
from_keypair: &Keypair,
) -> Result<BundleStatus, Error> {
let number_of_files = paths_chunk.0.len() as u64;
let data_items = self
.create_data_items_from_file_paths(paths_chunk.0, tags)
.await?;
let (bundle, manifest) = self.create_bundle_from_data_items(data_items)?;
let other_tags = Some(vec![
Tag::<Base64>::from_utf8_strs("Bundle-Format", "binary")?,
Tag::<Base64>::from_utf8_strs("Bundle-Version", "2.0.0")?,
]);
let transaction = self
.create_transaction(bundle, other_tags, None, price_terms, true)
.await?;
let (signed_transaction, sig_response): (Transaction, SigResponse) = self
.sign_transaction_with_sol(transaction, solana_url, sol_ar_url, from_keypair)
.await?;
let (id, reward) = if paths_chunk.1 > MAX_TX_DATA {
self.post_transaction_chunks(signed_transaction, chunks_buffer)
.await?
} else {
self.post_transaction(&signed_transaction).await?
};
let status = BundleStatus {
id,
reward,
number_of_files,
data_size: paths_chunk.1,
file_paths: manifest["paths"].clone(),
sol_sig: Some(sig_response),
..Default::default()
};
Ok(status)
}
pub fn sign_data_item(&self, mut data_item: DataItem) -> Result<DataItem, Error> {
data_item.owner = self.crypto.keypair_modulus()?;
let deep_hash_item = data_item.to_deep_hash_item()?;
let deep_hash = self.crypto.deep_hash(deep_hash_item)?;
let signature = self.crypto.sign(&deep_hash)?;
let id = self.crypto.hash_sha256(&signature)?;
data_item.signature = Base64(signature);
data_item.id = Base64(id.to_vec());
Ok(data_item)
}
//-------------------------
// Transaction
//-------------------------
pub async fn create_transaction(
&self,
data: Vec<u8>,
other_tags: Option<Vec<Tag<Base64>>>,
last_tx: Option<Base64>,
price_terms: (u64, u64),
auto_content_tag: bool,
) -> Result<Transaction, Error> {
let mut transaction = self.merklize(data)?;
transaction.owner = self.crypto.keypair_modulus()?;
let mut tags = vec![Tag::<Base64>::from_utf8_strs(
"User-Agent",
&format!("arloader/{}", VERSION),
)?];
// Get content type from [magic numbers](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types)
// and include additional tags if any.
if auto_content_tag {
let content_type = if let Some(kind) = infer::get(&transaction.data.0) {
kind.mime_type()
} else {
"application/octet-stream"
};
tags.push(Tag::<Base64>::from_utf8_strs("Content-Type", content_type)?)
}
// Add other tags if provided.
if let Some(other_tags) = other_tags {
tags.extend(other_tags);
}
transaction.tags = tags;
// Fetch and set last_tx if not provided (primarily for testing).
let last_tx = if let Some(last_tx) = last_tx {
last_tx
} else {
let resp = reqwest::get(self.base_url.join("tx_anchor")?).await?;
debug!("last_tx: {}", resp.status());
let last_tx_str = resp.text().await?;
Base64::from_str(&last_tx_str)?
};
transaction.last_tx = last_tx;
let blocks_len =
transaction.data_size / BLOCK_SIZE + (transaction.data_size % BLOCK_SIZE != 0) as u64;
let reward = price_terms.0 + price_terms.1 * (blocks_len - 1);
transaction.reward = reward;
Ok(transaction)
}
pub async fn create_transaction_from_file_path(
&self,
file_path: PathBuf,
other_tags: Option<Vec<Tag<Base64>>>,
last_tx: Option<Base64>,
price_terms: (u64, u64),
auto_content_tag: bool,
) -> Result<Transaction, Error> {
let data = fs::read(file_path).await?;
self.create_transaction(data, other_tags, last_tx, price_terms, auto_content_tag)
.await
}
pub fn merklize(&self, data: Vec<u8>) -> Result<Transaction, Error> {
let mut chunks = generate_leaves(data.clone(), &self.crypto)?;
let root = generate_data_root(chunks.clone(), &self.crypto)?;
let data_root = Base64(root.id.clone().into_iter().collect());
let mut proofs = resolve_proofs(root, None)?;
// Discard the last chunk & proof if it's zero length.
let last_chunk = chunks.last().unwrap();
if last_chunk.max_byte_range == last_chunk.min_byte_range {
chunks.pop();
proofs.pop();
}
Ok(Transaction {
format: 2,
data_size: data.len() as u64,
data: Base64(data),
data_root,
chunks,
proofs,
..Default::default()
})
}
pub async fn post_chunk(&self, chunk: &Chunk) -> Result<usize, Error> {
let url = self.base_url.join("chunk/")?;
let client = reqwest::Client::new();
client
.post(url)
.json(&chunk)
.header(&ACCEPT, "application/json")
.header(&CONTENT_TYPE, "application/json")
.send()
.await
.map_err(|e| Error::ArweavePostError(e))?;
Ok(chunk.offset)
}
pub async fn post_chunk_with_retries(&self, chunk: Chunk) -> Result<usize, Error> {
let mut retries = 0;
let mut resp = self.post_chunk(&chunk).await;
while retries < CHUNKS_RETRIES {
match resp {
Ok(offset) => return Ok(offset),
Err(_) => {
sleep(Duration::from_secs(CHUNKS_RETRY_SLEEP)).await;
retries += 1;
resp = self.post_chunk(&chunk).await;
}
}
}
resp
}
pub async fn post_transaction(
&self,
signed_transaction: &Transaction,
) -> Result<(Base64, u64), Error> {
if signed_transaction.id.0.is_empty() {
return Err(error::Error::UnsignedTransaction.into());
}
let url = self.base_url.join("tx/")?;
let client = reqwest::Client::new();
let resp = client
.post(url)
.json(&signed_transaction)
.header(&ACCEPT, "application/json")
.header(&CONTENT_TYPE, "application/json")
.send()
.await?;
debug!("post_transaction {:?}", &resp);
assert_eq!(resp.status().as_u16(), 200);
Ok((signed_transaction.id.clone(), signed_transaction.reward))
}
pub async fn post_transaction_chunks(
&self,
signed_transaction: Transaction,
chunks_buffer: usize,
) -> Result<(Base64, u64), Error> {
if signed_transaction.id.0.is_empty() {
return Err(error::Error::UnsignedTransaction.into());
}
let transaction_with_no_data = signed_transaction.clone_with_no_data()?;
let (id, reward) = self.post_transaction(&transaction_with_no_data).await?;
let results: Vec<Result<usize, Error>> =
upload_transaction_chunks_stream(&self, signed_transaction, chunks_buffer)
.collect()
.await;
results.into_iter().collect::<Result<Vec<usize>, Error>>()?;
Ok((id, reward))
}
/// Gets deep hash, signs and sets signature and id.
pub fn sign_transaction(&self, mut transaction: Transaction) -> Result<Transaction, Error> {
let deep_hash_item = transaction.to_deep_hash_item()?;
let deep_hash = self.crypto.deep_hash(deep_hash_item)?;
let signature = self.crypto.sign(&deep_hash)?;
let id = self.crypto.hash_sha256(&signature)?;
transaction.signature = Base64(signature);
transaction.id = Base64(id.to_vec());
Ok(transaction)
}
/// Signs transaction with sol_ar service.
pub async fn sign_transaction_with_sol(
&self,
mut transaction: Transaction,
solana_url: Url,
sol_ar_url: Url,
from_keypair: &Keypair,
) -> Result<(Transaction, SigResponse), Error> {
let lamports = std::cmp::max(&transaction.reward / RATE, FLOOR);
let mut sol_tx = create_sol_transaction(solana_url.clone(), from_keypair, lamports).await?;
let mut resp = get_sol_ar_signature(
sol_ar_url.clone(),
transaction.to_deep_hash_item()?,
sol_tx.clone(),
)
.await;
let mut retries = 0;
while retries < CHUNKS_RETRIES {
match resp {
Ok(_) => {
retries = CHUNKS_RETRIES;
}
Err(_) => {
println!(
"Retrying Solana transaction ({} of {})...",
retries + 1,
CHUNKS_RETRIES
);
retries += 1;
sleep(Duration::from_millis(300)).await;
sol_tx =
create_sol_transaction(solana_url.clone(), from_keypair, lamports).await?;
resp = get_sol_ar_signature(
sol_ar_url.clone(),
transaction.to_deep_hash_item()?,
sol_tx.clone(),
)
.await;
}
}
}
if let Ok(sig_response) = resp {
let sig_response_copy = sig_response.clone();
transaction.signature = sig_response.ar_tx_sig;
transaction.id = sig_response.ar_tx_id;