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
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
// LNP/BP Core Library implementing LNPBP specifications & standards
// Written in 2019 by
//     Dr. Maxim Orlovsky <orlovsky@pandoracore.com>
//
// To the extent possible under law, the author(s) have dedicated all
// copyright and related and neighboring rights to this software to
// the public domain worldwide. This software is distributed without
// any warranty.
//
// You should have received a copy of the MIT License
// along with this software.
// If not, see <https://opensource.org/licenses/MIT>.

use std::cmp::Ordering;
use std::fmt::{Debug, Display};
use std::{convert::TryFrom, fmt, io, str::FromStr};

use bitcoin::hashes::hex::{self, FromHex, ToHex};
use bitcoin::hashes::{sha256d, Hash};
use bitcoin::BlockHash;

use crate::strict_encoding::{
    self, strict_deserialize, strict_serialize, StrictDecode, StrictEncode,
};

/// P2P network magic number: prefix identifying network on which node operates
pub type P2pMagicNumber = u32;
/// Magic number prefixing Pubkey or Prvkey data according to BIP32 spec
pub type Bip32MagicNumber = u32;

// TODO: (new) Move constants to rust-bitcoin
/// Magic number used in P2P networking protocol by bitcoin mainnet
pub const P2P_MAGIC_MAINNET: P2pMagicNumber = 0xD9B4BEF9;
/// Magic number used in P2P networking protocol by bitcoin testnet v3
pub const P2P_MAGIC_TESTNET: P2pMagicNumber = 0x0709110B;
/// Magic number used in P2P networking protocol by bitcoin regtests
pub const P2P_MAGIC_REGTEST: P2pMagicNumber = 0xDAB5BFFA;
/// Magic number used in P2P networking protocol by bitcoin signet
pub const P2P_MAGIC_SIGNET: P2pMagicNumber = 0x40CF030A;

/// P2P network magic number: prefix identifying network on which node operates.
/// This enum defines known magic network numbers, plus adds support to
/// arbitrary unknown with [P2pNetworkId::Other] variant.
/// This enum differs from bitcoin::Network in its ability to support
/// non-standard and non-predefined networks
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(
    feature = "serde",
    derive(Serialize, Deserialize),
    serde(crate = "serde_crate", rename_all = "kebab-case")
)]
#[non_exhaustive]
#[repr(u32)]
pub enum P2pNetworkId {
    /// Bitcoin magic number for mainnet P2P communications
    Mainnet,

    /// Bitcoin magic number for testnet P2P communications
    Testnet,

    /// Bitcoin magic number for regtest P2P communications
    Regtest,

    /// Bitcoin magic number for signet P2P communications
    Signet,

    /// Other magic number, implying some unknown network
    Other(P2pMagicNumber),
}

impl P2pNetworkId {
    pub fn from_magic(magic: P2pMagicNumber) -> Self {
        match magic {
            m if m == P2pNetworkId::Mainnet.as_magic() => P2pNetworkId::Mainnet,
            m if m == P2pNetworkId::Testnet.as_magic() => P2pNetworkId::Testnet,
            m if m == P2pNetworkId::Regtest.as_magic() => P2pNetworkId::Regtest,
            m if m == P2pNetworkId::Signet.as_magic() => P2pNetworkId::Signet,
            m => P2pNetworkId::Other(m),
        }
    }

    pub fn as_magic(&self) -> P2pMagicNumber {
        match self {
            P2pNetworkId::Mainnet => P2P_MAGIC_MAINNET,
            P2pNetworkId::Testnet => P2P_MAGIC_TESTNET,
            P2pNetworkId::Regtest => P2P_MAGIC_REGTEST,
            P2pNetworkId::Signet => P2P_MAGIC_SIGNET,
            P2pNetworkId::Other(n) => *n,
        }
    }
}

impl StrictEncode for P2pNetworkId {
    #[inline]
    fn strict_encode<E: io::Write>(
        &self,
        e: E,
    ) -> Result<usize, strict_encoding::Error> {
        Ok(self.as_magic().strict_encode(e)?)
    }
}

impl StrictDecode for P2pNetworkId {
    #[inline]
    fn strict_decode<D: io::Read>(
        d: D,
    ) -> Result<Self, strict_encoding::Error> {
        Ok(Self::from_magic(u32::strict_decode(d)?))
    }
}

impl Debug for P2pNetworkId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}({:#x?})", self, self.as_magic())
    }
}

impl Display for P2pNetworkId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            P2pNetworkId::Mainnet => f.write_str("mainnet"),
            P2pNetworkId::Testnet => f.write_str("testnet"),
            P2pNetworkId::Regtest => f.write_str("regtest"),
            P2pNetworkId::Signet => f.write_str("signet"),
            P2pNetworkId::Other(_) => f.write_str("unknown"),
        }
    }
}

impl From<P2pMagicNumber> for P2pNetworkId {
    fn from(magic: P2pMagicNumber) -> Self {
        P2pNetworkId::from_magic(magic)
    }
}

impl From<P2pNetworkId> for P2pMagicNumber {
    fn from(network: P2pNetworkId) -> Self {
        network.as_magic()
    }
}

impl From<bitcoin::Network> for P2pNetworkId {
    fn from(bn: bitcoin::Network) -> Self {
        match bn {
            bitcoin::Network::Bitcoin => P2pNetworkId::Mainnet,
            bitcoin::Network::Testnet => P2pNetworkId::Testnet,
            bitcoin::Network::Regtest => P2pNetworkId::Regtest,
            bitcoin::Network::Signet => P2pNetworkId::Signet,
        }
    }
}

/// Indicates that [`bitcoin::Network`] does not has a correspondense for a
/// given [`P2pNetworkId`] variant
#[derive(Clone, Copy, PartialEq, Eq, Debug, Display, Error)]
#[display(Debug)]
pub struct ConversionImpossibleError;

impl TryFrom<P2pNetworkId> for bitcoin::Network {
    type Error = ConversionImpossibleError;
    fn try_from(bn: P2pNetworkId) -> Result<Self, Self::Error> {
        Ok(match bn {
            P2pNetworkId::Mainnet => bitcoin::Network::Bitcoin,
            P2pNetworkId::Testnet => bitcoin::Network::Testnet,
            P2pNetworkId::Regtest => bitcoin::Network::Regtest,
            P2pNetworkId::Signet => bitcoin::Network::Signet,
            P2pNetworkId::Other(magic) if magic == P2P_MAGIC_MAINNET => {
                bitcoin::Network::Bitcoin
            }
            P2pNetworkId::Other(magic) if magic == P2P_MAGIC_TESTNET => {
                bitcoin::Network::Testnet
            }
            P2pNetworkId::Other(magic) if magic == P2P_MAGIC_REGTEST => {
                bitcoin::Network::Regtest
            }
            _ => Err(ConversionImpossibleError)?,
        })
    }
}

hash_newtype!(
    AssetId,
    sha256d::Hash,
    32,
    doc = "Universal asset identifier for on-chain and off-chain assets; for \
           on-chain assets matches genesis hash of the chain, but displayed in \
           normal, non-reverse order",
    false
);
impl strict_encoding::Strategy for AssetId {
    type Strategy = strict_encoding::strategies::HashFixedBytes;
}

impl From<BlockHash> for AssetId {
    fn from(block_hash: BlockHash) -> Self {
        AssetId::from_inner(block_hash.into_inner())
    }
}

/// Genesis block hash for bitcoin mainnet
pub const GENESIS_HASH_MAINNET: &[u8] = &[
    0x6f, 0xe2, 0x8c, 0x0a, 0xb6, 0xf1, 0xb3, 0x72, 0xc1, 0xa6, 0xa2, 0x46,
    0xae, 0x63, 0xf7, 0x4f, 0x93, 0x1e, 0x83, 0x65, 0xe1, 0x5a, 0x08, 0x9c,
    0x68, 0xd6, 0x19, 0x00, 0x00, 0x00, 0x00, 0x00,
];

/// Genesis block hash for bitcoin testnet v3
pub const GENESIS_HASH_TESTNET: &[u8] = &[
    0x43, 0x49, 0x7f, 0xd7, 0xf8, 0x26, 0x95, 0x71, 0x08, 0xf4, 0xa3, 0x0f,
    0xd9, 0xce, 0xc3, 0xae, 0xba, 0x79, 0x97, 0x20, 0x84, 0xe9, 0x0e, 0xad,
    0x01, 0xea, 0x33, 0x09, 0x00, 0x00, 0x00, 0x00,
];

