-
Notifications
You must be signed in to change notification settings - Fork 49
Expand file tree
/
Copy pathoffline.rs
More file actions
2531 lines (2335 loc) · 87.7 KB
/
Copy pathoffline.rs
File metadata and controls
2531 lines (2335 loc) · 87.7 KB
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
//! RGB wallet
//!
//! This module defines the offline methods of the [`Wallet`] structure and all its related data.
use super::*;
pub(crate) const RGB_LIB_DB_NAME: &str = "rgb_lib_db";
const BDK_DB_NAME: &str = "bdk_db";
pub(crate) const KEYCHAIN_RGB_OPRET: u8 = 9;
pub(crate) const KEYCHAIN_RGB_TAPRET: u8 = 10;
pub(crate) const KEYCHAIN_BTC: u8 = 1;
pub(crate) const MEDIA_DIR: &str = "media_files";
const TRANSFERS_DIR: &str = "transfers";
const MIN_BTC_REQUIRED: u64 = 2000;
pub(crate) const NUM_KNOWN_SCHEMAS: usize = 3;
pub(crate) const MAX_TRANSPORT_ENDPOINTS: usize = 3;
pub(crate) const DURATION_RCV_TRANSFER: u32 = 86400;
pub(crate) const ASSET_ID_PREFIX: &str = "rgb:";
pub(crate) const CONSIGNMENT_FILE: &str = "consignment_out";
pub(crate) const SCHEMA_ID_NIA: &str =
"rgb:sch:RDYhMTR!9gv8Y2GLv9UNBEK1hcrCmdLDFk9Qd5fnO8k#brave-dinner-banana";
pub(crate) const SCHEMA_ID_UDA: &str =
"rgb:sch:$$bAmeZTo5kK3RJHgeUr06qG86vQ0ozgtug7Yi9zdZo#korea-trumpet-dexter";
pub(crate) const SCHEMA_ID_CFA: &str =
"rgb:sch:cJjPZfUpkOqIWhpCTqYJtFYzLfz$AB3JNxIEOJZYn28#circus-version-silence";
/// The interface of an RGB asset.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Deserialize, Serialize)]
pub enum AssetIface {
/// RGB20 interface
RGB20,
/// RGB21 interface
RGB21,
/// RGB25 interface
RGB25,
}
impl AssetIface {
pub(crate) fn to_typename(&self) -> TypeName {
let variant = match self {
Self::RGB20 => "Fixed",
Self::RGB21 => "Unique",
Self::RGB25 => "Base",
};
tn!(format!("{self:?}{variant}"))
}
pub(crate) fn get_from_contract_id(
contract_id: ContractId,
runtime: &RgbRuntime,
) -> Result<Self, Error> {
let genesis = runtime.genesis(contract_id)?;
let schema_id = genesis.schema_id.to_string();
Ok(match &schema_id[..] {
SCHEMA_ID_NIA => AssetIface::RGB20,
SCHEMA_ID_UDA => AssetIface::RGB21,
SCHEMA_ID_CFA => AssetIface::RGB25,
_ => return Err(Error::UnknownRgbSchema { schema_id }),
})
}
fn get_asset_details(
&self,
wallet: &Wallet,
asset: &DbAsset,
token: Option<TokenLight>,
transfers: Option<Vec<DbTransfer>>,
asset_transfers: Option<Vec<DbAssetTransfer>>,
batch_transfers: Option<Vec<DbBatchTransfer>>,
colorings: Option<Vec<DbColoring>>,
txos: Option<Vec<DbTxo>>,
medias: Option<Vec<DbMedia>>,
) -> Result<AssetType, Error> {
let media = match &self {
AssetIface::RGB20 | AssetIface::RGB25 => {
let medias = if let Some(m) = medias {
m
} else {
wallet.database.iter_media()?
};
medias
.iter()
.find(|m| Some(m.idx) == asset.media_idx)
.map(|m| Media::from_db_media(m, wallet.get_media_dir()))
}
AssetIface::RGB21 => None,
};
let balance = wallet.database.get_asset_balance(
asset.id.clone(),
transfers,
asset_transfers,
batch_transfers,
colorings,
txos,
)?;
let issued_supply = asset.issued_supply.parse::<u64>().unwrap();
Ok(match &self {
AssetIface::RGB20 => AssetType::AssetNIA(AssetNIA {
asset_id: asset.id.clone(),
asset_iface: self.clone(),
ticker: asset.ticker.clone().unwrap(),
name: asset.name.clone(),
details: asset.details.clone(),
precision: asset.precision,
issued_supply,
timestamp: asset.timestamp,
added_at: asset.added_at,
balance,
media,
}),
AssetIface::RGB21 => AssetType::AssetUDA(AssetUDA {
asset_id: asset.id.clone(),
asset_iface: self.clone(),
details: asset.details.clone(),
ticker: asset.ticker.clone().unwrap(),
name: asset.name.clone(),
precision: asset.precision,
issued_supply,
timestamp: asset.timestamp,
added_at: asset.added_at,
balance,
token,
}),
AssetIface::RGB25 => AssetType::AssetCFA(AssetCFA {
asset_id: asset.id.clone(),
asset_iface: self.clone(),
name: asset.name.clone(),
details: asset.details.clone(),
precision: asset.precision,
issued_supply,
timestamp: asset.timestamp,
added_at: asset.added_at,
balance,
media,
}),
})
}
}
impl From<AssetSchema> for AssetIface {
fn from(x: AssetSchema) -> AssetIface {
match x {
AssetSchema::Nia => AssetIface::RGB20,
AssetSchema::Uda => AssetIface::RGB21,
AssetSchema::Cfa => AssetIface::RGB25,
}
}
}
impl TryFrom<TypeName> for AssetIface {
type Error = Error;
fn try_from(value: TypeName) -> Result<Self, Self::Error> {
match value.to_string().as_str() {
"RGB20Fixed" => Ok(AssetIface::RGB20),
"RGB21Unique" => Ok(AssetIface::RGB21),
"RGB25Base" => Ok(AssetIface::RGB25),
_ => Err(Error::UnknownRgbInterface {
interface: value.to_string(),
}),
}
}
}
/// The bitcoin balances (in sats) for the vanilla and colored wallets.
///
/// The settled balances include the confirmed balance.
/// The future balances also include the immature balance and the untrusted and trusted pending
/// balances.
/// The spendable balances include the settled balance and also the untrusted and trusted pending
/// balances.
#[derive(Clone, Debug, PartialEq, Deserialize, Serialize)]
#[cfg_attr(feature = "camel_case", serde(rename_all = "camelCase"))]
pub struct BtcBalance {
/// Funds that will never hold RGB assets
pub vanilla: Balance,
/// Funds that may hold RGB assets
pub colored: Balance,
}
/// An asset media file.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Deserialize, Serialize)]
#[cfg_attr(feature = "camel_case", serde(rename_all = "camelCase"))]
pub struct Media {
/// Path of the media file
pub file_path: String,
/// Digest of the media file
pub digest: String,
/// Mime type of the media file
pub mime: String,
}
impl Media {
pub(crate) fn get_digest(&self) -> String {
PathBuf::from(&self.file_path)
.file_name()
.unwrap()
.to_string_lossy()
.to_string()
}
pub(crate) fn from_attachment<P: AsRef<Path>>(attachment: &Attachment, media_dir: P) -> Self {
let digest = hex::encode(attachment.digest);
let file_path = media_dir
.as_ref()
.join(&digest)
.to_string_lossy()
.to_string();
Self {
digest,
mime: attachment.ty.to_string(),
file_path,
}
}
pub(crate) fn from_db_media<P: AsRef<Path>>(db_media: &DbMedia, media_dir: P) -> Self {
let digest = db_media.digest.clone();
let file_path = media_dir
.as_ref()
.join(&digest)
.to_string_lossy()
.to_string();
Self {
digest,
mime: db_media.mime.clone(),
file_path,
}
}
}
/// Metadata of an RGB asset.
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
#[cfg_attr(feature = "camel_case", serde(rename_all = "camelCase"))]
pub struct Metadata {
/// Asset interface type
pub asset_iface: AssetIface,
/// Asset schema type
pub asset_schema: AssetSchema,
/// Total issued amount
pub issued_supply: u64,
/// Timestamp of asset genesis
pub timestamp: i64,
/// Asset name
pub name: String,
/// Asset precision
pub precision: u8,
/// Asset ticker
pub ticker: Option<String>,
/// Asset details
pub details: Option<String>,
/// Asset unique token
pub token: Option<Token>,
}
/// A Non-Inflatable Asset.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Deserialize, Serialize)]
#[cfg_attr(feature = "camel_case", serde(rename_all = "camelCase"))]
pub struct AssetNIA {
/// ID of the asset
pub asset_id: String,
/// Asset interface type
pub asset_iface: AssetIface,
/// Ticker of the asset
pub ticker: String,
/// Name of the asset
pub name: String,
/// Details of the asset
pub details: Option<String>,
/// Precision, also known as divisibility, of the asset
pub precision: u8,
/// Total issued amount
pub issued_supply: u64,
/// Timestamp of asset genesis
pub timestamp: i64,
/// Timestamp of asset import
pub added_at: i64,
/// Current balance of the asset
pub balance: Balance,
/// Asset media attachment
pub media: Option<Media>,
}
impl AssetNIA {
pub(crate) fn get_asset_details(
wallet: &Wallet,
asset: &DbAsset,
transfers: Option<Vec<DbTransfer>>,
asset_transfers: Option<Vec<DbAssetTransfer>>,
batch_transfers: Option<Vec<DbBatchTransfer>>,
colorings: Option<Vec<DbColoring>>,
txos: Option<Vec<DbTxo>>,
medias: Option<Vec<DbMedia>>,
) -> Result<AssetNIA, Error> {
match AssetIface::RGB20.get_asset_details(
wallet,
asset,
None,
transfers,
asset_transfers,
batch_transfers,
colorings,
txos,
medias,
)? {
AssetType::AssetNIA(asset) => Ok(asset),
_ => unreachable!("impossible"),
}
}
}
/// Light version of an RGB21 [`Token`], with embedded_media and reserves as booleans.
#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize, Serialize)]
#[cfg_attr(feature = "camel_case", serde(rename_all = "camelCase"))]
pub struct TokenLight {
/// Index of the token
pub index: u32,
/// Ticker of the token
pub ticker: Option<String>,
/// Name of the token
pub name: Option<String>,
/// Details of the token
pub details: Option<String>,
/// Whether the token has an embedded media
pub embedded_media: bool,
/// Token primary media attachment
pub media: Option<Media>,
/// Token extra media attachments
pub attachments: HashMap<u8, Media>,
/// Whether the token has proof of reserves
pub reserves: bool,
}
/// A media embedded in the contract.
#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize, Serialize)]
#[cfg_attr(feature = "camel_case", serde(rename_all = "camelCase"))]
pub struct EmbeddedMedia {
/// Mime of the embedded media
pub mime: String,
/// Bytes of the embedded media (max 16MB)
pub data: Vec<u8>,
}
impl From<RgbEmbeddedMedia> for EmbeddedMedia {
fn from(value: RgbEmbeddedMedia) -> Self {
Self {
mime: value.ty.to_string(),
data: value.data.to_unconfined(),
}
}
}
/// A proof of reserves.
#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize, Serialize)]
#[cfg_attr(feature = "camel_case", serde(rename_all = "camelCase"))]
pub struct ProofOfReserves {
/// Proof of reserves UTXO
pub utxo: Outpoint,
/// Proof bytes
pub proof: Vec<u8>,
}
impl From<RgbProofOfReserves> for ProofOfReserves {
fn from(value: RgbProofOfReserves) -> Self {
Self {
utxo: value.utxo.into(),
proof: value.proof.to_unconfined(),
}
}
}
/// An RGB21 token.
#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize, Serialize)]
#[cfg_attr(feature = "camel_case", serde(rename_all = "camelCase"))]
pub struct Token {
/// Index of the token
pub index: u32,
/// Ticker of the token
pub ticker: Option<String>,
/// Name of the token
pub name: Option<String>,
/// Details of the token
pub details: Option<String>,
/// Embedded media of the token
pub embedded_media: Option<EmbeddedMedia>,
/// Token primary media attachment
pub media: Option<Media>,
/// Token extra media attachments
pub attachments: HashMap<u8, Media>,
/// Proof of reserves of the token
pub reserves: Option<ProofOfReserves>,
}
impl Token {
pub(crate) fn from_token_data<P: AsRef<Path>>(token_data: &TokenData, media_dir: P) -> Self {
Self {
index: token_data.index.into(),
ticker: token_data.ticker.clone().map(Into::into),
name: token_data.name.clone().map(Into::into),
details: token_data.details.clone().map(|d| d.to_string()),
embedded_media: token_data.preview.clone().map(Into::into),
media: token_data
.media
.clone()
.map(|a| Media::from_attachment(&a, &media_dir)),
attachments: token_data
.attachments
.to_unconfined()
.into_iter()
.map(|(i, a)| (i, Media::from_attachment(&a, &media_dir)))
.collect(),
reserves: token_data.reserves.clone().map(Into::into),
}
}
}
/// A Unique Digital Asset.
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
#[cfg_attr(feature = "camel_case", serde(rename_all = "camelCase"))]
pub struct AssetUDA {
/// ID of the asset
pub asset_id: String,
/// Asset interface type
pub asset_iface: AssetIface,
/// Ticker of the asset
pub ticker: String,
/// Name of the asset
pub name: String,
/// Details of the asset
pub details: Option<String>,
/// Precision, also known as divisibility, of the asset
pub precision: u8,
/// Total issued amount
pub issued_supply: u64,
/// Timestamp of asset genesis
pub timestamp: i64,
/// Timestamp of asset import
pub added_at: i64,
/// Current balance of the asset
pub balance: Balance,
/// Asset unique token
pub token: Option<TokenLight>,
}
impl AssetUDA {
pub(crate) fn get_asset_details(
wallet: &Wallet,
asset: &DbAsset,
token: Option<TokenLight>,
transfers: Option<Vec<DbTransfer>>,
asset_transfers: Option<Vec<DbAssetTransfer>>,
batch_transfers: Option<Vec<DbBatchTransfer>>,
colorings: Option<Vec<DbColoring>>,
txos: Option<Vec<DbTxo>>,
) -> Result<AssetUDA, Error> {
match AssetIface::RGB21.get_asset_details(
wallet,
asset,
token,
transfers,
asset_transfers,
batch_transfers,
colorings,
txos,
None,
)? {
AssetType::AssetUDA(asset) => Ok(asset),
_ => unreachable!("impossible"),
}
}
}
/// A Collectible Fungible Asset.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Deserialize, Serialize)]
#[cfg_attr(feature = "camel_case", serde(rename_all = "camelCase"))]
pub struct AssetCFA {
/// ID of the asset
pub asset_id: String,
/// Asset interface type
pub asset_iface: AssetIface,
/// Name of the asset
pub name: String,
/// Details of the asset
pub details: Option<String>,
/// Precision, also known as divisibility, of the asset
pub precision: u8,
/// Total issued amount
pub issued_supply: u64,
/// Timestamp of asset genesis
pub timestamp: i64,
/// Timestamp of asset import
pub added_at: i64,
/// Current balance of the asset
pub balance: Balance,
/// Asset media attachment
pub media: Option<Media>,
}
impl AssetCFA {
pub(crate) fn get_asset_details(
wallet: &Wallet,
asset: &DbAsset,
transfers: Option<Vec<DbTransfer>>,
asset_transfers: Option<Vec<DbAssetTransfer>>,
batch_transfers: Option<Vec<DbBatchTransfer>>,
colorings: Option<Vec<DbColoring>>,
txos: Option<Vec<DbTxo>>,
medias: Option<Vec<DbMedia>>,
) -> Result<AssetCFA, Error> {
match AssetIface::RGB25.get_asset_details(
wallet,
asset,
None,
transfers,
asset_transfers,
batch_transfers,
colorings,
txos,
medias,
)? {
AssetType::AssetCFA(asset) => Ok(asset),
_ => unreachable!("impossible"),
}
}
}
enum AssetType {
AssetNIA(AssetNIA),
AssetUDA(AssetUDA),
AssetCFA(AssetCFA),
}
/// List of RGB assets, grouped by asset schema.
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
#[cfg_attr(feature = "camel_case", serde(rename_all = "camelCase"))]
pub struct Assets {
/// List of NIA assets
pub nia: Option<Vec<AssetNIA>>,
/// List of UDA assets
pub uda: Option<Vec<AssetUDA>>,
/// List of CFA assets
pub cfa: Option<Vec<AssetCFA>>,
}
/// A balance.
///
/// This structure is used both for RGB assets and BTC balances (in sats). When used for a BTC
/// balance it can be used both for the vanilla wallet and the colored wallet.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Deserialize, Serialize)]
#[cfg_attr(feature = "camel_case", serde(rename_all = "camelCase"))]
pub struct Balance {
/// Settled balance, based on operations that have reached the final status
pub settled: u64,
/// Future balance, including settled operations plus ones are not yet finalized
pub future: u64,
/// Spendable balance, only including balance that can actually be spent. It's a subset of the
/// settled balance. For the RGB balance this excludes the allocations on UTXOs related to
/// pending operations
pub spendable: u64,
}
/// Data to receive an RGB transfer.
#[derive(Clone, Debug, Deserialize, Serialize)]
#[cfg_attr(feature = "camel_case", serde(rename_all = "camelCase"))]
pub struct ReceiveData {
/// Invoice string
pub invoice: String,
/// ID of the receive operation (blinded UTXO or Bitcoin script)
pub recipient_id: String,
/// Expiration of the receive operation
pub expiration_timestamp: Option<i64>,
/// Batch transfer idx
pub batch_transfer_idx: i32,
}
/// RGB recipient information used to be paid
#[derive(Clone, Debug, Deserialize, Serialize)]
#[cfg_attr(feature = "camel_case", serde(rename_all = "camelCase"))]
pub struct RecipientInfo {
/// Recipient ID
pub recipient_id: String,
/// Recipient type
pub recipient_type: RecipientType,
/// Recipient network
pub network: BitcoinNetwork,
}
impl RecipientInfo {
/// Builds a new [`RecipientInfo`] from the provided string, checking that it is valid.
pub fn new(recipient_id: String) -> Result<Self, Error> {
let xchainnet_beneficiary = XChainNet::<Beneficiary>::from_str(&recipient_id)
.map_err(|_| Error::InvalidRecipientID)?;
let recipient_type = match xchainnet_beneficiary.into_inner() {
Beneficiary::WitnessVout(_) => RecipientType::Witness,
Beneficiary::BlindedSeal(_) => RecipientType::Blind,
};
Ok(Self {
recipient_id,
recipient_type,
network: xchainnet_beneficiary.chain_network().try_into()?,
})
}
}
/// An RGB transport endpoint.
#[derive(Clone, Debug, Deserialize, Serialize)]
#[cfg_attr(feature = "camel_case", serde(rename_all = "camelCase"))]
pub struct TransportEndpoint {
/// Endpoint address
pub endpoint: String,
/// Endpoint transport type
pub transport_type: TransportType,
}
impl TransportEndpoint {
/// Builds a new [`TransportEndpoint::endpoint`] from the provided string, checking that it is
/// valid.
pub fn new(transport_endpoint: String) -> Result<Self, Error> {
let rgb_transport = RgbTransport::from_str(&transport_endpoint)?;
TransportEndpoint::try_from(rgb_transport)
}
/// Return the transport type of this transport endpoint.
pub fn transport_type(&self) -> TransportType {
self.transport_type
}
}
impl TryFrom<RgbTransport> for TransportEndpoint {
type Error = Error;
fn try_from(x: RgbTransport) -> Result<Self, Self::Error> {
match x {
RgbTransport::JsonRpc { tls, host } => Ok(TransportEndpoint {
endpoint: format!("http{}://{host}", if tls { "s" } else { "" }),
transport_type: TransportType::JsonRpc,
}),
_ => Err(Error::UnsupportedTransportType),
}
}
}
/// Supported database types.
#[derive(Clone, Debug, Deserialize, Serialize)]
pub enum DatabaseType {
/// A SQLite database
Sqlite,
}
/// A bitcoin address.
#[derive(Clone, Debug, Deserialize, Serialize)]
#[cfg_attr(feature = "camel_case", serde(rename_all = "camelCase"))]
pub struct Address {
/// The bitcoin address string
address_string: String,
/// The bitcoin network of the address
bitcoin_network: BitcoinNetwork,
}
impl Address {
/// Parse the provided `address_string`.
/// Throws an error if the provided string is not a valid bitcoin address for the given
/// network.
pub fn new(address_string: String, bitcoin_network: BitcoinNetwork) -> Result<Self, Error> {
let decoded = BtcAddress::from_str(&address_string).map_err(|e| Error::InvalidAddress {
details: e.to_string(),
})?;
if !decoded.is_valid_for_network(bitcoin_network.into()) {
return Err(Error::InvalidAddress {
details: s!("address for wrong network"),
});
}
Ok(Address {
address_string,
bitcoin_network,
})
}
}
/// An RGB invoice.
#[derive(Clone, Debug, Deserialize, Serialize)]
#[cfg_attr(feature = "camel_case", serde(rename_all = "camelCase"))]
pub struct Invoice {
/// The RGB invoice string
invoice_string: String,
/// The data of the RGB invoice
pub(crate) invoice_data: InvoiceData,
}
impl Invoice {
/// Parse the provided `invoice_string`.
/// Throws an error if the provided string is not a valid RGB invoice.
pub fn new(invoice_string: String) -> Result<Self, Error> {
let decoded = RgbInvoice::from_str(&invoice_string).map_err(|e| Error::InvalidInvoice {
details: e.to_string(),
})?;
let asset_id = decoded.contract.map(|cid| cid.to_string());
let amount = match decoded.owned_state {
InvoiceState::Amount(v) => Some(v.value()),
_ => None,
};
let recipient_id = decoded.beneficiary.to_string();
let asset_iface = if let Some(iface) = decoded.iface {
Some(AssetIface::try_from(iface)?)
} else {
None
};
let transport_endpoints: Vec<String> =
decoded.transports.iter().map(|t| t.to_string()).collect();
let layer_1 = decoded.beneficiary.layer1();
let network = match layer_1 {
Layer1::Bitcoin => decoded.beneficiary.chain_network().try_into().unwrap(),
_ => {
return Err(Error::UnsupportedLayer1 {
layer_1: layer_1.to_string(),
})
}
};
let invoice_data = InvoiceData {
recipient_id,
asset_iface,
asset_id,
amount,
expiration_timestamp: decoded.expiry,
transport_endpoints,
network,
};
Ok(Invoice {
invoice_string,
invoice_data,
})
}
/// Parse the provided `invoice_data`.
/// Throws an error if the provided data is invalid.
pub fn from_invoice_data(invoice_data: InvoiceData) -> Result<Self, Error> {
let beneficiary = XChainNet::<Beneficiary>::from_str(&invoice_data.recipient_id)
.map_err(|_| Error::InvalidRecipientID)?
.into_inner();
let network: ChainNet = invoice_data.network.into();
let beneficiary = XChainNet::with(network, beneficiary);
let mut invoice_builder = RgbInvoiceBuilder::new(beneficiary);
if let Some(asset_iface) = &invoice_data.asset_iface {
invoice_builder = invoice_builder.set_interface(asset_iface.to_typename());
}
if let Some(cid) = &invoice_data.asset_id.clone() {
let contract_id = ContractId::from_str(cid).map_err(|_| Error::InvalidAssetID {
asset_id: cid.clone(),
})?;
invoice_builder = invoice_builder.set_contract(contract_id);
}
for transport in &invoice_data.transport_endpoints {
invoice_builder = invoice_builder
.add_transport(transport)
.map_err(|(_, e)| e)?;
}
if let Some(amount) = &invoice_data.amount {
invoice_builder = invoice_builder.set_amount_raw(*amount);
}
if let Some(expiry) = &invoice_data.expiration_timestamp {
invoice_builder = invoice_builder.set_expiry_timestamp(*expiry);
}
let invoice = invoice_builder.finish();
let invoice_string = invoice.to_string();
Ok(Invoice {
invoice_string,
invoice_data,
})
}
/// Return the data associated with this [`Invoice`].
pub fn invoice_data(&self) -> InvoiceData {
self.invoice_data.clone()
}
/// Return the string associated with this [`Invoice`].
pub fn invoice_string(&self) -> String {
self.invoice_string.clone()
}
}
/// The data of an RGB invoice.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Deserialize, Serialize)]
#[cfg_attr(feature = "camel_case", serde(rename_all = "camelCase"))]
pub struct InvoiceData {
/// ID of the receive operation (blinded UTXO or Bitcoin script)
pub recipient_id: String,
/// RGB interface
pub asset_iface: Option<AssetIface>,
/// RGB asset ID
pub asset_id: Option<String>,
/// RGB amount
pub amount: Option<u64>,
/// Bitcoin network
pub network: BitcoinNetwork,
/// Invoice expiration
pub expiration_timestamp: Option<i64>,
/// Transport endpoints
pub transport_endpoints: Vec<String>,
}
/// Data for operations that require the wallet to be online.
///
/// Methods not requiring an `Online` object don't need network access and can be performed
/// offline. Methods taking an optional `Online` will operate offline when it's missing and will
/// use local data only.
///
/// <div class="warning">This should not be manually constructed but should be obtained from the
/// [`Wallet::go_online`] method.</div>
#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
#[cfg_attr(feature = "camel_case", serde(rename_all = "camelCase"))]
pub struct Online {
/// Unique ID for this object
pub id: u64,
/// URL of the indexer server to be used for online operations
pub indexer_url: String,
}
/// Bitcoin transaction outpoint.
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, Deserialize, Serialize)]
#[cfg_attr(feature = "camel_case", serde(rename_all = "camelCase"))]
pub struct Outpoint {
/// ID of the transaction
pub txid: String,
/// Output index
pub vout: u32,
}
impl fmt::Display for Outpoint {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
write!(fmt, "{}:{}", self.txid, self.vout)
}
}
impl From<OutPoint> for Outpoint {
fn from(x: OutPoint) -> Outpoint {
Outpoint {
txid: x.txid.to_string(),
vout: x.vout,
}
}
}
impl From<RgbOutpoint> for Outpoint {
fn from(x: RgbOutpoint) -> Outpoint {
Outpoint {
txid: x.txid.to_string(),
vout: x.vout.into_u32(),
}
}
}
impl From<DbTxo> for Outpoint {
fn from(x: DbTxo) -> Outpoint {
Outpoint {
txid: x.txid,
vout: x.vout,
}
}
}
impl From<Outpoint> for OutPoint {
fn from(x: Outpoint) -> OutPoint {
OutPoint::from_str(&x.to_string()).expect("outpoint should be parsable")
}
}
impl From<Outpoint> for RgbOutpoint {
fn from(x: Outpoint) -> RgbOutpoint {
RgbOutpoint::new(RgbTxid::from_str(&x.txid).unwrap(), x.vout)
}
}
/// A recipient of an RGB transfer.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Deserialize, Serialize)]
#[cfg_attr(feature = "camel_case", serde(rename_all = "camelCase"))]
pub struct Recipient {
/// Recipient ID
pub recipient_id: String,
/// Witness data (to be provided only with a witness recipient)
pub witness_data: Option<WitnessData>,
/// RGB amount
#[serde(deserialize_with = "from_str_or_number_mandatory")]
pub amount: u64,
/// Transport endpoints
pub transport_endpoints: Vec<String>,
}
/// The information needed to receive RGB assets in witness mode.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Deserialize, Serialize)]
#[cfg_attr(feature = "camel_case", serde(rename_all = "camelCase"))]
pub struct WitnessData {
/// The Bitcoin amount (in sats) to send to the recipient
#[serde(deserialize_with = "from_str_or_number_mandatory")]
pub amount_sat: u64,
/// An optional blinding
#[serde(deserialize_with = "from_str_or_number_optional")]
pub blinding: Option<u64>,
}
/// An RGB allocation.
#[derive(Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Deserialize, Serialize)]
#[cfg_attr(feature = "camel_case", serde(rename_all = "camelCase"))]
pub struct RgbAllocation {
/// Asset ID
pub asset_id: Option<String>,
/// RGB amount
pub amount: u64,
/// Defines if the allocation is settled, meaning it refers to a transfer in the
/// [`TransferStatus::Settled`] status
pub settled: bool,
}
impl From<LocalRgbAllocation> for RgbAllocation {
fn from(x: LocalRgbAllocation) -> RgbAllocation {
RgbAllocation {
asset_id: x.asset_id.clone(),
amount: x.amount,
settled: x.settled(),
}
}
}
/// A Bitcoin transaction.
#[derive(Clone, Debug, Deserialize, Serialize)]
#[cfg_attr(feature = "camel_case", serde(rename_all = "camelCase"))]
pub struct Transaction {
/// Type of transaction
pub transaction_type: TransactionType,
/// Transaction ID
pub txid: String,
/// Received value (in sats), computed as the sum of owned output amounts included in this
/// transaction
pub received: u64,
/// Sent value (in sats), computed as the sum of owned input amounts included in this
/// transaction
pub sent: u64,
/// Fee value (in sats) if transaction is confirmed
pub fee: Option<u64>,
/// Height and Unix timestamp of the block containing the transaction if confirmed, `None` if
/// unconfirmed
pub confirmation_time: Option<BlockTime>,
}
/// The type of a transaction.
#[derive(Clone, Debug, Deserialize, Serialize)]
pub enum TransactionType {
/// Transaction used to perform an RGB send
RgbSend,
/// Transaction used to drain the RGB wallet
Drain,
/// Transaction used to create UTXOs
CreateUtxos,
/// Transaction not created by rgb-lib directly
User,
}
/// An RGB transfer.
#[derive(Clone, Debug, Deserialize, Serialize)]
#[cfg_attr(feature = "camel_case", serde(rename_all = "camelCase"))]
pub struct Transfer {
/// ID of the transfer
pub idx: i32,
/// ID of the batch transfer containing this transfer
pub batch_transfer_idx: i32,
/// Timestamp of the transfer creation
pub created_at: i64,
/// Timestamp of the transfer last update
pub updated_at: i64,
/// Status of the transfer
pub status: TransferStatus,
/// Amount in RGB unit (not considering precision)
pub amount: u64,
/// Type of the transfer
pub kind: TransferKind,
/// ID of the Bitcoin transaction anchoring the transfer
pub txid: Option<String>,
/// Recipient ID (blinded UTXO or Bitcoin script) of an incoming transfer
pub recipient_id: Option<String>,
/// UTXO of an incoming transfer
pub receive_utxo: Option<Outpoint>,
/// Change UTXO of an outgoing transfer
pub change_utxo: Option<Outpoint>,
// before to branch issue37