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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
//  Copyright (C) 2017-2019  The AXIOM TEAM Association.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.

//! Wrappers around Transaction documents.

use dup_crypto::hashs::*;
use durs_common_tools::fatal_error;
use pest::iterators::Pair;
use pest::iterators::Pairs;
use pest::Parser;
use std::ops::{Add, Deref, Sub};
use std::str::FromStr;
use unwrap::unwrap;

use crate::blockstamp::Blockstamp;
use crate::documents::*;
use crate::text_document_traits::*;

/// Wrap a transaction amount
#[derive(Debug, Copy, Clone, Eq, Ord, PartialEq, PartialOrd, Deserialize, Hash, Serialize)]
pub struct TxAmount(pub isize);

impl Add for TxAmount {
    type Output = TxAmount;
    fn add(self, a: TxAmount) -> Self::Output {
        TxAmount(self.0 + a.0)
    }
}

impl Sub for TxAmount {
    type Output = TxAmount;
    fn sub(self, a: TxAmount) -> Self::Output {
        TxAmount(self.0 - a.0)
    }
}

/// Wrap a transaction amout base
#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Deserialize, Hash, Serialize)]
pub struct TxBase(pub usize);

/// Wrap a transaction index
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, Deserialize, Serialize)]
pub struct TxIndex(pub usize);

/// Wrap a transaction input
#[derive(Debug, Copy, Clone, PartialEq, Eq, Deserialize, Serialize)]
pub enum TransactionInput {
    /// Universal Dividend Input
    D(TxAmount, TxBase, PubKey, BlockNumber),
    /// Previous Transaction Input
    T(TxAmount, TxBase, Hash, TxIndex),
}

impl ToString for TransactionInput {
    fn to_string(&self) -> String {
        match *self {
            TransactionInput::D(amount, base, pubkey, block_number) => {
                format!("{}:{}:D:{}:{}", amount.0, base.0, pubkey, block_number.0)
            }
            TransactionInput::T(amount, base, ref tx_hash, tx_index) => {
                format!("{}:{}:T:{}:{}", amount.0, base.0, tx_hash, tx_index.0)
            }
        }
    }
}

impl TransactionInput {
    fn from_pest_pair(mut pairs: Pairs<Rule>) -> TransactionInput {
        let tx_input_type_pair = pairs.next().unwrap();
        match tx_input_type_pair.as_rule() {
            Rule::tx_input_du => {
                let mut inner_rules = tx_input_type_pair.into_inner(); // ${ tx_amount ~ ":" ~ tx_amount_base ~ ":D:" ~ pubkey ~ ":" ~ du_block_id }

                TransactionInput::D(
                    TxAmount(inner_rules.next().unwrap().as_str().parse().unwrap()),
                    TxBase(inner_rules.next().unwrap().as_str().parse().unwrap()),
                    PubKey::Ed25519(
                        ed25519::PublicKey::from_base58(inner_rules.next().unwrap().as_str())
                            .unwrap(),
                    ),
                    BlockNumber(inner_rules.next().unwrap().as_str().parse().unwrap()),
                )
            }
            Rule::tx_input_tx => {
                let mut inner_rules = tx_input_type_pair.into_inner(); // ${ tx_amount ~ ":" ~ tx_amount_base ~ ":D:" ~ pubkey ~ ":" ~ du_block_id }

                TransactionInput::T(
                    TxAmount(inner_rules.next().unwrap().as_str().parse().unwrap()),
                    TxBase(inner_rules.next().unwrap().as_str().parse().unwrap()),
                    Hash::from_hex(inner_rules.next().unwrap().as_str()).unwrap(),
                    TxIndex(inner_rules.next().unwrap().as_str().parse().unwrap()),
                )
            }
            _ => fatal_error!("unexpected rule: {:?}", tx_input_type_pair.as_rule()), // Grammar ensures that we never reach this line
        }
    }
}

impl FromStr for TransactionInput {
    type Err = TextDocumentParseError;

    fn from_str(source: &str) -> Result<Self, Self::Err> {
        match DocumentsParser::parse(Rule::tx_input, source) {
            Ok(mut pairs) => Ok(TransactionInput::from_pest_pair(
                pairs.next().unwrap().into_inner(),
            )),
            Err(_) => Err(TextDocumentParseError::InvalidInnerFormat(
                "Invalid unlocks !".to_owned(),
            )),
        }
    }
}

/*impl TransactionInput {
    /// Parse Transaction Input from string.
    pub fn from_str(source: &str) -> Result<TransactionInput, TextDocumentParseError> {
        if let Some(caps) = D_INPUT_REGEX.captures(source) {
            let amount = &caps["amount"];
            let base = &caps["base"];
            let pubkey = &caps["pubkey"];
            let block_number = &caps["block_number"];
            Ok(TransactionInput::D(
                TxAmount(amount.parse().expect("fail to parse input amount !")),
                TxBase(base.parse().expect("fail to parse input base !")),
                PubKey::Ed25519(
                    ed25519::PublicKey::from_base58(pubkey).expect("fail to parse input pubkey !"),
                ),
                BlockNumber(
                    block_number
                        .parse()
                        .expect("fail to parse input block_number !"),
                ),
            ))
        //Ok(TransactionInput::D(10, 0, PubKey::Ed25519(ed25519::PublicKey::from_base58("FD9wujR7KABw88RyKEGBYRLz8PA6jzVCbcBAsrBXBqSa").unwrap(), 0)))
        } else if let Some(caps) = T_INPUT_REGEX.captures(source) {
            let amount = &caps["amount"];
            let base = &caps["base"];
            let tx_hash = &caps["tx_hash"];
            let tx_index = &caps["tx_index"];
            Ok(TransactionInput::T(
                TxAmount(amount.parse().expect("fail to parse input amount")),
                TxBase(base.parse().expect("fail to parse base amount")),
                Hash::from_hex(tx_hash).expect("fail to parse tx_hash"),
                TxIndex(tx_index.parse().expect("fail to parse tx_index amount")),
            ))
        } else {
            println!("Fail to parse this input = {:?}", source);
            Err(TextDocumentParseError::InvalidInnerFormat("Transaction2"))
        }
    }
}*/