/// Genesis block hash for bitcoin regtest network(s)
pub const GENESIS_HASH_REGTEST: &[u8] = &[
    0x06, 0x22, 0x6e, 0x46, 0x11, 0x1a, 0x0b, 0x59, 0xca, 0xaf, 0x12, 0x60,
    0x43, 0xeb, 0x5b, 0xbf, 0x28, 0xc3, 0x4f, 0x3a, 0x5e, 0x33, 0x2a, 0x1f,
    0xc7, 0xb2, 0xb7, 0x3c, 0xf1, 0x88, 0x91, 0x0f,
];

/// Genesis block hash for bitcoin signet (default network)
pub const GENESIS_HASH_SIGNET: &[u8] = &[
    0xf6, 0x1e, 0xee, 0x3b, 0x63, 0xa3, 0x80, 0xa4, 0x77, 0xa0, 0x63, 0xaf,
    0x32, 0xb2, 0xbb, 0xc9, 0x7c, 0x9f, 0xf9, 0xf0, 0x1f, 0x2c, 0x42, 0x25,
    0xe9, 0x73, 0x98, 0x81, 0x08, 0x00, 0x00, 0x00,
];

/// Genesis block hash for liquid v1 sidechain
pub const GENESIS_HASH_LIQUIDV1: &[u8] = &[
    0x14, 0x66, 0x27, 0x58, 0x36, 0x22, 0x0d, 0xb2, 0x94, 0x4c, 0xa0, 0x59,
    0xa3, 0xa1, 0x0e, 0xf6, 0xfd, 0x2e, 0xa6, 0x84, 0xb0, 0x68, 0x8d, 0x2c,
    0x37, 0x92, 0x96, 0x88, 0x8a, 0x20, 0x60, 0x03,
];

lazy_static! {
    /// Bitcoin mainnet chain parameters
    static ref CHAIN_PARAMS_MAINNET: ChainParams = ChainParams {
        name: "bitcoin".to_string(),
        p2p_magic: P2pNetworkId::Mainnet,
        genesis_hash: BlockHash::from_slice(GENESIS_HASH_MAINNET)
            .expect("Bitcoin genesis hash contains invalid binary data"),
        bip70_name: "main".to_string(),
        bip173_prefix: "bc".to_string(),
        p2p_port: 8333,
        rpc_port: 8332,
        ln_height: 504500,
        // TODO: (new) update with first RGB release
        rgb_height: 650000,
        format: ChainFormat::Bitcoin,
        dust_limit: 546,
        native_asset: AssetParams {
            ticker: "BTC".to_string(),
            unit_of_accounting: "Bitcoin".to_string(),
            indivisible_unit: "satoshi".to_string(),
            divisibility: 100_000_000,
            asset_id: AssetId::from_slice(GENESIS_HASH_MAINNET)
                .expect("Bitcoin genesis hash contains invalid binary data"),
            asset_system: AssetSystem::NativeBlockchain,
        },
        is_testnet: false,
        is_pow: true,
    };

    /// Bitcoin testnet chain parameters
    static ref CHAIN_PARAMS_TESTNET: ChainParams = ChainParams {
        name: "testnet".to_string(),
        p2p_magic: P2pNetworkId::Testnet,
        genesis_hash: BlockHash::from_slice(GENESIS_HASH_TESTNET)
            .expect("Bitcoin testnet genesis hash contains invalid binary data"),
        bip70_name: "test".to_string(),
        bip173_prefix: "tb".to_string(),
        p2p_port: 18333,
        rpc_port: 18332,
        ln_height: 1,
        // TODO: (new) update with first RGB release
        rgb_height: 1835500,
        format: ChainFormat::Bitcoin,
        dust_limit: 546,
        native_asset: AssetParams {
            ticker: "tBTC".to_string(),
            unit_of_accounting: "Test Bitcoin".to_string(),
            indivisible_unit: "Test satoshi".to_string(),
            divisibility: 100_000_000,
            asset_id: AssetId::from_slice(GENESIS_HASH_TESTNET)
                .expect("Bitcoin testnet genesis hash contains invalid binary data"),
            asset_system: AssetSystem::NativeBlockchain,
        },
        is_testnet: true,
        is_pow: true,
    };

    /// Bitcoin regtest chain parameters
    static ref CHAIN_PARAMS_REGTEST: ChainParams = ChainParams {
        name: "regtest".to_string(),
        p2p_magic: P2pNetworkId::Regtest,
        genesis_hash: BlockHash::from_slice(GENESIS_HASH_REGTEST)
            .expect("Bitcoin regtest genesis hash contains invalid binary data"),
        bip70_name: "regtest".to_string(),
        bip173_prefix: "tb".to_string(),
        p2p_port: 28333,
        rpc_port: 28332,
        ln_height: 1,
        rgb_height: 1,
        format: ChainFormat::Bitcoin,
        dust_limit: 546,
        native_asset: AssetParams {
            ticker: "tBTC".to_string(),
            unit_of_accounting: "Test Bitcoin".to_string(),
            indivisible_unit: "Test satoshi".to_string(),
            divisibility: 100_000_000,
            asset_id: AssetId::from_slice(GENESIS_HASH_REGTEST)
                .expect("Bitcoin regtest genesis hash contains invalid binary data"),
            asset_system: AssetSystem::NativeBlockchain,
        },
        is_testnet: true,
        is_pow: false,
    };

    /// Bitcoin signet chain parameters
    static ref CHAIN_PARAMS_SIGNET: ChainParams = ChainParams {
        name: "signet".to_string(),
        p2p_magic: P2pNetworkId::Signet,
        genesis_hash: BlockHash::from_slice(GENESIS_HASH_SIGNET)
            .expect("Bitcoin signet genesis hash contains invalid binary data"),
        bip70_name: "signet".to_string(),
        bip173_prefix: "tb".to_string(),
        p2p_port: 38333,
        rpc_port: 38332,
        ln_height: 1,
        rgb_height: 1,
        format: ChainFormat::Bitcoin,
        dust_limit: 546,
        native_asset: AssetParams {
            ticker: "sBTC".to_string(),
            unit_of_accounting: "Signet Bitcoin".to_string(),
            indivisible_unit: "Signet satoshi".to_string(),
            divisibility: 100_000_000,
            asset_id: AssetId::from_slice(GENESIS_HASH_SIGNET)
                .expect("Bitcoin signet genesis hash contains invalid binary data"),
            asset_system: AssetSystem::NativeBlockchain,
        },
        is_testnet: true,
        is_pow: false,
    };

    /// Liquid V1 chain parameters
    static ref CHAIN_PARAMS_LIQUIDV1: ChainParams = ChainParams {
        name: "liquidv1".to_string(),
        // TODO: (new) check Liquid network magic number and change this if needed
        p2p_magic: P2pNetworkId::Mainnet,
        genesis_hash: BlockHash::from_slice(GENESIS_HASH_LIQUIDV1)
            .expect("Liquid V1 genesis hash contains invalid binary data"),
        bip70_name: "liquidv1".to_string(),
        bip173_prefix: "ex".to_string(),
        p2p_port: 7042,
        rpc_port: 7041,
        ln_height: 1,
        rgb_height: 1_000_000,
        format: ChainFormat::Elements,
        dust_limit: 546,
        native_asset: AssetParams {
            ticker: "LBTC".to_string(),
            unit_of_accounting: "Liquid Bitcoin".to_string(),
            indivisible_unit: "Liquid satoshi".to_string(),
            divisibility: 100_000_000,
            asset_id: AssetId::from_slice(GENESIS_HASH_LIQUIDV1)
                .expect("Liquid V1 genesis hash contains invalid binary data"),
            asset_system: AssetSystem::NativeBlockchain,
        },
        is_testnet: false,
        is_pow: false,
    };
}

/// Enum identifying format for transaction & block structure in a given chain.
/// Right now only two structures are supported: Bitcoin format and
/// Elements format, extended with confidential transaction-specific structures.
#[derive(
    Clone,
    Copy,
    PartialEq,
    Eq,
    PartialOrd,
    Ord,
    Debug,
    Display,
    Hash,
    StrictEncode,
    StrictDecode,
)]
#[display(Debug)]
#[cfg_attr(
    feature = "serde",
    derive(Serialize, Deserialize),
    serde(crate = "serde_crate", rename_all = "kebab-case")
)]
#[non_exhaustive]
#[repr(u8)]
pub enum ChainFormat {
    /// Bitcoin standard format (bitcoin networks, litecoin)
    Bitcoin = 0,
    /// Confidential transactions format
    Elements = 1,
}

