forked from everx-labs/ever-block
-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathmessages.rs
More file actions
1984 lines (1752 loc) · 59.4 KB
/
Copy pathmessages.rs
File metadata and controls
1984 lines (1752 loc) · 59.4 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
/*
* Copyright 2018-2020 TON DEV SOLUTIONS LTD.
*
* Licensed under the SOFTWARE EVALUATION License (the "License"); you may not use
* this file except in compliance with the License.
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific TON DEV software governing permissions and
* limitations under the License.
*/
use crate::GetRepresentationHash;
use crate::{
blocks::Block,
define_HashmapE,
error::BlockError,
hashmapaug::HashmapAugType,
merkle_proof::MerkleProof,
shard::MASTERCHAIN_ID,
types::{AddSub, CurrencyCollection, Grams, Number5, Number9, UnixTime32},
Deserializable, MaybeDeserialize, MaybeSerialize, Serializable,
};
use std::fmt;
use std::str::FromStr;
use ton_types::{
error, fail, AccountId, BuilderData, Cell, HashmapE, HashmapType, IBitstring, Result,
SliceData, UInt256, UsageTree, MAX_DATA_BITS, MAX_REFERENCES_COUNT,
};
///////////////////////////////////////////////////////////////////////////////
///
/// MessageAddress
///
///
/*
3.1.2. TL-B scheme for addresses. The serialization of source and destination addresses is defined by the following TL-B scheme:
addr_none$00 = MsgAddressExt;
addr_extern$01 len:(## 9) external_address:(len * Bit)
= MsgAddressExt;
anycast_info depth:(## 5) rewrite_pfx:(depth * Bit) = Anycast;
addr_std$10 anycast:(Maybe Anycast)
workchain_id:int8 address:uint256 = MsgAddressInt;
addr_var$11 anycast:(Maybe Anycast) addr_len:(## 9)
workchain_id:int32 address:(addr_len * Bit) = MsgAddressInt;
_ MsgAddressInt = MsgAddress;
_ MsgAddressExt = MsgAddress;
*/
impl AnycastInfo {
pub fn with_rewrite_pfx(pfx: SliceData) -> Result<Self> {
Ok(Self {
depth: Number5::new(pfx.remaining_bits() as u32)?,
rewrite_pfx: pfx
})
}
pub fn set_rewrite_pfx(&mut self, pfx: SliceData) -> Result<()>{
self.depth = Number5::new(pfx.remaining_bits() as u32)?;
self.rewrite_pfx = pfx;
Ok(())
}
}
impl Serializable for AnycastInfo {
fn write_to(&self, cell: &mut BuilderData) -> Result<()> {
self.depth.write_to(cell)?; // write depth
cell.checked_append_references_and_data(&self.rewrite_pfx)?; // write rewrite_pfx
Ok(())
}
}
impl fmt::Display for AnycastInfo {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(
f,
"AnycastInfo[pfx {}]", self.rewrite_pfx
)
}
}
/*
addr_std$10 anycast:(Maybe Anycast)
workchain_id:int8 address:uint256 = MsgAddressInt;
addr_var$11 anycast:(Maybe Anycast) addr_len:(## 9)
workchain_id:int32 address:(addr_len * Bit) = MsgAddressInt;
_ MsgAddressInt = MsgAddress;
_ MsgAddressExt = MsgAddress;
*/
impl MsgAddrVar {
pub fn with_address(anycast: Option<AnycastInfo>, workchain_id: i32, address: SliceData) -> Result<MsgAddrVar> {
let addr_len = Number9::new(address.remaining_bits() as u32)?;
Ok(MsgAddrVar { anycast, addr_len, workchain_id, address })
}
}
impl Serializable for MsgAddrVar {
fn write_to(&self, cell: &mut BuilderData) -> Result<()> {
self.anycast.write_maybe_to(cell)?; // anycast
let addr_len = Number9::new(self.address.remaining_bits() as u32)?;
addr_len.write_to(cell)?; // addr_len
cell.append_i32(self.workchain_id)?; // workchain_id
cell.checked_append_references_and_data(&self.address)?; // address
Ok(())
}
}
impl fmt::Display for MsgAddrVar {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
if let Some(anycast) = &self.anycast {
write!(f, "{:x}:", anycast.rewrite_pfx)?;
}
if (self.workchain_id / 128 == 0) && (self.address.remaining_bits() == 256) {
write!(f, "{}:{:x}8_", self.workchain_id, self.address)
} else {
write!(f, "{}:{:x}", self.workchain_id, self.address)
}
}
}
impl MsgAddrStd {
pub fn with_address(anycast: Option<AnycastInfo>, workchain_id: i8, address: AccountId) -> Self {
MsgAddrStd { anycast, workchain_id, address }
}
}
impl Default for MsgAddrStd {
fn default() -> Self{
MsgAddrStd { anycast: None, workchain_id: 0, address: AccountId::from([0; 32]) }
}
}
impl Serializable for MsgAddrStd {
fn write_to(&self, cell: &mut BuilderData) -> Result<()> {
self.anycast.write_maybe_to(cell)?; // anycast
self.workchain_id.write_to(cell)?; // workchain_id
self.address.write_to(cell)?; // address
Ok(())
}
}
impl fmt::Display for MsgAddrStd {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
if let Some(anycast) = &self.anycast {
write!(f, "{:x}:", anycast.rewrite_pfx)?;
}
write!(f, "{}:{:x}", self.workchain_id, self.address)
}
}
impl MsgAddrExt {
pub fn with_address(address: SliceData) -> Result<Self>{
if address.remaining_bits() > Number9::get_max_len(){
fail!(
BlockError::InvalidArg("address can't be longer than 2^9-1 bits".to_string())
)
}
Ok(MsgAddrExt {
len: Number9::new(address.remaining_bits() as u32)?,
external_address: address
})
}
}
impl Serializable for MsgAddrExt {
fn write_to(&self, cell: &mut BuilderData) -> Result<()> {
let len = Number9::new(self.external_address.remaining_bits() as u32)?;
len.write_to(cell)?; // write len
cell.checked_append_references_and_data(&self.external_address)?; // write address
Ok(())
}
}
impl fmt::Display for MsgAddrExt {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, ":{:x}", self.external_address)
}
}
impl MsgAddressExt {
pub fn with_extern(address: SliceData) -> Result<Self> {
Ok(MsgAddressExt::AddrExtern(MsgAddrExt::with_address(address)?))
}
}
impl Default for MsgAddressExt {
fn default() -> Self{
MsgAddressExt::AddrNone
}
}
impl FromStr for MsgAddressExt {
type Err = anyhow::Error;
fn from_str(string: &str) -> Result<Self> {
match MsgAddress::from_str(string)? {
MsgAddress::AddrNone => Ok(MsgAddressExt::AddrNone),
MsgAddress::AddrExt(addr) => Ok(MsgAddressExt::AddrExtern(addr)),
_ => fail!(BlockError::Other("Wrong type of address".to_string()))
}
}
}
impl Serializable for MsgAddressExt {
fn write_to(&self, cell: &mut BuilderData) -> Result<()> {
match self {
MsgAddressExt::AddrNone => {
cell.append_raw(&[0x00], 2)?; // prefix AddrNone
},
MsgAddressExt::AddrExtern(ext) => {
cell.append_raw(&[0x40], 2)?; // prefix AddrExtern
ext.write_to(cell)?; // MsgAddressExt
},
}
Ok(())
}
}
impl fmt::Display for MsgAddressExt {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
MsgAddressExt::AddrNone => write!(f, ""),
MsgAddressExt::AddrExtern(addr) => write!(f, "{}", addr),
}
}
}
impl MsgAddress {
pub fn with_extern(address: SliceData) -> Result<Self> {
Ok(MsgAddress::AddrExt(MsgAddrExt::with_address(address)?))
}
pub fn with_variant(anycast: Option<AnycastInfo>, workchain_id: i32, address: SliceData) -> Result<Self> {
Ok(MsgAddress::AddrVar(MsgAddrVar::with_address(anycast, workchain_id, address)?))
}
pub fn with_standart(anycast: Option<AnycastInfo>, workchain_id: i8, address: AccountId) -> Result<Self> {
Ok(MsgAddress::AddrStd(MsgAddrStd::with_address(anycast, workchain_id, address)))
}
pub fn get_address(&self) -> SliceData {
match self {
MsgAddress::AddrNone => SliceData::default(),
MsgAddress::AddrExt(addr_ext) => addr_ext.external_address.clone(),
MsgAddress::AddrStd(addr_std) => addr_std.address.clone(),
MsgAddress::AddrVar(addr_var) => addr_var.address.clone()
}
}
pub fn get_type(&self) -> u8 {
match self {
MsgAddress::AddrNone => 0b00,
MsgAddress::AddrExt(_) => 0b01,
MsgAddress::AddrStd(_) => 0b10,
MsgAddress::AddrVar(_) => 0b11
}
}
}
impl FromStr for MsgAddress {
type Err = anyhow::Error;
fn from_str(string: &str) -> Result<Self> {
let parts: Vec<&str> = string.split(':').take(4).collect();
let len = parts.len();
if len > 3 {
fail!(BlockError::InvalidArg("too many components in address".to_string()))
}
if len == 0 {
fail!(BlockError::InvalidArg("bad split".to_string()))
}
if parts[len - 1].is_empty() {
if len == 1 {
return Ok(MsgAddress::AddrNone)
} else {
fail!(BlockError::InvalidArg("wrong format".to_string()))
}
}
let address = SliceData::from_string(parts[len - 1])?;
if len == 2 && parts[0].is_empty() {
return MsgAddress::with_extern(address)
}
let workchain_id = len.checked_sub(2)
.map(|index| parts[index].parse::<i32>()).transpose()
.map_err(
|err| BlockError::InvalidArg(
format!("workchain_id is not correct number: {}", err)
)
)?
.ok_or_else(|| BlockError::InvalidArg("missing workchain id".to_string()))?;
let anycast = len.checked_sub(3)
.map(
|index| if parts[index].is_empty() {
Err(BlockError::InvalidArg("wrong format".to_string()))
} else {
SliceData::from_string(parts[index])
.map_err(
|err| BlockError::InvalidArg(
format!("anycast is not correct: {}", err)
)
)
}
).transpose()?
.map(AnycastInfo::with_rewrite_pfx)
.transpose()
.map_err(
|err| BlockError::InvalidArg(
format!("anycast is not correct: {}", err)
)
)?;
if workchain_id < 128 && workchain_id >= -128 {
if address.remaining_bits() != 256 {
fail!(
BlockError::InvalidArg(
format!(
"account address should be 256 bits long in workchain {}",
workchain_id
)
)
)
}
if parts[len - 1].len() == 64 {
Ok(MsgAddress::with_standart(anycast, workchain_id as i8, address)?)
} else {
Ok(MsgAddress::with_variant(anycast, workchain_id, address)?)
}
} else {
Ok(MsgAddress::with_variant(anycast, workchain_id, address)?)
}
}
}
impl Default for MsgAddress {
fn default() -> Self {
MsgAddress::AddrNone
}
}
impl fmt::Display for MsgAddress {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
MsgAddress::AddrNone => write!(f, ""),
MsgAddress::AddrExt(addr) => write!(f, "{}", addr),
MsgAddress::AddrStd(addr) => write!(f, "{}", addr),
MsgAddress::AddrVar(addr) => write!(f, "{}", addr),
}
}
}
impl Serializable for MsgAddress {
fn write_to(&self, cell: &mut BuilderData) -> Result<()> {
cell.append_raw(&[self.get_type() << 6], 2)?;
match self {
MsgAddress::AddrNone => (),
MsgAddress::AddrExt(ext) => ext.write_to(cell)?,
MsgAddress::AddrStd(std) => std.write_to(cell)?,
MsgAddress::AddrVar(var) => var.write_to(cell)?,
}
Ok(())
}
}
impl Default for MsgAddressInt {
fn default() -> Self {
MsgAddressInt::AddrStd(MsgAddrStd::default())
}
}
impl FromStr for MsgAddressInt {
type Err = anyhow::Error;
fn from_str(string: &str) -> Result<Self> {
match MsgAddress::from_str(string)? {
MsgAddress::AddrStd(addr) => Ok(MsgAddressInt::AddrStd(addr)),
MsgAddress::AddrVar(addr) => Ok(MsgAddressInt::AddrVar(addr)),
_ => fail!(BlockError::Other("Wrong type of address".to_string()))
}
}
}
impl MsgAddressInt {
pub fn with_variant(anycast: Option<AnycastInfo>, workchain_id: i32, address: SliceData) -> Result<Self> {
Ok(MsgAddressInt::AddrVar(MsgAddrVar::with_address(anycast, workchain_id, address)?))
}
pub fn with_standart(anycast: Option<AnycastInfo>, workchain_id: i8, address: AccountId) -> Result<Self> {
Ok(MsgAddressInt::AddrStd(MsgAddrStd::with_address(anycast, workchain_id, address)))
}
pub fn get_address(&self) -> SliceData { self.address() }
pub fn get_workchain_id(&self) -> i32 { self.workchain_id() }
pub fn get_rewrite_pfx(&self) -> Option<AnycastInfo> { self.rewrite_pfx() }
pub fn address(&self) -> AccountId {
match self {
MsgAddressInt::AddrStd(addr_std) => addr_std.address.clone(),
MsgAddressInt::AddrVar(addr_var) => addr_var.address.clone()
}
}
pub fn workchain_id(&self) -> i32 {
match self {
MsgAddressInt::AddrStd(addr_std) => addr_std.workchain_id as i32,
MsgAddressInt::AddrVar(addr_var) => addr_var.workchain_id
}
}
pub fn rewrite_pfx(&self) -> Option<AnycastInfo> {
match self {
MsgAddressInt::AddrStd(addr_std) => addr_std.anycast.clone(),
MsgAddressInt::AddrVar(addr_var) => addr_var.anycast.clone()
}
}
pub fn extract_std_address(&self, do_rewrite: bool) -> Result<(i32, AccountId)> {
let (workchain_id, mut account_id, anycast_opt) = match self {
MsgAddressInt::AddrStd(addr_std) => (addr_std.workchain_id as i32, addr_std.address.clone(), &addr_std.anycast),
MsgAddressInt::AddrVar(addr_var) => (addr_var.workchain_id, addr_var.address.clone(), &addr_var.anycast)
};
if let Some(ref anycast) = anycast_opt {
if do_rewrite {
account_id.overwrite_prefix(&anycast.rewrite_pfx)?;
}
}
Ok((workchain_id, account_id))
}
pub fn is_masterchain(&self) -> bool {
self.get_workchain_id() == MASTERCHAIN_ID
}
}
impl Serializable for MsgAddressInt {
fn write_to(&self, cell: &mut BuilderData) -> Result<()> {
match self {
MsgAddressInt::AddrStd(std) => {
cell.append_raw(&[0x80], 2)?; // $10 prefix AddrStd
std.write_to(cell)?; // MsgAddrStd
}
MsgAddressInt::AddrVar(var) => {
cell.append_raw(&[0xC0], 2)?; // $11 prefix AddrVar
var.write_to(cell)?; // MsgAddressInt
}
}
Ok(())
}
}
impl fmt::Display for MsgAddressInt {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
MsgAddressInt::AddrStd(addr) => write!(f, "{}", addr),
MsgAddressInt::AddrVar(addr) => write!(f, "{}", addr),
}
}
}
/*
This file contains definitions for internal and external message headers
as defined in Blockchain: 3.1.
In test_messages.rs and contracts/messages/contract.code there are parsers
for these formats.
Known limitations:
1. For account addreses:
* we don't serialize the workchain id;
* anycast is not supported (is supposed to be `nothing`);
* only standard 256-bit addresses are supported.
2. Instead of CurrencyCollection, Grams type is used.
3. In Message X format, only the info field is parsed.
4. External address is supposed to consist of a whole number of bytes.
*/
impl fmt::Display for InternalMessageHeader {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Internal {{src: {}, dst: {}", self.src, self.dst)?;
if f.alternate() {
write!(f, ", ihr_disabled: {}, bounce: {}, bounced: {}, value: {}, ihr_fee: {}, fwd_fee: {}, lt: {}, at: {}",
self.ihr_disabled,
self.bounce,
self.bounced,
self.value,
self.ihr_fee,
self.fwd_fee,
self.created_lt,
self.created_at
)?;
}
write!(f, "}}")
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum MsgAddressIntOrNone {
None,
Some(MsgAddressInt)
}
impl MsgAddressIntOrNone {
pub fn get_type(&self) -> u8 {
match self {
MsgAddressIntOrNone::None => 0b00,
MsgAddressIntOrNone::Some(addr) =>
match addr {
MsgAddressInt::AddrStd(_) => 0b10,
MsgAddressInt::AddrVar(_) => 0b11,
}
}
}
pub fn get_rewrite_pfx(&self) -> Option<AnycastInfo> {
match self {
MsgAddressIntOrNone::None => None,
MsgAddressIntOrNone::Some(addr) => addr.get_rewrite_pfx()
}
}
}
impl Default for MsgAddressIntOrNone {
fn default() -> Self {
MsgAddressIntOrNone::None
}
}
impl fmt::Display for MsgAddressIntOrNone {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
MsgAddressIntOrNone::None => write!(f, ""),
MsgAddressIntOrNone::Some(addr) => write!(f, "{}", addr),
}
}
}
impl Serializable for MsgAddressIntOrNone {
fn write_to(&self, cell: &mut BuilderData) -> Result<()> {
match self {
MsgAddressIntOrNone::None => {
cell.append_raw(&[0x00], 2)?;
}
MsgAddressIntOrNone::Some(addr) => addr.write_to(cell)?
}
Ok(())
}
}
impl Deserializable for MsgAddressIntOrNone {
fn read_from(&mut self, cell: &mut SliceData) -> Result<()>{
let addr_type = cell.get_next_int(2)? as u8;
match addr_type & 0b11 {
0b00 => {
*self = MsgAddressIntOrNone::None;
},
0b10 => {
let mut std = MsgAddrStd::default();
std.read_from(cell)?;
*self = MsgAddressIntOrNone::Some(MsgAddressInt::AddrStd(std));
},
0b11 => {
let mut var = MsgAddrVar::default();
var.read_from(cell)?;
*self = MsgAddressIntOrNone::Some(MsgAddressInt::AddrVar(var));
},
_ => fail!(BlockError::Other("Wrong type of address".to_string()))
}
Ok(())
}
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct InternalMessageHeader {
pub ihr_disabled: bool,
pub bounce: bool,
pub bounced: bool,
pub src: MsgAddressIntOrNone,
pub dst: MsgAddressInt,
pub value: CurrencyCollection,
pub ihr_fee: Grams,
pub fwd_fee: Grams,
pub created_lt: u64,
pub created_at: UnixTime32,
}
impl InternalMessageHeader {
///
/// Create new instance of InternalMessageHeader
/// with source and destination address and value
///
pub fn with_addresses(
src: MsgAddressInt,
dst: MsgAddressInt,
value: CurrencyCollection,
) -> Self {
InternalMessageHeader {
ihr_disabled: true,
bounce: false,
bounced: false,
src: MsgAddressIntOrNone::Some(src),
dst,
value,
ihr_fee: Grams::default(),
fwd_fee: Grams::default(),
created_lt: 0, // Logical Time will be set on BlockBuilder
created_at: UnixTime32::default(), // UNIX time too
}
}
pub fn with_addresses_and_bounce(
src: MsgAddressInt,
dst: MsgAddressInt,
value: CurrencyCollection,
bounce: bool,
) -> Self {
let mut hdr = Self::with_addresses(src, dst, value);
hdr.bounce = bounce;
hdr
}
///
/// Get value tansfered message
///
pub fn value(&self) -> &CurrencyCollection {
&self.value
}
///
/// Get IHR fee for message
///
pub fn ihr_fee(&self) -> &Grams {
&self.ihr_fee
}
///
/// Get forwarding fee for message transfer
///
pub fn fwd_fee(&self) -> &Grams {
&self.fwd_fee
}
pub fn src(&self) -> Result<&MsgAddressInt> {
self.src_ref().ok_or_else(|| error!("incorrect source address"))
}
pub fn src_ref(&self) -> Option<&MsgAddressInt> {
match self.src {
MsgAddressIntOrNone::Some(ref addr) => Some(addr),
MsgAddressIntOrNone::None => None
}
}
pub fn set_src(&mut self, src: MsgAddressInt) {
self.src = MsgAddressIntOrNone::Some(src)
}
pub fn set_dst(&mut self, dst: MsgAddressInt) {
self.dst = dst
}
}
impl Serializable for InternalMessageHeader{
fn write_to(&self, cell: &mut BuilderData) -> Result<()> {
cell
.append_bit_zero()? //tag
.append_bit_bool(self.ihr_disabled)?
.append_bit_bool(self.bounce)?
.append_bit_bool(self.bounced)?;
self.src.write_to(cell)?;
self.dst.write_to(cell)?;
self.value.write_to(cell)?; //value: CurrencyCollection
self.ihr_fee.write_to(cell)?; //ihr_fee
self.fwd_fee.write_to(cell)?; //fwd_fee
self.created_lt.write_to(cell)?; //created_lt
self.created_at.write_to(cell)?; //created_at
Ok(())
}
}
impl Deserializable for InternalMessageHeader {
fn read_from(&mut self, cell: &mut SliceData) -> Result<()>{
// constructor tag will be readed in Message
self.ihr_disabled = cell.get_next_bit()?; // ihr_disabled
self.bounce = cell.get_next_bit()?; // bounce
self.bounced = cell.get_next_bit()?;
self.src.read_from(cell)?; // addr src
self.dst.read_from(cell)?; // addr dst
self.value.read_from(cell)?; // value - balance
self.ihr_fee.read_from(cell)?; //ihr_fee
self.fwd_fee.read_from(cell)?; //fwd_fee
self.created_lt.read_from(cell)?; //created_lt
self.created_at.read_from(cell)?; //created_at
Ok(())
}
}
impl fmt::Display for ExternalInboundMessageHeader {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "External Inbound {{src: {}, dst: {}, fee: {}}}",
self.src, self.dst, self.import_fee
)
}
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct ExternalInboundMessageHeader {
pub src: MsgAddressExt,
pub dst: MsgAddressInt,
pub import_fee: Grams,
}
impl ExternalInboundMessageHeader {
pub const fn new(src: MsgAddressExt, dst: MsgAddressInt) -> Self {
let import_fee = Grams::zero();
Self { src, dst, import_fee }
}
}
impl Serializable for ExternalInboundMessageHeader{
fn write_to(&self, cell: &mut BuilderData) -> Result<()> {
cell
.append_bit_one()?
.append_bit_zero()?;
self.src.write_to(cell)?; // addr src
self.dst.write_to(cell)?; // addr dst
self.import_fee.write_to(cell)?; //ihr_fee
Ok(())
}
}
impl Deserializable for ExternalInboundMessageHeader {
fn read_from(&mut self, cell: &mut SliceData) -> Result<()>{
// constructor tag will be readed in Message
self.src.read_from(cell)?; // addr src
self.dst.read_from(cell)?; // addr dst
self.import_fee.read_from(cell)?; //ihr_fee
Ok(())
}
}
impl fmt::Display for ExtOutMessageHeader {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "External Outbound {{src: {}, dst: {}, lt: {}, at: {}}}",
self.src, self.dst, self.created_lt, self.created_at
)
}
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct ExtOutMessageHeader {
pub src: MsgAddressIntOrNone,
pub dst: MsgAddressExt,
pub created_lt: u64,
pub created_at: UnixTime32,
}
impl ExtOutMessageHeader {
pub fn with_addresses(src: MsgAddressInt, dst: MsgAddressExt) -> ExtOutMessageHeader {
ExtOutMessageHeader {
src: MsgAddressIntOrNone::Some(src),
dst,
created_lt: 0, // Logical Time will be set on block builder
created_at: UnixTime32::default(), // UNIX time too
}
}
pub fn src(&self) -> Option<&MsgAddressInt> {
match self.src {
MsgAddressIntOrNone::Some(ref src) => Some(src),
MsgAddressIntOrNone::None => None
}
}
pub fn set_src(&mut self, src: MsgAddressInt) {
self.src = MsgAddressIntOrNone::Some(src);
}
}
impl Serializable for ExtOutMessageHeader{
fn write_to(&self, cell: &mut BuilderData) -> Result<()> {
cell
.append_bit_one()?
.append_bit_one()?;
self.src.write_to(cell)?; // addr src
self.dst.write_to(cell)?; // addr dst
self.created_lt.write_to(cell)?; //created_lt
self.created_at.write_to(cell)?; //created_at
Ok(())
}
}
impl Deserializable for ExtOutMessageHeader {
fn read_from(&mut self, cell: &mut SliceData) -> Result<()>{
// constructor tag will be readed in Message
self.src.read_from(cell)?; // addr src
self.dst.read_from(cell)?; // addr dst
self.created_lt.read_from(cell)?; //created_lt
self.created_at.read_from(cell)?; //created_at
Ok(())
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////
///
/// int_msg_info$0 ihr_disabled:Bool bounce:Bool
/// src:MsgAddressInt dest:MsgAddressInt
/// value:CurrencyCollection ihr_fee:Grams fwd_fee:Grams
/// created_lt:uint64 created_at:uint32 = CommonMsgInfo;
/// ext_in_msg_info$10 src:MsgAddressExt dest:MsgAddressInt
/// import_fee:Grams = CommonMsgInfo;
/// ext_out_msg_info$11 src:MsgAddressInt dest:MsgAddressExt
/// created_lt:uint64 created_at:uint32 = CommonMsgInfo;
///
impl fmt::Display for CommonMsgInfo {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
CommonMsgInfo::IntMsgInfo(hdr) => write!(f, "{}", hdr),
CommonMsgInfo::ExtInMsgInfo(hdr) => write!(f, "{}", hdr),
CommonMsgInfo::ExtOutMsgInfo(hdr) => write!(f, "{}", hdr),
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum CommonMsgInfo{
IntMsgInfo(InternalMessageHeader),
ExtInMsgInfo(ExternalInboundMessageHeader),
ExtOutMsgInfo(ExtOutMessageHeader)
}
impl CommonMsgInfo {
///
/// Get destination account address
///
pub fn dest_account_address(&self) -> Option<AccountId> {
match self {
CommonMsgInfo::IntMsgInfo(header) => {
match header.dst {
MsgAddressInt::AddrStd(ref std) => Some(std.address.clone()),
MsgAddressInt::AddrVar(ref _var) => unimplemented!(), // TODO
}
},
CommonMsgInfo::ExtInMsgInfo(header) => {
match header.dst {
MsgAddressInt::AddrStd(ref std) => Some(std.address.clone()),
MsgAddressInt::AddrVar(ref _var) => unimplemented!(), // TODO
}
}
_ => None,
}
}
///
/// Get value transmitted by the value
/// Value can be transmitted only internal messages
/// For other types of messages, function returned None
///
pub fn get_value(&self) -> Option<&CurrencyCollection> {
match self {
CommonMsgInfo::IntMsgInfo(header) => Some(&header.value),
_ => None,
}
}
pub fn get_value_mut(&mut self) -> Option<&mut CurrencyCollection> {
match self {
CommonMsgInfo::IntMsgInfo(header) => Some(&mut header.value),
_ => None,
}
}
///
/// Get message header fees
/// Fee collected only for transfer internal and external outbound messages.
/// for other types of messages, function returned None
///
pub fn fee(&self) -> Result<Option<Grams>> {
match self {
CommonMsgInfo::IntMsgInfo(header) => {
let mut result = header.ihr_fee;
result.add(&header.fwd_fee)?;
Ok(Some(result))
},
CommonMsgInfo::ExtInMsgInfo(header) => {
Ok(Some(header.import_fee))
}
_ => Ok(None),
}
}
///
/// Get dest address for Intrenal and Inbound external messages
///
pub fn get_dst_address(&self) -> Option<MsgAddressInt> {
match self {
CommonMsgInfo::IntMsgInfo(header) => {
Some(header.dst.clone())
},
CommonMsgInfo::ExtInMsgInfo(header) => {
Some(header.dst.clone())
}
_ => None,
}
}
}
impl Default for CommonMsgInfo {
fn default() -> Self {
CommonMsgInfo::IntMsgInfo(InternalMessageHeader::default())
}
}
impl Serializable for CommonMsgInfo
{
fn write_to(&self, cell: &mut BuilderData) -> Result<()> {
match self {
CommonMsgInfo::IntMsgInfo(header) => header.write_to(cell)?,
CommonMsgInfo::ExtInMsgInfo(header) => header.write_to(cell)?,
CommonMsgInfo::ExtOutMsgInfo(header) => header.write_to(cell)?,
}
Ok(())
}
}
impl Deserializable for CommonMsgInfo
{
fn read_from(&mut self, cell: &mut SliceData) -> Result<()>{
*self = if !cell.get_next_bit()? { // CommonMsgInfo::int_msg_info
let mut int_msg = InternalMessageHeader::default();
int_msg.read_from(cell)?;
CommonMsgInfo::IntMsgInfo(int_msg)
} else if !cell.get_next_bit()? {
let mut ext_in_msg = ExternalInboundMessageHeader::default();
ext_in_msg.read_from(cell)?;
CommonMsgInfo::ExtInMsgInfo(ext_in_msg)
} else {
let mut ext_out_ms = ExtOutMessageHeader::default();
ext_out_ms.read_from(cell)?;
CommonMsgInfo::ExtOutMsgInfo(ext_out_ms)
};
Ok(())
}
}
pub type MessageId = UInt256;
///////////////////////////////////////////////////////////////////////////////////////////
///
/// message$_ {X:Type} info:CommonMsgInfo
/// init:(Maybe (Either StateInit ^StateInit))
/// body:(Either X ^X) = Message X;
///
///
#[derive(Debug, Default, Clone, Eq)]
pub struct Message {
header: CommonMsgInfo,
init: Option<StateInit>,
body: Option<SliceData>,
body_to_ref: Option<bool>,
init_to_ref: Option<bool>,
}
impl fmt::Display for Message {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Message {{header: {}", self.header)?;
match &self.init {
Some(init) => write!(f, ", init: {:?}", init)?,
None => write!(f, ", init: None")?
}
match &self.body {
Some(body) => write!(f, ", body: {:x}", body)?,
None => write!(f, ", body: None")?
}
write!(f, "}}")
}
}