/// Wrap a transaction unlock proof
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
pub enum TransactionUnlockProof {
    /// Indicates that the signature of the corresponding key is at the bottom of the document
    Sig(usize),
    /// Provides the code to unlock the corresponding funds
    Xhx(String),
}

impl ToString for TransactionUnlockProof {
    fn to_string(&self) -> String {
        match *self {
            TransactionUnlockProof::Sig(ref index) => format!("SIG({})", index),
            TransactionUnlockProof::Xhx(ref hash) => format!("XHX({})", hash),
        }
    }
}

/// Wrap a transaction unlocks input
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
pub struct TransactionInputUnlocks {
    /// Input index
    pub index: usize,
    /// List of proof to unlock funds
    pub unlocks: Vec<TransactionUnlockProof>,
}

impl ToString for TransactionInputUnlocks {
    fn to_string(&self) -> String {
        let mut result: String = format!("{}:", self.index);
        for unlock in &self.unlocks {
            result.push_str(&format!("{} ", unlock.to_string()));
        }
        let new_size = result.len() - 1;
        result.truncate(new_size);
        result
    }
}

impl TransactionInputUnlocks {
    fn from_pest_pair(pairs: Pairs<Rule>) -> TransactionInputUnlocks {
        let mut input_index = 0;
        let mut unlock_conds = Vec::new();
        for unlock_field in pairs {
            // ${ input_index ~ ":" ~ unlock_cond ~ (" " ~ unlock_cond)* }
            match unlock_field.as_rule() {
                Rule::input_index => input_index = unlock_field.as_str().parse().unwrap(),
                Rule::unlock_sig => unlock_conds.push(TransactionUnlockProof::Sig(
                    unlock_field
                        .into_inner()
                        .next()
                        .unwrap()
                        .as_str()
                        .parse()
                        .unwrap(),
                )),
                Rule::unlock_xhx => unlock_conds.push(TransactionUnlockProof::Xhx(String::from(
                    unlock_field.into_inner().next().unwrap().as_str(),
                ))),
                _ => fatal_error!("unexpected rule: {:?}", unlock_field.as_rule()), // Grammar ensures that we never reach this line
            }
        }
        TransactionInputUnlocks {
            index: input_index,
            unlocks: unlock_conds,
        }
    }
}

impl FromStr for TransactionInputUnlocks {
    type Err = TextDocumentParseError;

    fn from_str(source: &str) -> Result<Self, Self::Err> {
        match DocumentsParser::parse(Rule::tx_unlock, source) {
            Ok(mut pairs) => Ok(TransactionInputUnlocks::from_pest_pair(
                pairs.next().unwrap().into_inner(),
            )),
            Err(_) => Err(TextDocumentParseError::InvalidInnerFormat(
                "Invalid unlocks !".to_owned(),
            )),
        }
    }
}

/// Wrap a transaction ouput condition
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, Deserialize, Serialize)]
pub enum TransactionOutputCondition {
    /// The consumption of funds will require a valid signature of the specified key
    Sig(PubKey),
    /// The consumption of funds will require to provide a code with the hash indicated
    Xhx(Hash),
    /// Funds may not be consumed until the blockchain reaches the timestamp indicated.
    Cltv(u64),
    /// Funds may not be consumed before the duration indicated, starting from the timestamp of the block where the transaction is written.
    Csv(u64),
}

impl ToString for TransactionOutputCondition {
    fn to_string(&self) -> String {
        match *self {
            TransactionOutputCondition::Sig(ref pubkey) => format!("SIG({})", pubkey),
            TransactionOutputCondition::Xhx(ref hash) => format!("XHX({})", hash),
            TransactionOutputCondition::Cltv(timestamp) => format!("CLTV({})", timestamp),
            TransactionOutputCondition::Csv(duration) => format!("CSV({})", duration),
        }
    }
}

/// Wrap an utxo conditions
#[derive(Debug, Clone, PartialEq, Eq, Hash, Deserialize, Serialize)]
pub struct UTXOConditions {
    /// We are obliged to allow the introduction of the original text (instead of the self-generated text),
    /// because the original text may contain errors that are unfortunately allowed by duniter-ts.
    pub origin_str: Option<String>,
    /// Store script conditions
    pub conditions: UTXOConditionsGroup,
}

impl UTXOConditions {
    /// Lightens the UTXOConditions (for example to store it while minimizing the space required)
    pub fn reduce(&mut self) {
        if self.origin_str.is_some()
            && self.origin_str.clone().expect("safe unwrap") == self.conditions.to_string()
        {
            self.origin_str = None;
        }
    }
    /// Check validity of this UTXOConditions
    pub fn check(&self) -> bool {
        !(self.origin_str.is_some()
            && self.origin_str.clone().expect("safe unwrap") != self.conditions.to_string())
    }
}