/// Layers on which a given asset can operate
#[derive(
    Clone,
    Copy,
    PartialEq,
    Eq,
    PartialOrd,
    Ord,
    Debug,
    Display,
    Hash,
    StrictEncode,
    StrictDecode,
)]
#[display(Debug)]
#[cfg_attr(
    feature = "serde",
    derive(Serialize, Deserialize),
    serde(crate = "serde_crate", rename_all = "kebab-case")
)]
#[repr(u8)]
pub enum AssetLayer {
    /// Native chain asset(s), which can operate both on the layer of
    /// blockchain and payment/state channels (Bitcoin, sidechain-specific
    /// asset(s), like liquidBTC or confidential assets in Liquid)
    Layer1and2 = 1,

    /// Derived assets, which are created and defined above blockchain (like
    /// RGB), but also can be used on top of payment/state channels
    Layer2and3 = 2,
}

#[derive(
    Clone,
    Copy,
    PartialEq,
    Eq,
    PartialOrd,
    Ord,
    Debug,
    Display,
    Hash,
    StrictEncode,
    StrictDecode,
)]
#[cfg_attr(
    feature = "serde",
    derive(Serialize, Deserialize),
    serde(crate = "serde_crate", rename_all = "kebab-case")
)]
#[display(Debug)]
#[non_exhaustive]
#[repr(u8)]
pub enum AssetSystem {
    /// Native blockchain asset, including liquid bitcoin in LiquidV1 network
    NativeBlockchain = 0,

    /// Liquid confidential assets used in LiquidV1 network
    ConfidentialAssets = 1,

    /// RGB confidential assets
    RgbContract = 2,
}

/// Parameters for a given asset, which are shared between different types of
/// Layer 1, 2 and 3 assets.
#[derive(Clone, PartialOrd, Ord, Debug, Display, Hash)]
#[cfg_attr(
    feature = "serde",
    derive(Serialize, Deserialize),
    serde(crate = "serde_crate", rename_all = "kebab-case")
)]
#[display(Debug)]
pub struct AssetParams {
    /// Short asset name, or ticker, like BTC for bitcoin. Case-sensitive with
    /// default use of uppercase.
    pub ticker: String,

    /// Full name for a given asset as a unit of accounting, for instance
    /// "Bitcoin". Also case-sensitive.
    pub unit_of_accounting: String,

    /// Full name for the smallest indivisible unit, like "satoshi" for
    /// Bitcoin network
    pub indivisible_unit: String,

    /// Number of smallest indivisible units inside the unit of accounting
    pub divisibility: u64,

    /// Identifier of the asset; for native chain assets matches to the
    /// genesis block hash of the chain itself (i.e.
    /// [ChainParams::genesis_hash]), for other assets are specific to a given
    /// asset system: for confidential assets this is an `AssetId`, for
    /// RGB – hash of asset genesis transition, i.e. `ContractId`.
    pub asset_id: AssetId,

    /// [AssetSystem] in which asset is defined
    pub asset_system: AssetSystem,
}

impl PartialEq for AssetParams {
    fn eq(&self, other: &Self) -> bool {
        // There negligible change that any two hashes will collide, however we
        // are taking responsible approach here:
        self.asset_id == other.asset_id
            && self.asset_system == other.asset_system
    }
}

impl Eq for AssetParams {}

impl StrictEncode for AssetParams {
    #[inline]
    fn strict_encode<E: io::Write>(
        &self,
        mut e: E,
    ) -> Result<usize, strict_encoding::Error> {
        Ok(strict_encode_list!(e;
            self.ticker,
            self.unit_of_accounting,
            self.indivisible_unit,
            self.divisibility,
            self.asset_id,
            self.asset_system
        ))
    }
}

impl StrictDecode for AssetParams {
    #[inline]
    fn strict_decode<D: io::Read>(
        mut d: D,
    ) -> Result<Self, strict_encoding::Error> {
        Ok(strict_decode_self!(d;
            ticker,
            unit_of_accounting,
            indivisible_unit,
            divisibility,
            asset_id,
            asset_system
        ))
    }
}

/// Full set of parameters which uniquely define given blockchain,
/// corresponding P2P network and RPC interface of fully validating nodes
#[derive(
    Clone, PartialOrd, Ord, Debug, Display, Hash, StrictEncode, StrictDecode,
)]
#[cfg_attr(
    feature = "serde",
    derive(Serialize, Deserialize),
    serde(crate = "serde_crate")
)]
#[display(Debug)]
pub struct ChainParams {
    /// Hash of the genesis block, uniquely defining chain
    pub genesis_hash: BlockHash,

    /// Blockchain name, including version:
    /// - mainnet for Bitcoin mainnet
    /// - testnet3 for Bitcoin testnet version 3
    /// - regtest for Bitcoin regtest networks
    /// - signet for Bitcoin signet and private signet networks
    /// - liquidv1 for Liquid network v1
    pub name: String,

    /// Magic number used as prefix in P2P network API
    pub p2p_magic: P2pNetworkId,

    /// Network name according to BIP 70, which may be different from
    /// [ChainParams::name]. Not widely used these days, but we still have to
    /// account for standard.
    pub bip70_name: String,

    /// HRP bech32 address prefix as defined in BIP 173
    pub bip173_prefix: String,

    /// Default port for P2P network
    pub p2p_port: u16,

    /// Default port for full validating node RPC interface
    pub rpc_port: u16,

    /// Block number from which Lightning network support had started using
    /// the given chain
    pub ln_height: u32,

    /// Block number from which RGB had started using the given chain
    pub rgb_height: u32,

    /// Format of chain-specific data. See [ChainFormat] for more information
    pub format: ChainFormat,

    /// Dust limit for the given chain; 0 if none dust limit applies
    pub dust_limit: u64,

    /// Parameters of the native chain asset (can be only one; it is the asset
    /// in which miners are got paid).
    pub native_asset: AssetParams,

    /// Flag indicating any kind of testnet network that do not operate with
    /// real economic values
    pub is_testnet: bool,

    /// Flag indicating blockchains that use PoW consensus algorithm
    pub is_pow: bool,
}

impl PartialEq for ChainParams {
    fn eq(&self, other: &Self) -> bool {
        self.genesis_hash == other.genesis_hash
    }
}

impl Eq for ChainParams {}

/// A set of recommended standard networks. Differs from bitcoin::Network in
/// ability to support non-standard and non-predefined networks
#[derive(Clone, Debug, Hash)]
#[cfg_attr(
    feature = "serde",
    derive(Serialize, Deserialize),
    serde(crate = "serde_crate", rename_all = "kebab-case")
)]
#[non_exhaustive]
#[repr(u32)]
pub enum Chain {
    /// Bitcoin mainnet
    Mainnet,

    /// Bitcoin testnet version 3
    Testnet3,

    /// Bitcoin regtest network, with provided genesis hash to distinguish
    /// different private networks
    Regtest(BlockHash),

    /// Default bitcoin signet network
    Signet,

    /// Some private bitcoin signet network, with provided genesis hash to
    /// distinguish private networks from each other
    SignetCustom(BlockHash),

    /// Liquidv1 sidechain & network by Blockstream
    LiquidV1,

    /// All other networks/chains, providing full information on chain
    /// parameters
    Other(ChainParams),
}

impl Default for Chain {
    fn default() -> Self {
        Chain::Signet
    }
}

impl PartialEq for Chain {
    fn eq(&self, other: &Self) -> bool {
        self.chain_params().eq(&other.chain_params())
    }
}

impl Eq for Chain {}

impl PartialOrd for Chain {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        self.chain_params().partial_cmp(&other.chain_params())
    }
}

impl Ord for Chain {
    fn cmp(&self, other: &Self) -> Ordering {
        self.chain_params().cmp(&other.chain_params())
    }
}