impl ToString for UTXOConditions {
    fn to_string(&self) -> String {
        if let Some(ref origin_str) = self.origin_str {
            origin_str.to_string()
        } else {
            self.conditions.to_string()
        }
    }
}

/// Wrap a transaction ouput condition group
#[derive(Debug, Clone, PartialEq, Eq, Hash, Deserialize, Serialize)]
pub enum UTXOConditionsGroup {
    /// Single
    Single(TransactionOutputCondition),
    /// Brackets
    Brackets(Box<UTXOConditionsGroup>),
    /// And operator
    And(Box<UTXOConditionsGroup>, Box<UTXOConditionsGroup>),
    /// Or operator
    Or(Box<UTXOConditionsGroup>, Box<UTXOConditionsGroup>),
}

macro_rules! utxo_conds_wrap_op_chain {
    ($op:expr, $fn_name:ident) => {
        fn $fn_name(conds_subgroups: &mut Vec<UTXOConditionsGroup>) -> UTXOConditionsGroup {
            if conds_subgroups.len() == 2 {
                $op(
                    Box::new(conds_subgroups[0].clone()),
                    Box::new(conds_subgroups[1].clone()),
                )
            } else if conds_subgroups.len() > 2 {
                let last_subgroup = conds_subgroups.pop().unwrap();
                let previous_last_subgroup = conds_subgroups.pop().unwrap();
                conds_subgroups.push($op(
                    Box::new(previous_last_subgroup),
                    Box::new(last_subgroup),
                ));
                UTXOConditionsGroup::$fn_name(conds_subgroups)
            } else {
                fatal_error!(
                    "Grammar should ensure that and chain contains at least two conditions subgroups !"
                )
            }
        }
    }
}

impl UTXOConditionsGroup {
    /// Wrap UTXO and chain
    utxo_conds_wrap_op_chain!(UTXOConditionsGroup::And, new_and_chain);
    /// Wrap UTXO or chain
    utxo_conds_wrap_op_chain!(UTXOConditionsGroup::Or, new_or_chain);

    /// Wrap UTXO conditions
    pub fn wrap_utxo_conds(pair: Pair<Rule>) -> UTXOConditionsGroup {
        match pair.as_rule() {
            Rule::output_and_group => {
                let and_pairs = pair.into_inner();
                let mut conds_subgroups: Vec<UTXOConditionsGroup> = and_pairs
                    .map(UTXOConditionsGroup::wrap_utxo_conds)
                    .collect();
                UTXOConditionsGroup::Brackets(Box::new(UTXOConditionsGroup::new_and_chain(
                    &mut conds_subgroups,
                )))
            }
            Rule::output_or_group => {
                let or_pairs = pair.into_inner();
                let mut conds_subgroups: Vec<UTXOConditionsGroup> =
                    or_pairs.map(UTXOConditionsGroup::wrap_utxo_conds).collect();
                UTXOConditionsGroup::Brackets(Box::new(UTXOConditionsGroup::new_or_chain(
                    &mut conds_subgroups,
                )))
            }
            Rule::output_cond_sig => {
                UTXOConditionsGroup::Single(TransactionOutputCondition::Sig(PubKey::Ed25519(
                    ed25519::PublicKey::from_base58(pair.into_inner().next().unwrap().as_str())
                        .unwrap(),
                )))
            }
            Rule::output_cond_xhx => UTXOConditionsGroup::Single(TransactionOutputCondition::Xhx(
                Hash::from_hex(pair.into_inner().next().unwrap().as_str()).unwrap(),
            )),
            Rule::output_cond_csv => UTXOConditionsGroup::Single(TransactionOutputCondition::Csv(
                pair.into_inner().next().unwrap().as_str().parse().unwrap(),
            )),
            Rule::output_cond_cltv => {
                UTXOConditionsGroup::Single(TransactionOutputCondition::Cltv(
                    pair.into_inner().next().unwrap().as_str().parse().unwrap(),
                ))
            }
            _ => fatal_error!("unexpected rule: {:?}", pair.as_rule()), // Grammar ensures that we never reach this line
        }
    }
}

impl ToString for UTXOConditionsGroup {
    fn to_string(&self) -> String {
        match *self {
            UTXOConditionsGroup::Single(ref condition) => condition.to_string(),
            UTXOConditionsGroup::Brackets(ref condition_group) => {
                format!("({})", condition_group.deref().to_string())
            }
            UTXOConditionsGroup::And(ref condition_group_1, ref condition_group_2) => format!(
                "{} && {}",
                condition_group_1.deref().to_string(),
                condition_group_2.deref().to_string()
            ),
            UTXOConditionsGroup::Or(ref condition_group_1, ref condition_group_2) => format!(
                "{} || {}",
                condition_group_1.deref().to_string(),
                condition_group_2.deref().to_string()
            ),
        }
    }
}

/// Wrap a transaction ouput
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
pub struct TransactionOutput {
    /// Amount
    pub amount: TxAmount,
    /// Base
    pub base: TxBase,
    /// List of conditions for consum this output
    pub conditions: UTXOConditions,
}

impl TransactionOutput {
    /// Lightens the TransactionOutput (for example to store it while minimizing the space required)
    fn reduce(&mut self) {
        self.conditions.reduce()
    }
    /// Check validity of this output
    pub fn check(&self) -> bool {
        self.conditions.check()
    }
}