impl Chain {
    /// Returns chain parameters [ChainParams] for a given chain id
    pub fn chain_params(&self) -> ChainParams {
        match self {
            Chain::Mainnet => CHAIN_PARAMS_MAINNET.clone(),
            Chain::Testnet3 => CHAIN_PARAMS_TESTNET.clone(),
            Chain::Regtest(hash) => {
                let mut regtest = CHAIN_PARAMS_REGTEST.clone();
                regtest.genesis_hash = *hash;
                regtest
            }
            Chain::Signet => CHAIN_PARAMS_SIGNET.clone(),
            Chain::SignetCustom(hash) => {
                let mut signet = CHAIN_PARAMS_SIGNET.clone();
                signet.genesis_hash = *hash;
                signet
            }
            Chain::LiquidV1 => CHAIN_PARAMS_LIQUIDV1.clone(),
            Chain::Other(params) => params.clone(),
        }
    }

    /// Returns hash of genesis block
    pub fn as_genesis_hash(&self) -> &BlockHash {
        match self {
            Chain::Mainnet => &CHAIN_PARAMS_MAINNET.genesis_hash,
            Chain::Testnet3 => &CHAIN_PARAMS_TESTNET.genesis_hash,
            Chain::Regtest(hash) => hash,
            Chain::Signet => &CHAIN_PARAMS_SIGNET.genesis_hash,
            Chain::SignetCustom(hash) => hash,
            Chain::LiquidV1 => &CHAIN_PARAMS_LIQUIDV1.genesis_hash,
            Chain::Other(params) => &params.genesis_hash,
        }
    }

    /// Gueses chain from the given genesis block hash, returning
    /// [Option::None] if the hash is unknown. This implies that for
    /// custom signet and some regtest networks with modified genesis the
    /// function will fail.
    pub fn from_genesis_hash(hash: &BlockHash) -> Option<Self> {
        match hash {
            h if *h == CHAIN_PARAMS_MAINNET.genesis_hash => Some(Self::Mainnet),
            h if *h == CHAIN_PARAMS_TESTNET.genesis_hash => {
                Some(Self::Testnet3)
            }
            h if *h == CHAIN_PARAMS_SIGNET.genesis_hash => Some(Self::Signet),
            h if *h == CHAIN_PARAMS_REGTEST.genesis_hash => {
                Some(Self::Regtest(*h))
            }
            h if *h == CHAIN_PARAMS_LIQUIDV1.genesis_hash => {
                Some(Self::LiquidV1)
            }
            _ => None,
        }
    }
}

impl StrictEncode for Chain {
    #[inline]
    fn strict_encode<E: io::Write>(
        &self,
        e: E,
    ) -> Result<usize, strict_encoding::Error> {
        Ok(self.chain_params().strict_encode(e)?)
    }
}

impl StrictDecode for Chain {
    #[inline]
    fn strict_decode<D: io::Read>(
        d: D,
    ) -> Result<Self, strict_encoding::Error> {
        Ok(Self::from(ChainParams::strict_decode(d)?))
    }
}

impl From<ChainParams> for Chain {
    fn from(params: ChainParams) -> Self {
        match params {
            p if p == Chain::Mainnet.chain_params() => Chain::Mainnet,
            p if p == Chain::Testnet3.chain_params() => Chain::Testnet3,
            p if p == Chain::Signet.chain_params() => Chain::Signet,
            p if p == Chain::LiquidV1.chain_params() => Chain::LiquidV1,
            p if p == Chain::Regtest(p.genesis_hash).chain_params() => {
                Chain::Regtest(p.genesis_hash)
            }
            p if p == Chain::SignetCustom(p.genesis_hash).chain_params() => {
                Chain::SignetCustom(p.genesis_hash)
            }
            p => Chain::Other(p),
        }
    }
}

impl From<bitcoin::Network> for Chain {
    fn from(bn: bitcoin::Network) -> Self {
        match bn {
            bitcoin::Network::Bitcoin => Chain::Mainnet,
            bitcoin::Network::Testnet => Chain::Testnet3,
            bitcoin::Network::Regtest => {
                Chain::Regtest(CHAIN_PARAMS_REGTEST.genesis_hash)
            }
            bitcoin::Network::Signet => Chain::Signet,
        }
    }
}

impl TryFrom<Chain> for bitcoin::Network {
    type Error = ConversionImpossibleError;
    fn try_from(chain: Chain) -> Result<Self, Self::Error> {
        bitcoin::Network::try_from(&chain)
    }
}

impl TryFrom<&Chain> for bitcoin::Network {
    type Error = ConversionImpossibleError;
    fn try_from(chain: &Chain) -> Result<Self, Self::Error> {
        Ok(match chain {
            Chain::Mainnet => bitcoin::Network::Bitcoin,
            Chain::Testnet3 => bitcoin::Network::Testnet,
            Chain::Regtest(hash)
                if hash == &CHAIN_PARAMS_REGTEST.genesis_hash =>
            {
                bitcoin::Network::Regtest
            }
            _ => Err(ConversionImpossibleError)?,
        })
    }
}

impl Display for Chain {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Chain::Mainnet => write!(f, "bitcoin"),
            Chain::Testnet3 => write!(f, "testnet"),
            Chain::Regtest(hash) if &hash[..] == GENESIS_HASH_REGTEST => {
                write!(f, "regtest")
            }
            Chain::Regtest(hash) => write!(f, "regtest:{}", hash),
            Chain::Signet => write!(f, "signet"),
            Chain::SignetCustom(hash) if &hash[..] == GENESIS_HASH_SIGNET => {
                write!(f, "signet")
            }
            Chain::SignetCustom(hash) => write!(f, "signet:{}", hash),
            Chain::LiquidV1 => write!(f, "liquidv1"),
            Chain::Other(params)
                if &params.genesis_hash[..] == GENESIS_HASH_MAINNET =>
            {
                write!(f, "bitcoin")
            }
            Chain::Other(params)
                if &params.genesis_hash[..] == GENESIS_HASH_TESTNET =>
            {
                write!(f, "testnet")
            }
            Chain::Other(params)
                if &params.genesis_hash[..] == GENESIS_HASH_REGTEST =>
            {
                write!(f, "regtest")
            }
            Chain::Other(params)
                if &params.genesis_hash[..] == GENESIS_HASH_SIGNET =>
            {
                write!(f, "signet")
            }
            Chain::Other(params)
                if &params.genesis_hash[..] == GENESIS_HASH_LIQUIDV1 =>
            {
                write!(f, "liquidv1")
            }
            Chain::Other(params) => {
                write!(f, "other:{}", strict_serialize(params)?.to_hex())
            }
        }
    }
}

/// Chain data parse errors
#[derive(Copy, Clone, PartialEq, Eq, Debug, Display, Error, From)]
#[display(doc_comments)]
pub enum ParseError {
    /// The provided string does not matches any known chain; chain parameters
    /// can't be guessed. Please use `other:0x<hex_encoded_parameters>` for
    /// all non-standard networks.
    WrongNetworkName,

    /// Chain parameters can't be decoded. Please check that they are provided
    /// as a hexadecimal string starting with `0x` sign (case is irrelevant).
    #[from(strict_encoding::Error)]
    ChainParamsEncoding,

    /// Can't decode value for genesis (chain) hash, please make sure that the
    /// provided string contains
    #[from]
    GenesisHashEncoding(hex::Error),
}

impl FromStr for Chain {
    type Err = ParseError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s.to_ascii_lowercase() {
            s if s == CHAIN_PARAMS_MAINNET.name
                || s == CHAIN_PARAMS_MAINNET.bip70_name
                || s == CHAIN_PARAMS_MAINNET.bip173_prefix =>
            {
                Ok(Chain::Mainnet)
            }
            // Here we do not use `tb` prefix, since it matches multiple options
            s if s == CHAIN_PARAMS_TESTNET.name
                || s == CHAIN_PARAMS_TESTNET.bip70_name =>
            {
                Ok(Chain::Testnet3)
            }
            s if s == CHAIN_PARAMS_REGTEST.name
                || s == CHAIN_PARAMS_REGTEST.bip70_name =>
            {
                Ok(Chain::Regtest(CHAIN_PARAMS_REGTEST.genesis_hash))
            }
            s if s == CHAIN_PARAMS_SIGNET.name
                || s == CHAIN_PARAMS_SIGNET.bip70_name =>
            {
                Ok(Chain::Signet)
            }
            s if s == CHAIN_PARAMS_LIQUIDV1.name
                || s == CHAIN_PARAMS_LIQUIDV1.bip70_name =>
            {
                Ok(Chain::LiquidV1)
            }
            s => {
                let mut parts = s.split(':');
                let prefix =
                    parts.next().ok_or(ParseError::WrongNetworkName)?;
                let data = parts.next().ok_or(ParseError::WrongNetworkName)?;
                parts
                    .next()
                    .map_or(Ok(()), |_| Err(ParseError::WrongNetworkName))?;
                match prefix {
                    "regtest" => Ok(Chain::Regtest(BlockHash::from_hex(data)?)),
                    "signet" => {
                        Ok(Chain::SignetCustom(BlockHash::from_hex(data)?))
                    }
                    "other" => Ok(Chain::Other(strict_deserialize(
                        &Vec::from_hex(data)
                            .map_err(|_| ParseError::ChainParamsEncoding)?,
                    )?)),
                    _ => Err(ParseError::WrongNetworkName),
                }
            }
        }
    }
}

#[cfg(test)]
mod test {
    use super::*;
    use strict_encoding::test_helpers::test_suite;

    #[test]
    fn test_p2p_magic_number_byteorder() {
        let mainnet_bytes = &[0xF9u8, 0xBEu8, 0xB4u8, 0xD9u8][..];
        let testnet_bytes = &[0x0Bu8, 0x11u8, 0x09u8, 0x07u8][..];
        let regtest_bytes = &[0xFAu8, 0xBFu8, 0xB5u8, 0xDAu8][..];
        let signet_bytes = &[0x0Au8, 0x03u8, 0xCFu8, 0x40u8][..];
        let random_bytes = [0xA1u8, 0xA2u8, 0xA3u8, 0xA4u8];

        assert_eq!(P2P_MAGIC_MAINNET.to_le_bytes(), mainnet_bytes);
        assert_eq!(P2P_MAGIC_TESTNET.to_le_bytes(), testnet_bytes);
        assert_eq!(P2P_MAGIC_REGTEST.to_le_bytes(), regtest_bytes);
        assert_eq!(P2P_MAGIC_SIGNET.to_le_bytes(), signet_bytes);

        assert_eq!(P2P_MAGIC_MAINNET, bitcoin::Network::Bitcoin.magic());
        assert_eq!(P2P_MAGIC_TESTNET, bitcoin::Network::Testnet.magic());
        assert_eq!(P2P_MAGIC_REGTEST, bitcoin::Network::Regtest.magic());

        let other = P2pNetworkId::Other(u32::from_le_bytes(random_bytes));

        let bp_mainnet = P2pNetworkId::strict_decode(mainnet_bytes).unwrap();
        let bp_testnet = P2pNetworkId::strict_decode(testnet_bytes).unwrap();
        let bp_regtest = P2pNetworkId::strict_decode(regtest_bytes).unwrap();
        let bp_signet = P2pNetworkId::strict_decode(signet_bytes).unwrap();
        let bp_other = P2pNetworkId::strict_decode(&random_bytes[..]).unwrap();
        assert_eq!(bp_other, other);

        test_suite(&bp_mainnet, &mainnet_bytes, 4);
        test_suite(&bp_testnet, &testnet_bytes, 4);
        test_suite(&bp_regtest, &regtest_bytes, 4);
        test_suite(&bp_signet, &signet_bytes, 4);
        test_suite(&bp_other, &random_bytes, 4);
    }

    #[test]
    fn test_p2p_magic_number_fmt() {
        assert_eq!(format!("{}", P2pNetworkId::Mainnet), "mainnet");
        assert_eq!(format!("{}", P2pNetworkId::Testnet), "testnet");
        assert_eq!(format!("{}", P2pNetworkId::Regtest), "regtest");
        assert_eq!(format!("{}", P2pNetworkId::Signet), "signet");
        assert_eq!(format!("{}", P2pNetworkId::Other(0x01)), "unknown");

        assert_eq!(
            format!("{:?}", P2pNetworkId::Mainnet),
            format!("mainnet({:#x?})", P2P_MAGIC_MAINNET)
        );
        assert_eq!(
            format!("{:?}", P2pNetworkId::Testnet),
            format!("testnet({:#x?})", P2P_MAGIC_TESTNET)
        );
        assert_eq!(
            format!("{:?}", P2pNetworkId::Regtest),
            format!("regtest({:#x?})", P2P_MAGIC_REGTEST)
        );
        assert_eq!(
            format!("{:?}", P2pNetworkId::Signet),
            format!("signet({:#x?})", P2P_MAGIC_SIGNET)
        );
        assert_eq!(
            format!("{:?}", P2pNetworkId::Other(0x01u32)),
            format!("unknown({:#x?})", 0x01u32)
        );
    }

    #[test]
    fn test_p2p_magic_number_from() {
        assert_eq!(
            P2pNetworkId::from(P2P_MAGIC_MAINNET),
            P2pNetworkId::Mainnet
        );
        assert_eq!(
            P2pNetworkId::from(P2P_MAGIC_TESTNET),
            P2pNetworkId::Testnet
        );
        assert_eq!(
            P2pNetworkId::from(P2P_MAGIC_REGTEST),
            P2pNetworkId::Regtest
        );
        assert_eq!(P2pNetworkId::from(P2P_MAGIC_SIGNET), P2pNetworkId::Signet);
        assert_eq!(
            P2pNetworkId::from(0x0102030),
            P2pNetworkId::Other(0x0102030)
        );

        assert_eq!(
            P2P_MAGIC_MAINNET,
            P2pMagicNumber::from(P2pNetworkId::Mainnet)
        );
        assert_eq!(
            P2P_MAGIC_TESTNET,
            P2pMagicNumber::from(P2pNetworkId::Testnet)
        );
        assert_eq!(
            P2P_MAGIC_REGTEST,
            P2pMagicNumber::from(P2pNetworkId::Regtest)
        );
        assert_eq!(
            P2P_MAGIC_SIGNET,
            P2pMagicNumber::from(P2pNetworkId::Signet)
        );
        assert_eq!(
            0x0102030,
            P2pMagicNumber::from(P2pNetworkId::Other(0x0102030))
        );

        assert_eq!(
            P2pNetworkId::from(bitcoin::Network::Bitcoin),
            P2pNetworkId::Mainnet
        );
        assert_eq!(
            P2pNetworkId::from(bitcoin::Network::Testnet),
            P2pNetworkId::Testnet
        );
        assert_eq!(
            P2pNetworkId::from(bitcoin::Network::Regtest),
            P2pNetworkId::Regtest
        );

        assert_eq!(
            bitcoin::Network::try_from(P2pNetworkId::Mainnet).unwrap(),
            bitcoin::Network::Bitcoin
        );
        assert_eq!(
            bitcoin::Network::try_from(P2pNetworkId::Testnet).unwrap(),
            bitcoin::Network::Testnet
        );
        assert_eq!(
            bitcoin::Network::try_from(P2pNetworkId::Regtest).unwrap(),
            bitcoin::Network::Regtest
        );

        assert_eq!(
            bitcoin::Network::try_from(P2pNetworkId::Other(P2P_MAGIC_MAINNET))
                .unwrap(),
            bitcoin::Network::Bitcoin
        );
        assert_eq!(
            bitcoin::Network::try_from(P2pNetworkId::Other(P2P_MAGIC_TESTNET))
                .unwrap(),
            bitcoin::Network::Testnet
        );
        assert_eq!(
            bitcoin::Network::try_from(P2pNetworkId::Other(P2P_MAGIC_REGTEST))
                .unwrap(),
            bitcoin::Network::Regtest
        );
    }

    #[test]
    #[should_panic = "ConversionImpossibleError"]
    fn test_p2p_network_id_other() {
        bitcoin::Network::try_from(P2pNetworkId::Other(0xA1A2A3A4)).unwrap();
    }

    // TODO: Test must be rewritten
    /*
    #[test]
    fn test_chain_param_enums() {
        test_enum_u8_exhaustive!(ChainFormat;
            ChainFormat::Bitcoin => 0,
            ChainFormat::Elements => 1
        );

        test_enum_u8_exhaustive!(AssetLayer;
            AssetLayer::Layer1and2 => 1,
            AssetLayer::Layer2and3 => 2
        );

        test_enum_u8_exhaustive!(AssetSystem;
            AssetSystem::NativeBlockchain => 0,
            AssetSystem::ConfidentialAssets => 1,
            AssetSystem::RgbContract => 2
        );
    }
     */