impl ToString for TransactionOutput {
    fn to_string(&self) -> String {
        format!(
            "{}:{}:{}",
            self.amount.0,
            self.base.0,
            self.conditions.to_string()
        )
    }
}

impl TransactionOutput {
    fn from_pest_pair(mut utxo_pairs: Pairs<Rule>) -> TransactionOutput {
        let amount = TxAmount(utxo_pairs.next().unwrap().as_str().parse().unwrap());
        let base = TxBase(utxo_pairs.next().unwrap().as_str().parse().unwrap());
        let conditions_pairs = utxo_pairs.next().unwrap();
        let conditions_origin_str = conditions_pairs.as_str();
        TransactionOutput {
            amount,
            base,
            conditions: UTXOConditions {
                origin_str: Some(String::from(conditions_origin_str)),
                conditions: UTXOConditionsGroup::wrap_utxo_conds(conditions_pairs),
            },
        }
    }
}

impl FromStr for TransactionOutput {
    type Err = TextDocumentParseError;

    fn from_str(source: &str) -> Result<Self, Self::Err> {
        let output_parts: Vec<&str> = source.split(':').collect();
        let amount = output_parts.get(0);
        let base = output_parts.get(1);
        let conditions_origin_str = output_parts.get(2);

        let str_to_parse = if amount.is_some() && base.is_some() && conditions_origin_str.is_some()
        {
            format!(
                "{}:{}:({})",
                unwrap!(amount),
                unwrap!(base),
                unwrap!(conditions_origin_str)
            )
        } else {
            source.to_owned()
        };

        match DocumentsParser::parse(Rule::tx_output, &str_to_parse) {
            Ok(mut utxo_pairs) => {
                let mut output =
                    TransactionOutput::from_pest_pair(utxo_pairs.next().unwrap().into_inner());
                output.conditions.origin_str = conditions_origin_str.map(ToString::to_string);
                Ok(output)
            }
            Err(_) => match DocumentsParser::parse(Rule::tx_output, source) {
                Ok(mut utxo_pairs) => {
                    let mut output =
                        TransactionOutput::from_pest_pair(utxo_pairs.next().unwrap().into_inner());
                    output.conditions.origin_str = conditions_origin_str.map(ToString::to_string);
                    Ok(output)
                }
                Err(e) => Err(TextDocumentParseError::InvalidInnerFormat(format!(
                    "Invalid output : {}",
                    e
                ))),
            },
        }
    }
}

/// Wrap a Transaction document.
///
/// Must be created by parsing a text document or using a builder.
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
pub struct TransactionDocument {
    /// Document as text.
    ///
    /// Is used to check signatures, and other values
    /// must be extracted from it.
    text: Option<String>,

    /// Currency.
    currency: String,
    /// Blockstamp
    blockstamp: Blockstamp,
    /// Locktime
    locktime: u64,
    /// Document issuer (there should be only one).
    issuers: Vec<PubKey>,
    /// Transaction inputs.
    inputs: Vec<TransactionInput>,
    /// Inputs unlocks.
    unlocks: Vec<TransactionInputUnlocks>,
    /// Transaction outputs.
    outputs: Vec<TransactionOutput>,
    /// Transaction comment
    comment: String,
    /// Document signature (there should be only one).
    signatures: Vec<Sig>,
    /// Transaction hash
    hash: Option<Hash>,
}

#[derive(Clone, Debug, Deserialize, Hash, Serialize, PartialEq, Eq)]
/// Transaction document stringifed
pub struct TransactionDocumentStringified {
    /// Currency.
    pub currency: String,
    /// Blockstamp
    pub blockstamp: String,
    /// Locktime
    pub locktime: u64,
    /// Document issuer (there should be only one).
    pub issuers: Vec<String>,
    /// Transaction inputs.
    pub inputs: Vec<String>,
    /// Inputs unlocks.
    pub unlocks: Vec<String>,
    /// Transaction outputs.
    pub outputs: Vec<String>,
    /// Transaction comment
    pub comment: String,
    /// Document signatures
    pub signatures: Vec<String>,
    /// Transaction hash
    pub hash: Option<String>,
}

impl ToStringObject for TransactionDocument {
    type StringObject = TransactionDocumentStringified;

    fn to_string_object(&self) -> TransactionDocumentStringified {
        TransactionDocumentStringified {
            currency: self.currency.clone(),
            blockstamp: format!("{}", self.blockstamp),
            locktime: self.locktime,
            issuers: self.issuers.iter().map(|p| format!("{}", p)).collect(),
            inputs: self
                .inputs
                .iter()
                .map(TransactionInput::to_string)
                .collect(),
            unlocks: self
                .unlocks
                .iter()
                .map(TransactionInputUnlocks::to_string)
                .collect(),
            outputs: self
                .outputs
                .iter()
                .map(TransactionOutput::to_string)
                .collect(),
            comment: self.comment.clone(),
            signatures: self.signatures.iter().map(|s| format!("{}", s)).collect(),
            hash: if let Some(hash) = self.hash {
                Some(hash.to_string())
            } else {
                None
            },
        }
    }
}