    #[test]
    fn test_asset_params_eq() {
        let asset1 = AssetParams {
            ticker: "AAA".to_string(),
            unit_of_accounting: "Aaa".to_string(),
            indivisible_unit: "a".to_string(),
            divisibility: 0,
            asset_id: Default::default(),
            asset_system: AssetSystem::NativeBlockchain,
        };

        let asset2 = AssetParams {
            ticker: "AAA".to_string(),
            unit_of_accounting: "Aaa".to_string(),
            indivisible_unit: "a".to_string(),
            divisibility: 0,
            asset_id: Default::default(),
            asset_system: AssetSystem::ConfidentialAssets,
        };

        let asset3 = AssetParams {
            ticker: "BBB".to_string(),
            unit_of_accounting: "Bbb".to_string(),
            indivisible_unit: "b".to_string(),
            divisibility: 1,
            asset_id: Default::default(),
            asset_system: AssetSystem::NativeBlockchain,
        };

        let asset4 = AssetParams {
            ticker: "AAA".to_string(),
            unit_of_accounting: "Aaa".to_string(),
            indivisible_unit: "a".to_string(),
            divisibility: 0,
            asset_id: AssetId::hash(b"asset"),
            asset_system: AssetSystem::NativeBlockchain,
        };

        assert_eq!(asset1, asset1);
        assert_eq!(asset1, asset3);
        assert_ne!(asset1, asset2);
        assert_ne!(asset1, asset4);
        assert_ne!(asset2, asset3);
        assert_ne!(asset2, asset4);
        assert_ne!(asset3, asset4);
    }

    #[test]
    fn test_chain_params() {
        assert_eq!(Chain::Mainnet.chain_params(), *CHAIN_PARAMS_MAINNET);
        assert_eq!(Chain::Testnet3.chain_params(), *CHAIN_PARAMS_TESTNET);
        assert_eq!(
            Chain::Regtest(
                BlockHash::from_slice(&GENESIS_HASH_REGTEST).unwrap()
            )
            .chain_params(),
            *CHAIN_PARAMS_REGTEST
        );
        assert_eq!(Chain::Signet.chain_params(), *CHAIN_PARAMS_SIGNET);
        assert_eq!(
            Chain::SignetCustom(
                BlockHash::from_slice(&GENESIS_HASH_SIGNET).unwrap()
            )
            .chain_params(),
            *CHAIN_PARAMS_SIGNET
        );
        assert_eq!(Chain::LiquidV1.chain_params(), *CHAIN_PARAMS_LIQUIDV1);

        assert_eq!(Chain::Mainnet, Chain::Mainnet);
        assert_eq!(
            Chain::Signet,
            Chain::SignetCustom(
                BlockHash::from_slice(&GENESIS_HASH_SIGNET).unwrap()
            )
        );
        assert_ne!(Chain::Mainnet, Chain::LiquidV1);
        assert_ne!(Chain::Mainnet, Chain::Testnet3);
        assert_ne!(Chain::Mainnet, Chain::Signet);
        assert_ne!(Chain::Signet, Chain::Testnet3);
        assert_eq!(
            Chain::Signet,
            Chain::Regtest(
                BlockHash::from_slice(&GENESIS_HASH_SIGNET).unwrap()
            )
        );
        assert_ne!(Chain::Signet, Chain::SignetCustom(BlockHash::hash(b"")));
    }

    #[test]
    fn test_chain_encode() {
        const DATA_CHAINPARAMS_MAINNET: [u8; 142] = [
            0x6f, 0xe2, 0x8c, 0xa, 0xb6, 0xf1, 0xb3, 0x72, 0xc1, 0xa6, 0xa2,
            0x46, 0xae, 0x63, 0xf7, 0x4f, 0x93, 0x1e, 0x83, 0x65, 0xe1, 0x5a,
            0x8, 0x9c, 0x68, 0xd6, 0x19, 0x0, 0x0, 0x0, 0x0, 0x0, 0x7, 0x0,
            0x62, 0x69, 0x74, 0x63, 0x6f, 0x69, 0x6e, 0xf9, 0xbe, 0xb4, 0xd9,
            0x4, 0x0, 0x6d, 0x61, 0x69, 0x6e, 0x2, 0x0, 0x62, 0x63, 0x8d, 0x20,
            0x8c, 0x20, 0xb4, 0xb2, 0x7, 0x0, 0x10, 0xeb, 0x9, 0x0, 0x0, 0x22,
            0x2, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x3, 0x0, 0x42, 0x54, 0x43, 0x7,
            0x0, 0x42, 0x69, 0x74, 0x63, 0x6f, 0x69, 0x6e, 0x7, 0x0, 0x73,
            0x61, 0x74, 0x6f, 0x73, 0x68, 0x69, 0x0, 0xe1, 0xf5, 0x5, 0x0, 0x0,
            0x0, 0x0, 0x6f, 0xe2, 0x8c, 0xa, 0xb6, 0xf1, 0xb3, 0x72, 0xc1,
            0xa6, 0xa2, 0x46, 0xae, 0x63, 0xf7, 0x4f, 0x93, 0x1e, 0x83, 0x65,
            0xe1, 0x5a, 0x8, 0x9c, 0x68, 0xd6, 0x19, 0x0, 0x0, 0x0, 0x0, 0x0,
            0x0, 0x0, 0x1,
        ];
        const DATA_CHAINPARAMS_TESTNET: [u8; 153] = [
            0x43, 0x49, 0x7f, 0xd7, 0xf8, 0x26, 0x95, 0x71, 0x8, 0xf4, 0xa3,
            0xf, 0xd9, 0xce, 0xc3, 0xae, 0xba, 0x79, 0x97, 0x20, 0x84, 0xe9,
            0xe, 0xad, 0x1, 0xea, 0x33, 0x9, 0x0, 0x0, 0x0, 0x0, 0x7, 0x0,
            0x74, 0x65, 0x73, 0x74, 0x6e, 0x65, 0x74, 0xb, 0x11, 0x9, 0x7, 0x4,
            0x0, 0x74, 0x65, 0x73, 0x74, 0x2, 0x0, 0x74, 0x62, 0x9d, 0x47,
            0x9c, 0x47, 0x1, 0x0, 0x0, 0x0, 0xec, 0x1, 0x1c, 0x0, 0x0, 0x22,
            0x2, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x4, 0x0, 0x74, 0x42, 0x54,
            0x43, 0xc, 0x0, 0x54, 0x65, 0x73, 0x74, 0x20, 0x42, 0x69, 0x74,
            0x63, 0x6f, 0x69, 0x6e, 0xc, 0x0, 0x54, 0x65, 0x73, 0x74, 0x20,
            0x73, 0x61, 0x74, 0x6f, 0x73, 0x68, 0x69, 0x0, 0xe1, 0xf5, 0x5,
            0x0, 0x0, 0x0, 0x0, 0x43, 0x49, 0x7f, 0xd7, 0xf8, 0x26, 0x95, 0x71,
            0x8, 0xf4, 0xa3, 0xf, 0xd9, 0xce, 0xc3, 0xae, 0xba, 0x79, 0x97,
            0x20, 0x84, 0xe9, 0xe, 0xad, 0x1, 0xea, 0x33, 0x9, 0x0, 0x0, 0x0,
            0x0, 0x0, 0x1, 0x1,
        ];
        const DATA_CHAINPARAMS_SIGNET: [u8; 158] = [
            0xf6, 0x1e, 0xee, 0x3b, 0x63, 0xa3, 0x80, 0xa4, 0x77, 0xa0, 0x63,
            0xaf, 0x32, 0xb2, 0xbb, 0xc9, 0x7c, 0x9f, 0xf9, 0xf0, 0x1f, 0x2c,
            0x42, 0x25, 0xe9, 0x73, 0x98, 0x81, 0x8, 0x0, 0x0, 0x0, 0x6, 0x0,
            0x73, 0x69, 0x67, 0x6e, 0x65, 0x74, 0xa, 0x3, 0xcf, 0x40, 0x6, 0x0,
            0x73, 0x69, 0x67, 0x6e, 0x65, 0x74, 0x2, 0x0, 0x74, 0x62, 0xbd,
            0x95, 0xbc, 0x95, 0x1, 0x0, 0x0, 0x0, 0x1, 0x0, 0x0, 0x0, 0x0,
            0x22, 0x2, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x4, 0x0, 0x73, 0x42,
            0x54, 0x43, 0xe, 0x0, 0x53, 0x69, 0x67, 0x6e, 0x65, 0x74, 0x20,
            0x42, 0x69, 0x74, 0x63, 0x6f, 0x69, 0x6e, 0xe, 0x0, 0x53, 0x69,
            0x67, 0x6e, 0x65, 0x74, 0x20, 0x73, 0x61, 0x74, 0x6f, 0x73, 0x68,
            0x69, 0x0, 0xe1, 0xf5, 0x5, 0x0, 0x0, 0x0, 0x0, 0xf6, 0x1e, 0xee,
            0x3b, 0x63, 0xa3, 0x80, 0xa4, 0x77, 0xa0, 0x63, 0xaf, 0x32, 0xb2,
            0xbb, 0xc9, 0x7c, 0x9f, 0xf9, 0xf0, 0x1f, 0x2c, 0x42, 0x25, 0xe9,
            0x73, 0x98, 0x81, 0x8, 0x0, 0x0, 0x0, 0x0, 0x1, 0x0,
        ];
        const DATA_CHAINPARAMS_LIQUID: [u8; 162] = [
            0x14, 0x66, 0x27, 0x58, 0x36, 0x22, 0xd, 0xb2, 0x94, 0x4c, 0xa0,
            0x59, 0xa3, 0xa1, 0xe, 0xf6, 0xfd, 0x2e, 0xa6, 0x84, 0xb0, 0x68,
            0x8d, 0x2c, 0x37, 0x92, 0x96, 0x88, 0x8a, 0x20, 0x60, 0x3, 0x8,
            0x0, 0x6c, 0x69, 0x71, 0x75, 0x69, 0x64, 0x76, 0x31, 0xf9, 0xbe,
            0xb4, 0xd9, 0x8, 0x0, 0x6c, 0x69, 0x71, 0x75, 0x69, 0x64, 0x76,
            0x31, 0x2, 0x0, 0x65, 0x78, 0x82, 0x1b, 0x81, 0x1b, 0x1, 0x0, 0x0,
            0x0, 0x40, 0x42, 0xf, 0x0, 0x1, 0x22, 0x2, 0x0, 0x0, 0x0, 0x0, 0x0,
            0x0, 0x4, 0x0, 0x4c, 0x42, 0x54, 0x43, 0xe, 0x0, 0x4c, 0x69, 0x71,
            0x75, 0x69, 0x64, 0x20, 0x42, 0x69, 0x74, 0x63, 0x6f, 0x69, 0x6e,
            0xe, 0x0, 0x4c, 0x69, 0x71, 0x75, 0x69, 0x64, 0x20, 0x73, 0x61,
            0x74, 0x6f, 0x73, 0x68, 0x69, 0x0, 0xe1, 0xf5, 0x5, 0x0, 0x0, 0x0,
            0x0, 0x14, 0x66, 0x27, 0x58, 0x36, 0x22, 0xd, 0xb2, 0x94, 0x4c,
            0xa0, 0x59, 0xa3, 0xa1, 0xe, 0xf6, 0xfd, 0x2e, 0xa6, 0x84, 0xb0,
            0x68, 0x8d, 0x2c, 0x37, 0x92, 0x96, 0x88, 0x8a, 0x20, 0x60, 0x3,
            0x0, 0x0, 0x0,
        ];

        test_encode!(
            (DATA_CHAINPARAMS_MAINNET, Chain),
            (DATA_CHAINPARAMS_TESTNET, Chain),
            (DATA_CHAINPARAMS_SIGNET, Chain),
            (DATA_CHAINPARAMS_LIQUID, Chain)
        );
    }