impl TransactionDocument {
    /// Compute transaction hash
    pub fn compute_hash(&mut self) -> Hash {
        let mut hashing_text = if let Some(ref text) = self.text {
            text.clone()
        } else {
            fatal_error!("Try to compute_hash of tx with None text !")
        };
        for sig in &self.signatures {
            hashing_text.push_str(&sig.to_string());
            hashing_text.push_str("\n");
        }
        //println!("tx_text_hasing={}", hashing_text);
        self.hash = Some(Hash::compute_str(&hashing_text));
        self.hash.expect("Try to get hash of a reduce tx !")
    }
    /// get transaction hash option
    pub fn get_hash_opt(&self) -> Option<Hash> {
        self.hash
    }
    /// Get transaction hash
    pub fn get_hash(&mut self) -> Hash {
        if let Some(hash) = self.hash {
            hash
        } else {
            self.compute_hash()
        }
    }
    /// Get transaction inputs
    pub fn get_inputs(&self) -> &[TransactionInput] {
        &self.inputs
    }
    /// Get transaction outputs
    pub fn get_outputs(&self) -> &[TransactionOutput] {
        &self.outputs
    }
    /// Lightens the transaction (for example to store it while minimizing the space required)
    pub fn reduce(&mut self) {
        self.text = None;
        self.hash = None;
        for output in &mut self.outputs {
            output.reduce()
        }
    }
    /// from pest parser pair
    pub fn from_pest_pair(pair: Pair<Rule>) -> Result<TransactionDocument, TextDocumentParseError> {
        let doc = pair.as_str();
        let mut currency = "";
        let mut blockstamp = Blockstamp::default();
        let mut locktime = 0;
        let mut issuers = Vec::new();
        let mut inputs = Vec::new();
        let mut unlocks = Vec::new();
        let mut outputs = Vec::new();
        let mut comment = "";
        let mut sigs = Vec::new();

        for field in pair.into_inner() {
            match field.as_rule() {
                Rule::currency => currency = field.as_str(),
                Rule::blockstamp => {
                    let mut inner_rules = field.into_inner(); // ${ block_id ~ "-" ~ hash }

                    let block_id: &str = inner_rules.next().unwrap().as_str();
                    let block_hash: &str = inner_rules.next().unwrap().as_str();
                    blockstamp = Blockstamp {
                        id: BlockNumber(block_id.parse().unwrap()), // Grammar ensures that we have a digits string.
                        hash: BlockHash(Hash::from_hex(block_hash).unwrap()), // Grammar ensures that we have an hexadecimal string.
                    };
                }
                Rule::tx_locktime => locktime = field.as_str().parse().unwrap(), // Grammar ensures that we have digits characters.
                Rule::pubkey => issuers.push(PubKey::Ed25519(
                    ed25519::PublicKey::from_base58(field.as_str()).unwrap(), // Grammar ensures that we have a base58 string.
                )),
                Rule::tx_input => inputs.push(TransactionInput::from_pest_pair(field.into_inner())),
                Rule::tx_unlock => {
                    unlocks.push(TransactionInputUnlocks::from_pest_pair(field.into_inner()))
                }
                Rule::tx_output => {
                    outputs.push(TransactionOutput::from_pest_pair(field.into_inner()))
                }
                Rule::tx_comment => comment = field.as_str(),
                Rule::ed25519_sig => {
                    sigs.push(Sig::Ed25519(
                        ed25519::Signature::from_base64(field.as_str()).unwrap(), // Grammar ensures that we have a base64 string.
                    ));
                }
                Rule::EOI => (),
                _ => fatal_error!("unexpected rule: {:?}", field.as_rule()), // Grammar ensures that we never reach this line
            }
        }

        Ok(TransactionDocument {
            text: Some(doc.to_owned()),
            currency: currency.to_owned(),
            blockstamp,
            locktime,
            issuers,
            inputs,
            unlocks,
            outputs,
            comment: comment.to_owned(),
            signatures: sigs,
            hash: None,
        })
    }
}

impl Document for TransactionDocument {
    type PublicKey = PubKey;

    fn version(&self) -> u16 {
        10
    }

    fn currency(&self) -> &str {
        &self.currency
    }

    fn blockstamp(&self) -> Blockstamp {
        self.blockstamp
    }

    fn issuers(&self) -> &Vec<PubKey> {
        &self.issuers
    }

    fn signatures(&self) -> &Vec<Sig> {
        &self.signatures
    }

    fn as_bytes(&self) -> &[u8] {
        self.as_text_without_signature().as_bytes()
    }
}

impl CompactTextDocument for TransactionDocument {
    fn as_compact_text(&self) -> String {
        let mut issuers_str = String::from("");
        for issuer in self.issuers.clone() {
            issuers_str.push_str("\n");
            issuers_str.push_str(&issuer.to_string());
        }
        let mut inputs_str = String::from("");
        for input in self.inputs.clone() {
            inputs_str.push_str("\n");
            inputs_str.push_str(&input.to_string());
        }
        let mut unlocks_str = String::from("");
        for unlock in self.unlocks.clone() {
            unlocks_str.push_str("\n");
            unlocks_str.push_str(&unlock.to_string());
        }
        let mut outputs_str = String::from("");
        for output in self.outputs.clone() {
            outputs_str.push_str("\n");
            outputs_str.push_str(&output.to_string());
        }
        let mut comment_str = self.comment.clone();
        if !comment_str.is_empty() {
            comment_str.push_str("\n");
        }
        let mut signatures_str = String::from("");
        for sig in self.signatures.clone() {
            signatures_str.push_str(&sig.to_string());
            signatures_str.push_str("\n");
        }
        // Remove end line step
        signatures_str.pop();
        format!(
            "TX:10:{issuers_count}:{inputs_count}:{unlocks_count}:{outputs_count}:{has_comment}:{locktime}
{blockstamp}{issuers}{inputs}{unlocks}{outputs}\n{comment}{signatures}",
            issuers_count = self.issuers.len(),
            inputs_count = self.inputs.len(),
            unlocks_count = self.unlocks.len(),
            outputs_count = self.outputs.len(),
            has_comment = if self.comment.is_empty() { 0 } else { 1 },
            locktime = self.locktime,
            blockstamp = self.blockstamp,
            issuers = issuers_str,
            inputs = inputs_str,
            unlocks = unlocks_str,
            outputs = outputs_str,
            comment = comment_str,
            signatures = signatures_str,
        )
    }
}