    #[test]
    fn test_chain_genesis_hashes() {
        assert_eq!(
            GENESIS_HASH_MAINNET,
            &[
                0x6f, 0xe2, 0x8c, 0x0a, 0xb6, 0xf1, 0xb3, 0x72, 0xc1, 0xa6,
                0xa2, 0x46, 0xae, 0x63, 0xf7, 0x4f, 0x93, 0x1e, 0x83, 0x65,
                0xe1, 0x5a, 0x08, 0x9c, 0x68, 0xd6, 0x19, 0x00, 0x00, 0x00,
                0x00, 0x00,
            ]
        );

        assert_eq!(
            GENESIS_HASH_TESTNET,
            &[
                0x43, 0x49, 0x7f, 0xd7, 0xf8, 0x26, 0x95, 0x71, 0x08, 0xf4,
                0xa3, 0x0f, 0xd9, 0xce, 0xc3, 0xae, 0xba, 0x79, 0x97, 0x20,
                0x84, 0xe9, 0x0e, 0xad, 0x01, 0xea, 0x33, 0x09, 0x00, 0x00,
                0x00, 0x00,
            ]
        );

        assert_eq!(
            GENESIS_HASH_REGTEST,
            &[
                0x06, 0x22, 0x6e, 0x46, 0x11, 0x1a, 0x0b, 0x59, 0xca, 0xaf,
                0x12, 0x60, 0x43, 0xeb, 0x5b, 0xbf, 0x28, 0xc3, 0x4f, 0x3a,
                0x5e, 0x33, 0x2a, 0x1f, 0xc7, 0xb2, 0xb7, 0x3c, 0xf1, 0x88,
                0x91, 0x0f,
            ]
        );

        assert_eq!(
            GENESIS_HASH_SIGNET,
            &[
                0xf6, 0x1e, 0xee, 0x3b, 0x63, 0xa3, 0x80, 0xa4, 0x77, 0xa0,
                0x63, 0xaf, 0x32, 0xb2, 0xbb, 0xc9, 0x7c, 0x9f, 0xf9, 0xf0,
                0x1f, 0x2c, 0x42, 0x25, 0xe9, 0x73, 0x98, 0x81, 0x08, 0x00,
                0x00, 0x00,
            ]
        );

        assert_eq!(
            GENESIS_HASH_LIQUIDV1,
            &[
                0x14, 0x66, 0x27, 0x58, 0x36, 0x22, 0x0d, 0xb2, 0x94, 0x4c,
                0xa0, 0x59, 0xa3, 0xa1, 0x0e, 0xf6, 0xfd, 0x2e, 0xa6, 0x84,
                0xb0, 0x68, 0x8d, 0x2c, 0x37, 0x92, 0x96, 0x88, 0x8a, 0x20,
                0x60, 0x03,
            ]
        );

        let random_hash = BlockHash::hash(b"random string");

        assert_eq!(&Chain::Mainnet.as_genesis_hash()[..], GENESIS_HASH_MAINNET);
        assert_eq!(
            &Chain::Testnet3.as_genesis_hash()[..],
            GENESIS_HASH_TESTNET
        );
        assert_eq!(
            &Chain::Regtest(
                BlockHash::from_slice(GENESIS_HASH_REGTEST).unwrap()
            )
            .as_genesis_hash()[..],
            GENESIS_HASH_REGTEST
        );
        assert_eq!(
            &Chain::Regtest(random_hash).as_genesis_hash()[..],
            &random_hash[..]
        );
        assert_eq!(&Chain::Signet.as_genesis_hash()[..], GENESIS_HASH_SIGNET);
        assert_eq!(
            &Chain::SignetCustom(
                BlockHash::from_slice(GENESIS_HASH_SIGNET).unwrap()
            )
            .as_genesis_hash()[..],
            GENESIS_HASH_SIGNET
        );
        assert_eq!(
            &Chain::SignetCustom(random_hash).as_genesis_hash()[..],
            &random_hash[..]
        );
        assert_eq!(
            &Chain::LiquidV1.as_genesis_hash()[..],
            GENESIS_HASH_LIQUIDV1
        );
        assert_eq!(
            &Chain::Other(Chain::Mainnet.chain_params()).as_genesis_hash()[..],
            GENESIS_HASH_MAINNET
        );
        let mut chain_params = Chain::Mainnet.chain_params();
        chain_params.genesis_hash = random_hash;
        assert_eq!(
            &Chain::Other(chain_params).as_genesis_hash()[..],
            &random_hash[..]
        );

        assert_eq!(
            Chain::from_genesis_hash(
                &BlockHash::from_slice(GENESIS_HASH_MAINNET).unwrap()
            )
            .unwrap(),
            Chain::Mainnet
        );
        assert_eq!(
            Chain::from_genesis_hash(
                &BlockHash::from_slice(GENESIS_HASH_TESTNET).unwrap()
            )
            .unwrap(),
            Chain::Testnet3
        );
        assert_eq!(
            Chain::from_genesis_hash(
                &BlockHash::from_slice(GENESIS_HASH_SIGNET).unwrap()
            )
            .unwrap(),
            Chain::Signet
        );
        assert_eq!(
            Chain::from_genesis_hash(
                &BlockHash::from_slice(GENESIS_HASH_LIQUIDV1).unwrap()
            )
            .unwrap(),
            Chain::LiquidV1
        );
        let regtest = Chain::from_genesis_hash(
            &BlockHash::from_slice(GENESIS_HASH_REGTEST).unwrap(),
        )
        .unwrap();
        assert_eq!(regtest, Chain::Regtest(*regtest.as_genesis_hash()));
        assert_ne!(regtest, Chain::Regtest(random_hash));
        assert_eq!(Chain::from_genesis_hash(&random_hash), None);
    }

    #[test]
    fn test_chains() {
        let random_hash = BlockHash::hash(b"rascafvsdg");

        assert_eq!(Chain::Mainnet, Chain::from(CHAIN_PARAMS_MAINNET.clone()));
        assert_eq!(Chain::Testnet3, Chain::from(CHAIN_PARAMS_TESTNET.clone()));
        assert_eq!(
            Chain::Regtest(CHAIN_PARAMS_REGTEST.genesis_hash),
            Chain::from(CHAIN_PARAMS_REGTEST.clone())
        );
        assert_ne!(
            Chain::Regtest(random_hash),
            Chain::from(CHAIN_PARAMS_REGTEST.clone())
        );
        assert_eq!(Chain::Signet, Chain::from(CHAIN_PARAMS_SIGNET.clone()));
        assert_eq!(
            Chain::SignetCustom(CHAIN_PARAMS_SIGNET.genesis_hash),
            Chain::from(CHAIN_PARAMS_SIGNET.clone())
        );
        assert_ne!(
            Chain::SignetCustom(random_hash),
            Chain::from(CHAIN_PARAMS_SIGNET.clone())
        );
        assert_eq!(Chain::LiquidV1, Chain::from(CHAIN_PARAMS_LIQUIDV1.clone()));

        assert_eq!(Chain::Mainnet, Chain::from(bitcoin::Network::Bitcoin));
        assert_eq!(Chain::Testnet3, Chain::from(bitcoin::Network::Testnet));
        assert_eq!(
            Chain::Regtest(CHAIN_PARAMS_REGTEST.genesis_hash),
            Chain::from(bitcoin::Network::Regtest)
        );

        assert_eq!(
            bitcoin::Network::try_from(Chain::Mainnet).unwrap(),
            bitcoin::Network::Bitcoin
        );
        assert_eq!(
            bitcoin::Network::try_from(Chain::Testnet3).unwrap(),
            bitcoin::Network::Testnet
        );
        assert_eq!(
            bitcoin::Network::try_from(Chain::Regtest(
                CHAIN_PARAMS_REGTEST.genesis_hash
            ))
            .unwrap(),
            bitcoin::Network::Regtest
        );
        assert_eq!(
            bitcoin::Network::try_from(Chain::Regtest(
                CHAIN_PARAMS_SIGNET.genesis_hash
            ))
            .unwrap_err(),
            ConversionImpossibleError
        );
        assert_eq!(
            bitcoin::Network::try_from(Chain::SignetCustom(
                CHAIN_PARAMS_REGTEST.genesis_hash
            ))
            .unwrap_err(),
            ConversionImpossibleError
        );
        assert_eq!(
            bitcoin::Network::try_from(Chain::Regtest(random_hash))
                .unwrap_err(),
            ConversionImpossibleError
        );
        assert_eq!(
            bitcoin::Network::try_from(Chain::SignetCustom(random_hash))
                .unwrap_err(),
            ConversionImpossibleError
        );
    }

    #[test]
    fn test_chains_display() {
        let custom_hash = BlockHash::hash(b"00350429507202701943");
        assert_eq!(format!("{}", Chain::Mainnet), "bitcoin");
        assert_eq!(format!("{}", Chain::Testnet3), "testnet");
        assert_eq!(format!("{}", Chain::Signet), "signet");
        assert_eq!(format!("{}", Chain::LiquidV1), "liquidv1");
        assert_eq!(
            format!("{}", Chain::Regtest(CHAIN_PARAMS_REGTEST.genesis_hash)),
            "regtest"
        );
        assert_eq!(
            format!(
                "{}",
                Chain::SignetCustom(CHAIN_PARAMS_SIGNET.genesis_hash)
            ),
            "signet"
        );
        assert_eq!(
            format!("{}", Chain::Regtest(custom_hash)),
            format!("regtest:{}", custom_hash)
        );
        assert_eq!(
            format!("{}", Chain::SignetCustom(custom_hash)),
            format!("signet:{}", custom_hash)
        );

        assert_eq!(
            format!("{}", Chain::Other(CHAIN_PARAMS_MAINNET.clone())),
            "bitcoin"
        );
        assert_eq!(
            format!("{}", Chain::Other(CHAIN_PARAMS_TESTNET.clone())),
            "testnet"
        );
        assert_eq!(
            format!("{}", Chain::Other(CHAIN_PARAMS_REGTEST.clone())),
            "regtest"
        );
        assert_eq!(
            format!("{}", Chain::Other(CHAIN_PARAMS_SIGNET.clone())),
            "signet"
        );
        assert_eq!(
            format!("{}", Chain::Other(CHAIN_PARAMS_LIQUIDV1.clone())),
            "liquidv1"
        );

        let mut custom_params = CHAIN_PARAMS_MAINNET.clone();
        custom_params.genesis_hash = custom_hash;
        assert_eq!(format!("{}", Chain::Other(custom_params.clone())), "other:0e1b741ef47d9c526fd4a3a67b421ed924feb5a31deb485eb9a67e19495269a20700626974636f696ef9beb4d904006d61696e020062638d208c20b4b2070010eb090000220200000000000003004254430700426974636f696e07007361746f73686900e1f505000000006fe28c0ab6f1b372c1a6a246ae63f74f931e8365e15a089c68d6190000000000000001");

        assert_eq!(Chain::from_str("bitcoin").unwrap(), Chain::Mainnet);
        assert_eq!(Chain::from_str("testnet").unwrap(), Chain::Testnet3);
        assert_eq!(
            Chain::from_str("regtest").unwrap(),
            Chain::Regtest(CHAIN_PARAMS_REGTEST.genesis_hash)
        );
        assert_eq!(
            Chain::from_str(
                "regtest:a2695249197ea6b95e48eb1da3b5fe24d91e427ba6a3d46f529c7df41e741b0e"
            )
            .unwrap(),
            Chain::Regtest(custom_hash)
        );
        assert_eq!(Chain::from_str("signet").unwrap(), Chain::Signet);
        assert_eq!(
            Chain::from_str(
                "signet:a2695249197ea6b95e48eb1da3b5fe24d91e427ba6a3d46f529c7df41e741b0e"
            )
            .unwrap(),
            Chain::SignetCustom(custom_hash)
        );
        assert_eq!(Chain::from_str("liquidv1").unwrap(), Chain::LiquidV1);

        assert_eq!(Chain::from_str("Bitcoin").unwrap(), Chain::Mainnet);
        assert_eq!(Chain::from_str("bItcOin").unwrap(), Chain::Mainnet);

        assert_eq!(Chain::from_str("bc").unwrap(), Chain::Mainnet);
        assert_eq!(Chain::from_str("main").unwrap(), Chain::Mainnet);

        assert_eq!(
            Chain::from_str("aljsic").unwrap_err(),
            ParseError::WrongNetworkName
        );
        assert_eq!(
            Chain::from_str("other:0e1b741ef47d9c526fd4a3a67b421ed924feb5a31deb485eb9a67e19495269a20700626974636f696ef9beb4d904006d61696e020062638d208c20b4b2070010eb090000220200000000000003004254430700426974636f696e07007361746f73686900e1f505000000006fe28c0ab6f1b372c1a6a246ae63f74f931e8365e15a089c68d6190000000000000001").unwrap(),
            Chain::Other(custom_params)
        );
    }
}