impl TextDocument for TransactionDocument {
    type CompactTextDocument_ = TransactionDocument;

    fn as_text(&self) -> &str {
        if let Some(ref text) = self.text {
            text
        } else {
            fatal_error!("Try to get text of tx whti None text !")
        }
    }

    fn to_compact_document(&self) -> Self::CompactTextDocument_ {
        self.clone()
    }
}

/// Transaction document builder.
#[derive(Debug, Copy, Clone)]
pub struct TransactionDocumentBuilder<'a> {
    /// Document currency.
    pub currency: &'a str,
    /// Reference blockstamp.
    pub blockstamp: &'a Blockstamp,
    /// Locktime
    pub locktime: &'a u64,
    /// Transaction Document issuers.
    pub issuers: &'a Vec<PubKey>,
    /// Transaction inputs.
    pub inputs: &'a Vec<TransactionInput>,
    /// Inputs unlocks.
    pub unlocks: &'a Vec<TransactionInputUnlocks>,
    /// Transaction ouputs.
    pub outputs: &'a Vec<TransactionOutput>,
    /// Transaction comment
    pub comment: &'a str,
    /// Transaction hash
    pub hash: Option<Hash>,
}

impl<'a> TransactionDocumentBuilder<'a> {
    fn build_with_text_and_sigs(self, text: String, signatures: Vec<Sig>) -> TransactionDocument {
        TransactionDocument {
            text: Some(text),
            currency: self.currency.to_string(),
            blockstamp: *self.blockstamp,
            locktime: *self.locktime,
            issuers: self.issuers.clone(),
            inputs: self.inputs.clone(),
            unlocks: self.unlocks.clone(),
            outputs: self.outputs.clone(),
            comment: String::from(self.comment),
            signatures,
            hash: self.hash,
        }
    }
}

impl<'a> DocumentBuilder for TransactionDocumentBuilder<'a> {
    type Document = TransactionDocument;
    type PrivateKey = PrivKey;

    fn build_with_signature(&self, signatures: Vec<Sig>) -> TransactionDocument {
        self.build_with_text_and_sigs(self.generate_text(), signatures)
    }

    fn build_and_sign(&self, private_keys: Vec<PrivKey>) -> TransactionDocument {
        let (text, signatures) = self.build_signed_text(private_keys);
        self.build_with_text_and_sigs(text, signatures)
    }
}

impl<'a> TextDocumentBuilder for TransactionDocumentBuilder<'a> {
    fn generate_text(&self) -> String {
        let mut issuers_string: String = "".to_owned();
        let mut inputs_string: String = "".to_owned();
        let mut unlocks_string: String = "".to_owned();
        let mut outputs_string: String = "".to_owned();
        for issuer in self.issuers {
            issuers_string.push_str(&format!("{}\n", issuer.to_string()))
        }
        for input in self.inputs {
            inputs_string.push_str(&format!("{}\n", input.to_string()))
        }
        for unlock in self.unlocks {
            unlocks_string.push_str(&format!("{}\n", unlock.to_string()))
        }
        for output in self.outputs {
            outputs_string.push_str(&format!("{}\n", output.to_string()))
        }
        format!(
            "Version: 10
Type: Transaction
Currency: {currency}
Blockstamp: {blockstamp}
Locktime: {locktime}
Issuers:
{issuers}Inputs:
{inputs}Unlocks:
{unlocks}Outputs:
{outputs}Comment: {comment}
",
            currency = self.currency,
            blockstamp = self.blockstamp,
            locktime = self.locktime,
            issuers = issuers_string,
            inputs = inputs_string,
            unlocks = unlocks_string,
            outputs = outputs_string,
            comment = self.comment,
        )
    }
}

/// Transaction document parser
#[derive(Debug, Clone, Copy)]
pub struct TransactionDocumentParser;

impl TextDocumentParser<Rule> for TransactionDocumentParser {
    type DocumentType = TransactionDocument;

    fn parse(doc: &str) -> Result<Self::DocumentType, TextDocumentParseError> {
        let mut tx_pairs = DocumentsParser::parse(Rule::tx, doc)?;
        let tx_pair = tx_pairs.next().unwrap(); // get and unwrap the `tx` rule; never fails
        Self::from_pest_pair(tx_pair)
    }
    #[inline]
    fn from_pest_pair(pair: Pair<Rule>) -> Result<Self::DocumentType, TextDocumentParseError> {
        let tx_vx_pair = pair.into_inner().next().unwrap(); // get and unwrap the `tx_vX` rule; never fails

        match tx_vx_pair.as_rule() {
            Rule::tx_v10 => Ok(TransactionDocument::from_pest_pair(tx_vx_pair)?),
            _ => Err(TextDocumentParseError::UnexpectedRule(format!(
                "{:#?}",
                tx_vx_pair.as_rule()
            ))),
        }
    }
    #[inline]
    fn from_versioned_pest_pair(
        version: u16,
        pair: Pair<Rule>,
    ) -> Result<Self::DocumentType, TextDocumentParseError> {
        match version {
            10 => Ok(TransactionDocument::from_pest_pair(pair)?),
            v => Err(TextDocumentParseError::UnexpectedVersion(format!(
                "Unsupported version: {}",
                v
            ))),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::Document;

    #[test]
    fn generate_real_document() {
        let pubkey = PubKey::Ed25519(
            ed25519::PublicKey::from_base58("DNann1Lh55eZMEDXeYt59bzHbA3NJR46DeQYCS2qQdLV")
                .unwrap(),
        );

        let prikey = PrivKey::Ed25519(
            ed25519::PrivateKey::from_base58(
                "468Q1XtTq7h84NorZdWBZFJrGkB18CbmbHr9tkp9snt5G\
                 iERP7ySs3wM8myLccbAAGejgMRC9rqnXuW3iAfZACm7",
            )
            .unwrap(),
        );

        let sig = Sig::Ed25519(ed25519::Signature::from_base64(
            "pRQeKlzCsvPNmYAAkEP5jPPQO1RwrtFMRfCajEfkkrG0UQE0DhoTkxG3Zs2JFmvAFLw67pn1V5NQ08zsSfJkBg==",
        ).unwrap());

        let block = Blockstamp::from_string(
            "0-E3B0C44298FC1C149AFBF4C8996FB92427AE41E4649B934CA495991B7852B855",
        )
        .unwrap();

        let builder = TransactionDocumentBuilder {
            currency: "duniter_unit_test_currency",
            blockstamp: &block,
            locktime: &0,
            issuers: &vec![pubkey],
            inputs: &vec![TransactionInput::D(
                TxAmount(10),
                TxBase(0),
                PubKey::Ed25519(
                    ed25519::PublicKey::from_base58("DNann1Lh55eZMEDXeYt59bzHbA3NJR46DeQYCS2qQdLV")
                        .unwrap(),
                ),
                BlockNumber(0),
            )],
            unlocks: &vec![TransactionInputUnlocks {
                index: 0,
                unlocks: vec![TransactionUnlockProof::Sig(0)],
            }],
            outputs: &vec![TransactionOutput::from_str(
                "10:0:SIG(FD9wujR7KABw88RyKEGBYRLz8PA6jzVCbcBAsrBXBqSa)",
            )
            .expect("fail to parse output !")],
            comment: "test",
            hash: None,
        };
        println!(
            "Signature = {:?}",
            builder.build_and_sign(vec![prikey]).signatures()
        );
        assert!(builder
            .build_with_signature(vec![sig])
            .verify_signatures()
            .is_ok());
        assert!(builder
            .build_and_sign(vec![prikey])
            .verify_signatures()
            .is_ok());
    }

    #[test]
    fn compute_transaction_hash() {
        let pubkey = PubKey::Ed25519(
            ed25519::PublicKey::from_base58("FEkbc4BfJukSWnCU6Hed6dgwwTuPFTVdgz5LpL4iHr9J")
                .unwrap(),
        );

        let sig = Sig::Ed25519(ed25519::Signature::from_base64(
            "XEwKwKF8AI1gWPT7elR4IN+bW3Qn02Dk15TEgrKtY/S2qfZsNaodsLofqHLI24BBwZ5aadpC88ntmjo/UW9oDQ==",
        ).unwrap());

        let block = Blockstamp::from_string(
            "60-00001FE00410FCD5991EDD18AA7DDF15F4C8393A64FA92A1DB1C1CA2E220128D",
        )
        .unwrap();

        let builder = TransactionDocumentBuilder {
            currency: "g1",
            blockstamp: &block,
            locktime: &0,
            issuers: &vec![pubkey],
            inputs: &vec![TransactionInput::T(
                TxAmount(950),
                TxBase(0),
                Hash::from_hex("2CF1ACD8FE8DC93EE39A1D55881C50D87C55892AE8E4DB71D4EBAB3D412AA8FD")
                    .unwrap(),
                TxIndex(1),
            )],
            unlocks: &vec![
                TransactionInputUnlocks::from_str("0:SIG(0)").expect("fail to parse unlock !")
            ],
            outputs: &vec![
                TransactionOutput::from_str(
                    "30:0:SIG(38MEAZN68Pz1DTvT3tqgxx4yQP6snJCQhPqEFxbDk4aE)",
                )
                .expect("fail to parse output !"),
                TransactionOutput::from_str(
                    "920:0:SIG(FEkbc4BfJukSWnCU6Hed6dgwwTuPFTVdgz5LpL4iHr9J)",
                )
                .expect("fail to parse output !"),
            ],
            comment: "Pour cesium merci",
            hash: None,
        };
        let mut tx_doc = builder.build_with_signature(vec![sig]);
        tx_doc.hash = None;
        assert!(tx_doc.verify_signatures().is_ok());
        assert_eq!(
            tx_doc.get_hash(),
            Hash::from_hex("876D2430E0B66E2CE4467866D8F923D68896CACD6AA49CDD8BDD0096B834DEF1")
                .expect("fail to parse hash")
        );
    }

    #[test]
    fn parse_transaction_document() {
        let doc = "Version: 10
Type: Transaction
Currency: duniter_unit_test_currency
Blockstamp: 204-00003E2B8A35370BA5A7064598F628A62D4E9EC1936BE8651CE9A85F2E06981B
Locktime: 0
Issuers:
DNann1Lh55eZMEDXeYt59bzHbA3NJR46DeQYCS2qQdLV
4tNQ7d9pj2Da5wUVoW9mFn7JjuPoowF977au8DdhEjVR
FD9wujR7KABw88RyKEGBYRLz8PA6jzVCbcBAsrBXBqSa
Inputs:
40:2:T:6991C993631BED4733972ED7538E41CCC33660F554E3C51963E2A0AC4D6453D3:2
70:2:T:3A09A20E9014110FD224889F13357BAB4EC78A72F95CA03394D8CCA2936A7435:8
20:2:D:DNann1Lh55eZMEDXeYt59bzHbA3NJR46DeQYCS2qQdLV:46
70:2:T:A0D9B4CDC113ECE1145C5525873821398890AE842F4B318BD076095A23E70956:3
20:2:T:67F2045B5318777CC52CD38B424F3E40DDA823FA0364625F124BABE0030E7B5B:5
15:2:D:FD9wujR7KABw88RyKEGBYRLz8PA6jzVCbcBAsrBXBqSa:46
Unlocks:
0:SIG(0)
1:XHX(7665798292)
2:SIG(0)
3:SIG(0) SIG(2)
4:SIG(0) SIG(1) SIG(2)
5:SIG(2)
Outputs:
120:2:SIG(BYfWYFrsyjpvpFysgu19rGK3VHBkz4MqmQbNyEuVU64g)
146:2:SIG(DSz4rgncXCytsUMW2JU2yhLquZECD2XpEkpP9gG5HyAx)
49:2:(SIG(6DyGr5LFtFmbaJYRvcs9WmBsr4cbJbJ1EV9zBbqG7A6i) || XHX(3EB4702F2AC2FD3FA4FDC46A4FC05AE8CDEE1A85F2AC2FD3FA4FDC46A4FC01CA))
Comment: -----@@@----- (why not this comment?)
kL59C1izKjcRN429AlKdshwhWbasvyL7sthI757zm1DfZTdTIctDWlKbYeG/tS7QyAgI3gcfrTHPhu1E1lKCBw==
e3LpgB2RZ/E/BCxPJsn+TDDyxGYzrIsMyDt//KhJCjIQD6pNUxr5M5jrq2OwQZgwmz91YcmoQ2XRQAUDpe4BAw==
w69bYgiQxDmCReB0Dugt9BstXlAKnwJkKCdWvCeZ9KnUCv0FJys6klzYk/O/b9t74tYhWZSX0bhETWHiwfpWBw==";

        let doc = TransactionDocumentParser::parse(doc)
            .expect("fail to parse test transaction document !");
        //println!("Doc : {:?}", doc);
        println!("{}", doc.generate_compact_text());
        assert!(doc.verify_signatures().is_ok());
        assert_eq!(
            doc.generate_compact_text(),
            "TX:10:3:6:6:3:1:0
204-00003E2B8A35370BA5A7064598F628A62D4E9EC1936BE8651CE9A85F2E06981B
DNann1Lh55eZMEDXeYt59bzHbA3NJR46DeQYCS2qQdLV
4tNQ7d9pj2Da5wUVoW9mFn7JjuPoowF977au8DdhEjVR
FD9wujR7KABw88RyKEGBYRLz8PA6jzVCbcBAsrBXBqSa
40:2:T:6991C993631BED4733972ED7538E41CCC33660F554E3C51963E2A0AC4D6453D3:2
70:2:T:3A09A20E9014110FD224889F13357BAB4EC78A72F95CA03394D8CCA2936A7435:8
20:2:D:DNann1Lh55eZMEDXeYt59bzHbA3NJR46DeQYCS2qQdLV:46
70:2:T:A0D9B4CDC113ECE1145C5525873821398890AE842F4B318BD076095A23E70956:3
20:2:T:67F2045B5318777CC52CD38B424F3E40DDA823FA0364625F124BABE0030E7B5B:5
15:2:D:FD9wujR7KABw88RyKEGBYRLz8PA6jzVCbcBAsrBXBqSa:46
0:SIG(0)
1:XHX(7665798292)
2:SIG(0)
3:SIG(0) SIG(2)
4:SIG(0) SIG(1) SIG(2)
5:SIG(2)
120:2:SIG(BYfWYFrsyjpvpFysgu19rGK3VHBkz4MqmQbNyEuVU64g)
146:2:SIG(DSz4rgncXCytsUMW2JU2yhLquZECD2XpEkpP9gG5HyAx)
49:2:(SIG(6DyGr5LFtFmbaJYRvcs9WmBsr4cbJbJ1EV9zBbqG7A6i) || XHX(3EB4702F2AC2FD3FA4FDC46A4FC05AE8CDEE1A85F2AC2FD3FA4FDC46A4FC01CA))
-----@@@----- (why not this comment?)
kL59C1izKjcRN429AlKdshwhWbasvyL7sthI757zm1DfZTdTIctDWlKbYeG/tS7QyAgI3gcfrTHPhu1E1lKCBw==
e3LpgB2RZ/E/BCxPJsn+TDDyxGYzrIsMyDt//KhJCjIQD6pNUxr5M5jrq2OwQZgwmz91YcmoQ2XRQAUDpe4BAw==
w69bYgiQxDmCReB0Dugt9BstXlAKnwJkKCdWvCeZ9KnUCv0FJys6klzYk/O/b9t74tYhWZSX0bhETWHiwfpWBw=="
        );
    }
}