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
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
#![allow(unused_imports)]
use log::{info, error, debug};
use std::error::Error;
use super::crypto::Hash;
use super::header::PrimaryKey;
use serde::{Serialize, de::DeserializeOwned, Deserialize};

extern crate rmp_serde as rmps;

use rmp_serde::encode::Error as RmpEncodeError;
use rmp_serde::decode::Error as RmpDecodeError;
use serde_json::Error as JsonError;
use tokio::task::JoinError;
use std::time::SystemTimeError;
use std::sync::mpsc as smpsc;
use tokio::sync::mpsc as mpsc;
use tokio::sync::broadcast as broadcast;
use trust_dns_proto::error::ProtoError as DnsProtoError;
use trust_dns_client::error::ClientError as DnsClientError;

#[derive(Debug)]
pub enum CryptoError {
    NoIvPresent,    
}

impl From<CryptoError>
for std::io::Error {
    fn from(error: CryptoError) -> Self {
        match error {
            CryptoError::NoIvPresent => std::io::Error::new(std::io::ErrorKind::Other, "The metadata does not have IV component present")
        }
    }
}

impl std::fmt::Display
for CryptoError {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        match self {
            CryptoError::NoIvPresent => {
                write!(f, "The event has no initialization vector")
            },
        }
    }
}

impl std::error::Error
for CryptoError
{
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        None
    }
}

#[derive(Debug)]
pub enum TransformError {
    EncryptionError(openssl::error::ErrorStack),
    IO(std::io::Error),
    CryptoError(CryptoError),
    MissingReadKey(Hash),
    UnspecifiedReadability,
}

impl From<openssl::error::ErrorStack>
for TransformError
{
    fn from(err: openssl::error::ErrorStack) -> TransformError {
        TransformError::EncryptionError(err)
    }
}

impl From<std::io::Error>
for TransformError
{
    fn from(err: std::io::Error) -> TransformError {
        TransformError::IO(err)
    }
}

impl From<CryptoError>
for TransformError
{
    fn from(err: CryptoError) -> TransformError {
        TransformError::CryptoError(err)
    }
}

impl std::fmt::Display
for TransformError {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        match self {
            TransformError::EncryptionError(err) => {
                write!(f, "Encryption error while transforming event data - {}", err)
            },
            TransformError::IO(err) => {
                write!(f, "IO error while transforming event data - {}", err)
            },
            TransformError::CryptoError(err) => {
                write!(f, "Cryptography error while transforming event data - {}", err)
            },
            TransformError::MissingReadKey(key) => {
                write!(f, "Missing the read key ({}) needed to encrypt/decrypt this data object", key.to_string())
            },
            TransformError::UnspecifiedReadability => {
                write!(f, "The readability for this data object has not been specified")
            },
            
        }
    }
}

impl std::error::Error
for TransformError
{
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        None
    }
}

#[derive(Debug)]
pub enum CompactError {
    SinkError(SinkError),
    IO(tokio::io::Error),
    LoadError(LoadError),
    SerializationError(SerializationError),
}

impl From<tokio::io::Error>
for CompactError {
    fn from(err: tokio::io::Error) -> CompactError {
        CompactError::IO(err)
    }
}

impl From<SinkError>
for CompactError {
    fn from(err: SinkError) -> CompactError {
        CompactError::SinkError(err)
    }
}

impl From<LoadError>
for CompactError {
    fn from(err: LoadError) -> CompactError {
        CompactError::LoadError(err)
    }
}

impl From<SerializationError>
for CompactError {
    fn from(err: SerializationError) -> CompactError {
        CompactError::SerializationError(err)
    }
}

impl std::fmt::Display
for CompactError {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        match self {
            CompactError::IO(err) => {
                write!(f, "Failed to compact the chain due to an IO error - {}", err)
            },
            CompactError::SerializationError(err) => {
                write!(f, "Failed to compact the chain due to a serialization error - {}", err)
            },
            CompactError::SinkError(err) => {
                write!(f, "Failed to compact the chain due to an error in the sink - {}", err)
            },
            CompactError::LoadError(err) => {
                write!(f, "Failed to compact the chain due to an error loaded on event - {}", err)
            },
        }
    }
}

impl std::error::Error
for CompactError
{
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        None
    }
}

#[derive(Debug)]
pub enum SinkError {
    MissingPublicKey(Hash),
    Trust(TrustError),
    InvalidSignature {
        hash: Hash,
        err: Option<pqcrypto_traits::Error>,
    }
}

impl From<TrustError>
for SinkError
{
    fn from(err: TrustError) -> SinkError {
        SinkError::Trust(err)
    }   
}

impl std::fmt::Display
for SinkError {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        match self {
            SinkError::MissingPublicKey(hash) => {
                write!(f, "The public key ({}) for signature could not be found in the chain-of-trust", hash.to_string())
            },
            SinkError::Trust(err) => {
                write!(f, "Failed to accept event due to a trust error - {}", err)
            },
            SinkError::InvalidSignature { hash, err } => {
                match err {
                    Some(err) => write!(f, "Failed verification of hash while using public key ({}) - {}", hash.to_string(), err),
                    None => write!(f, "Failed verification of hash while using public key ({})", hash.to_string())
                }
            },
        }
    }
}

impl std::error::Error
for SinkError
{
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        None
    }
}

#[derive(Debug)]
pub enum SerializationError
{
    NoPrimarykey,
    NoData,
    InvalidSerializationFormat,
    IO(tokio::io::Error),
    EncodeError(RmpEncodeError),
    DecodeError(RmpDecodeError),
    JsonError(JsonError),
    BincodeError(bincode::Error),
    #[allow(dead_code)]
    CollectionDetached,
}

impl From<RmpEncodeError>
for SerializationError {
    fn from(err: RmpEncodeError) -> SerializationError {
        SerializationError::EncodeError(err)
    }
}

impl From<tokio::io::Error>
for SerializationError
{
    fn from(err: tokio::io::Error) -> SerializationError {
        SerializationError::IO(err)
    }   
}

impl From<bincode::Error>
for SerializationError
{
    fn from(err: bincode::Error) -> SerializationError {
        SerializationError::BincodeError(err)
    }   
}

impl From<RmpDecodeError>
for SerializationError {
    fn from(err: RmpDecodeError) -> SerializationError {
        SerializationError::DecodeError(err)
    }
}

impl From<JsonError>
for SerializationError {
    fn from(err: JsonError) -> SerializationError {
        SerializationError::JsonError(err)
    }
}

impl std::fmt::Display
for SerializationError {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        match self {
            SerializationError::NoPrimarykey => {
                write!(f, "Data object does not have a primary key")
            },
            SerializationError::NoData => {
                write!(f, "Data object has no actual data")
            },
            SerializationError::InvalidSerializationFormat => {
                write!(f, "Data is stored in an unknown serialization format")
            },
            SerializationError::IO(err) => {
                write!(f, "IO error during serialization - {}", err)
            },
            SerializationError::EncodeError(err) => {
                write!(f, "MessagePack encoding error - {}", err)
            },
            SerializationError::DecodeError(err) => {
                write!(f, "MessagePack decoding error - {}", err)
            },
            SerializationError::JsonError(err) => {
                write!(f, "JSON serialization error - {}", err)
            },
            SerializationError::BincodeError(err) => {
                write!(f, "Bincode serialization error - {}", err)
            },
            SerializationError::CollectionDetached => {
                write!(f, "Collection is detached from a parent")
            },
        }
    }
}

impl std::error::Error
for SerializationError
{
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        None
    }
}

#[derive(Debug)]
pub enum LoadError {
    NotFound(PrimaryKey),
    NoPrimaryKey,
    VersionMismatch,
    NotFoundByHash(Hash),
    ObjectStillLocked(PrimaryKey),
    AlreadyDeleted(PrimaryKey),
    Tombstoned(PrimaryKey),
    SerializationError(SerializationError),
    TransformationError(TransformError),
    IO(tokio::io::Error),
    #[allow(dead_code)]
    CollectionDetached,
}

impl From<tokio::io::Error>
for LoadError
{
    fn from(err: tokio::io::Error) -> LoadError {
        LoadError::IO(err)
    }   
}

impl From<SerializationError>
for LoadError
{
    fn from(err: SerializationError) -> LoadError {
        LoadError::SerializationError(err)
    }   
}

impl From<TransformError>
for LoadError
{
    fn from(err: TransformError) -> LoadError {
        LoadError::TransformationError(err)
    }   
}

impl From<RmpEncodeError>
for LoadError {
    fn from(err: RmpEncodeError) -> LoadError {
        LoadError::SerializationError(SerializationError::EncodeError(err))
    }
}

impl From<RmpDecodeError>
for LoadError {
    fn from(err: RmpDecodeError) -> LoadError {
        LoadError::SerializationError(SerializationError::DecodeError(err))
    }
}

impl std::fmt::Display
for LoadError {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        match self {
            LoadError::NotFound(key) => {
                write!(f, "Data object with key ({}) could not be found", key.as_hex_string())
            },
            LoadError::NotFoundByHash(hash) => {
                write!(f, "Data object with hash ({}) could not be found", hash.to_string())
            },
            LoadError::VersionMismatch => {
                write!(f, "Entry has an invalid version for this log file")
            }
            LoadError::NoPrimaryKey => {
                write!(f, "Entry has no primary could and hence could not be loaded")
            },
            LoadError::ObjectStillLocked(key) => {
                write!(f, "Data object with key ({}) is still being edited in the current scope", key.as_hex_string())
            },
            LoadError::AlreadyDeleted(key) => {
                write!(f, "Data object with key ({}) has already been deleted", key.as_hex_string())
            },
            LoadError::Tombstoned(key) => {
                write!(f, "Data object with key ({}) has already been tombstoned", key.as_hex_string())
            },
            LoadError::SerializationError(err) => {
                write!(f, "Serialization error while attempting to load data object - {}", err)
            },
            LoadError::TransformationError(err) => {
                write!(f, "Transformation error while attempting to load data object - {}", err)
            },
            LoadError::IO(err) => {
                write!(f, "IO error while attempting to load data object - {}", err)
            },
            LoadError::CollectionDetached => {
                write!(f, "Collection is detached from its parent, it must be attached before it can be used")
            },
        }
    }
}

impl std::error::Error
for LoadError
{
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        None
    }
}

#[derive(Debug, Default)]
pub struct ProcessError
{
    pub sink_errors: Vec<SinkError>,
    pub validation_errors: Vec<ValidationError>,
}

impl ProcessError {
    pub fn has_errors(&self) -> bool {
        if self.sink_errors.is_empty() == false { return true; }
        if self.validation_errors.is_empty() == false { return true; }
        false
    }

    pub fn as_result(self) -> Result<(), ProcessError> {
        match self.has_errors() {
            true => Err(self),
            false => Ok(())
        }
    }
}

impl std::fmt::Display
for ProcessError {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        let mut err = "Processing error - ".to_string();
        for sink in self.sink_errors.iter() {
            err = err + &sink.to_string()[..] + " - ";
        }
        for validation in self.validation_errors.iter() {
            err = err + &validation.to_string()[..] + " - ";
        }
        write!(f, "{}", err)
    }
}

impl std::error::Error
for ProcessError
{
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        None
    }
}

#[derive(Debug)]
pub enum ChainCreationError {
    ProcessError(ProcessError),
    IO(tokio::io::Error),
    SerializationError(SerializationError),
    NoRootFoundInConfig,
    NoRootFoundForUrl(String),
    UnsupportedProtocol,
    UrlInvalid(url::ParseError),
    NotSupported,
    #[allow(dead_code)]
    NotThisRoot,
    #[allow(dead_code)]
    NotImplemented,
    TimeError(TimeError),
    NoValidDomain(String),
    CommsError(CommsError),
    DnsProtoError(DnsProtoError),
    DnsClientError(DnsClientError),
    ServerRejected(String),
    InternalError(String),
}

impl From<url::ParseError>
for ChainCreationError
{
    fn from(err: url::ParseError) -> ChainCreationError {
        ChainCreationError::UrlInvalid(err)
    }   
}

impl From<ProcessError>
for ChainCreationError
{
    fn from(err: ProcessError) -> ChainCreationError {
        ChainCreationError::ProcessError(err)
    }   
}

impl From<SerializationError>
for ChainCreationError
{
    fn from(err: SerializationError) -> ChainCreationError {
        ChainCreationError::SerializationError(err)
    }   
}

impl From<tokio::io::Error>
for ChainCreationError
{
    fn from(err: tokio::io::Error) -> ChainCreationError {
        ChainCreationError::IO(err)
    }   
}

impl From<CommsError>
for ChainCreationError
{
    fn from(err: CommsError) -> ChainCreationError {
        ChainCreationError::CommsError(err)
    }   
}

impl From<DnsProtoError>
for ChainCreationError
{
    fn from(err: DnsProtoError) -> ChainCreationError {
        ChainCreationError::DnsProtoError(err)
    }
}

impl From<DnsClientError>
for ChainCreationError
{
    fn from(err: DnsClientError) -> ChainCreationError {
        ChainCreationError::DnsClientError(err)
    }
}

impl From<TimeError>
for ChainCreationError
{
    fn from(err: TimeError) -> ChainCreationError {
        ChainCreationError::TimeError(err)
    }
}

impl std::fmt::Display
for ChainCreationError {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        match self {
            ChainCreationError::ProcessError(err) => {
                write!(f, "Failed to create chain-of-trust due to a processingerror - {}", err)
            },
            ChainCreationError::SerializationError(err) => {
                write!(f, "Failed to create chain-of-trust due to a serialization error - {}", err)
            },
            ChainCreationError::UrlInvalid(err) => {
                write!(f, "Failed to create chain-of-trust due to a parsing the chain URL - {}", err)
            },
            ChainCreationError::IO(err) => {
                write!(f, "Failed to create chain-of-trust due to an IO error - {}", err)
            },
            ChainCreationError::NotImplemented => {
                write!(f, "Failed to create chain-of-trust as the method is not implemented")
            },
            ChainCreationError::NotSupported => {
                write!(f, "Failed to create chain-of-trust as the operation is not supported. Possible causes are calling 'open_by_key' on a Registry which only supports the 'open_by_url'.")
            },
            ChainCreationError::NoRootFoundInConfig => {
                write!(f, "Failed to create chain-of-trust as the root node is not found in the configuration settings")
            },
            ChainCreationError::NoRootFoundForUrl(url) => {
                write!(f, "Failed to create chain-of-trust as the root node is not found in the URL [{}]", url)
            },
            ChainCreationError::UnsupportedProtocol => {
                write!(f, "Failed to create chain-of-trust as the protocol is not supported (only TCP is supported)")
            },
            ChainCreationError::NotThisRoot => {
                write!(f, "Failed to create chain-of-trust as this is the wrong root node")
            },
            ChainCreationError::CommsError(err) => {
                write!(f, "Failed to create chain-of-trust due to a communication error - {}", err)
            },
            ChainCreationError::NoValidDomain(err) => {
                write!(f, "Failed to create chain-of-trust as the address does not have a valid domain name [{}]", err)
            },
            ChainCreationError::DnsProtoError(err) => {
                write!(f, "Failed to create chain-of-trust due to a DNS error - {}", err)
            },
            ChainCreationError::DnsClientError(err) => {
                write!(f, "Failed to create chain-of-trust due to a DNS error - {}", err)
            },
            ChainCreationError::ServerRejected(reason) => {
                write!(f, "Failed to create chain-of-trust as the server refused to create the chain ({})", reason)
            },
            ChainCreationError::TimeError(err) => {
                write!(f, "Failed to create chain-of-trust due error with time keeping - {}", err)
            },
            ChainCreationError::InternalError(err) => {
                write!(f, "{}", err)
            },
        }
    }
}

impl std::error::Error
for ChainCreationError
{
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        None
    }
}

#[derive(Debug)]
pub enum TrustError
{
    NoAuthorization(PrimaryKey),
    NoAuthorizationOrphan,
    MissingParent(PrimaryKey),
    Time(TimeError),
    UnspecifiedWritability,
}

impl From<TimeError>
for TrustError
{
    fn from(err: TimeError) -> TrustError {
        TrustError::Time(err)
    }   
}

impl std::fmt::Display
for TrustError {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        match self {
            TrustError::NoAuthorization(key) => {
                write!(f, "Data object with key ({}) has no write authorization in its metadata", key.as_hex_string())
            },
            TrustError::MissingParent(key) => {
                write!(f, "Data object references a parent object that does not exist ({})", key.as_hex_string())
            },
            TrustError::NoAuthorizationOrphan => {
                write!(f, "Data objects without a primary key has no write authorization")
            },
            TrustError::Time(err) => {
                write!(f, "Timing error while linting data object - {}", err)
            },
            TrustError::UnspecifiedWritability => {
                write!(f, "The writability of this data object has not been specified")
            },
        }
    }
}

impl std::error::Error
for TrustError
{
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        None
    }
}

#[derive(Debug)]
pub enum LintError {
    IO(std::io::Error),
    MissingWriteKey(Hash),
    Trust(TrustError),
    SerializationError(SerializationError),
}

impl From<std::io::Error>
for LintError
{
    fn from(err: std::io::Error) -> LintError {
        LintError::IO(err)
    }   
}

impl From<SerializationError>
for LintError
{
    fn from(err: SerializationError) -> LintError {
        LintError::SerializationError(err)
    }   
}

impl From<TrustError>
for LintError
{
    fn from(err: TrustError) -> LintError {
        LintError::Trust(err)
    }   
}

impl From<TimeError>
for LintError
{
    fn from(err: TimeError) -> LintError {
        LintError::Trust(TrustError::Time(err))
    }   
}

impl std::fmt::Display
for LintError {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        match self {
            LintError::IO(err) => {
                write!(f, "IO error while linting an event - {}", err)
            },
            LintError::MissingWriteKey(hash) => {
                write!(f, "Could not find the write public key ({}) in the session", hash.to_string())
            },
            LintError::SerializationError(err) => {
                write!(f, "Serialization error while linting data object - {}", err)
            },
            LintError::Trust(err) => {
                write!(f, "Trust error while linting data object - {}", err)
            },
        }
    }
}

impl std::error::Error
for LintError
{
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        None
    }
}

#[derive(Debug)]
pub enum ValidationError {
    Denied,
    AllAbstained,
    Detached,
    NoSignatures,
    Trust(TrustError),
}

impl From<TrustError>
for ValidationError
{
    fn from(err: TrustError) -> ValidationError {
        ValidationError::Trust(err)
    }   
}

impl From<TimeError>
for ValidationError
{
    fn from(err: TimeError) -> ValidationError {
        ValidationError::Trust(TrustError::Time(err))
    }   
}

impl std::fmt::Display
for ValidationError {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        match self {
            ValidationError::AllAbstained => {
                write!(f, "None of the validators approved this data object event")
            },
            ValidationError::Denied => {
                write!(f, "The data was rejected by one of the validators")
            },
            ValidationError::Detached => {
                write!(f, "The data object event is detached from the chain of trust")
            },
            ValidationError::NoSignatures => {
                write!(f, "The data object event has no signatures and one is required to store it at this specific location within the chain of trust")
            },
            ValidationError::Trust(err) => {
                write!(f, "The data object event has an issue with trust - {}", err)
            },
        }
    }
}

impl std::error::Error
for ValidationError
{
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        None
    }
}

#[derive(Debug)]
pub enum TimeError
{
    IO(std::io::Error),
    SystemTimeError(SystemTimeError),
    BeyondTolerance(u32),
    NoTimestamp,
    OutOfBounds(std::time::Duration),
}

impl From<std::io::Error>
for TimeError
{
    fn from(err: std::io::Error) -> TimeError {
        TimeError::IO(err)
    }   
}

impl From<SystemTimeError>
for TimeError
{
    fn from(err: SystemTimeError) -> TimeError {
        TimeError::SystemTimeError(err)
    }   
}

impl std::fmt::Display
for TimeError {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        match self {
            TimeError::IO(err) => {
                write!(f, "IO error while computing the current time - {}", err.to_string())
            },
            TimeError::SystemTimeError(err) => {
                write!(f, "System clock error while computing the current time - {}", err.to_string())
            },
            TimeError::BeyondTolerance(err) => {
                write!(f, "The network latency is beyond tolerance to synchronize the clocks - {}", err.to_string())
            },
            TimeError::NoTimestamp => {
                write!(f, "The data object has no timestamp metadata attached to it")
            },
            TimeError::OutOfBounds(dur) => {
                let time = std::time::UNIX_EPOCH + *dur;
                let datetime: chrono::DateTime<chrono::Utc> = time.into();
                write!(f, "The network latency is beyond tolerance to synchronize the clocks - {}", datetime.format("%d/%m/%Y %T"))
            },
        }
    }
}

impl std::error::Error
for TimeError
{
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        None
    }
}

#[derive(Debug)]
pub enum CommitError
{
    #[allow(dead_code)]
    Aborted,
    TransformError(TransformError),
    LintError(LintError),
    SinkError(SinkError),
    IO(tokio::io::Error),
    ValidationError(Vec<ValidationError>),
    SerializationError(SerializationError),
    PipeError(String),
    RootError(String),
    CommsError(CommsError),
}

impl From<TransformError>
for CommitError
{
    fn from(err: TransformError) -> CommitError {
        CommitError::TransformError(err)
    }   
}

impl From<LintError>
for CommitError
{
    fn from(err: LintError) -> CommitError {
        CommitError::LintError(err)
    }   
}

impl From<CommsError>
for CommitError
{
    fn from(err: CommsError) -> CommitError {
        CommitError::CommsError(err)
    }   
}

impl From<SinkError>
for CommitError
{
    fn from(err: SinkError) -> CommitError {
        CommitError::SinkError(err)
    }   
}

impl From<ValidationError>
for CommitError
{
    fn from(err: ValidationError) -> CommitError {
        let mut errors = Vec::new();
        errors.push(err);
        CommitError::ValidationError(errors)
    }   
}

impl From<tokio::io::Error>
for CommitError
{
    fn from(err: tokio::io::Error) -> CommitError {
        CommitError::IO(err)
    }   
}

impl From<SerializationError>
for CommitError
{
    fn from(err: SerializationError) -> CommitError {
        CommitError::SerializationError(err)
    }   
}

impl From<smpsc::RecvError>
for CommitError
{
    fn from(err: smpsc::RecvError) -> CommitError {
        CommitError::PipeError(err.to_string())
    }   
}

impl<T> From<smpsc::SendError<T>>
for CommitError
{
    fn from(err: smpsc::SendError<T>) -> CommitError {
        CommitError::PipeError(err.to_string())
    }   
}

impl From<mpsc::error::RecvError>
for CommitError
{
    fn from(err: mpsc::error::RecvError) -> CommitError {
        CommitError::PipeError(err.to_string())
    }   
}

impl<T> From<mpsc::error::SendError<T>>
for CommitError
{
    fn from(err: mpsc::error::SendError<T>) -> CommitError {
        CommitError::PipeError(err.to_string())
    }   
}

impl<T> From<broadcast::error::SendError<T>>
for CommitError
{
    fn from(err: broadcast::error::SendError<T>) -> CommitError {
        CommitError::PipeError(err.to_string())
    }   
}

impl std::fmt::Display
for CommitError {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        match self {
            CommitError::Aborted => {
                write!(f, "The transaction aborted before it could be completed")
            },
            CommitError::TransformError(err) => {
                write!(f, "Failed to commit the data due to an error transforming the data object into events - {}", err.to_string())
            },
            CommitError::CommsError(err) => {
                write!(f, "Failed to commit the data due to an error in communication - {}", err.to_string())
            },
            CommitError::LintError(err) => {
                write!(f, "Failed to commit the data due to an error linting the data object events - {}", err.to_string())
            },
            CommitError::SinkError(err) => {
                write!(f, "Failed to commit the data due to an error accepting the event into a sink - {}", err.to_string())
            },
            CommitError::IO(err) => {
                write!(f, "Failed to commit the data due to an IO error - {}", err.to_string())
            },
            CommitError::ValidationError(errs) => {
                write!(f, "Failed to commit the data due to a validation error")?;
                for err in errs.iter() {
                    write!(f, " - {}", err.to_string())?;
                }
                Ok(())
            },
            CommitError::SerializationError(err) => {
                write!(f, "Failed to commit the data due to an serialization error - {}", err.to_string())
            },
            CommitError::PipeError(err) => {
                write!(f, "Failed to commit the data due to an error receiving the result in the interprocess pipe - {}", err.to_string())
            },
            CommitError::RootError(err) => {
                write!(f, "Failed to commit the data due to an error at the root server while processing the events - {}", err.to_string())
            },
        }
    }
}

impl std::error::Error
for CommitError
{
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        None
    }
}

#[derive(Debug)]
pub enum CommsError
{
    SerializationError(SerializationError),
    SendError(String),
    ReceiveError(String),
    IO(std::io::Error),
    NoReplyChannel,
    NoWireFormat,
    Disconnected,
    ValidationError(Vec<ValidationError>),
    #[allow(dead_code)]
    JoinError(JoinError),
    LoadError(LoadError),
    RootServerError(String),
    InternalError(String),
}

impl From<SerializationError>
for CommsError
{
    fn from(err: SerializationError) -> CommsError {
        CommsError::SerializationError(err)
    }   
}

impl From<std::io::Error>
for CommsError
{
    fn from(err: std::io::Error) -> CommsError {
        CommsError::IO(err)
    }   
}

impl<T> From<mpsc::error::SendError<T>>
for CommsError
{
    fn from(err: mpsc::error::SendError<T>) -> CommsError {
        CommsError::SendError(err.to_string())
    }   
}

impl From<mpsc::error::RecvError>
for CommsError
{
    fn from(err: mpsc::error::RecvError) -> CommsError {
        CommsError::ReceiveError(err.to_string())
    }   
}

impl From<smpsc::RecvError>
for CommsError
{
    fn from(err: smpsc::RecvError) -> CommsError {
        CommsError::ReceiveError(err.to_string())
    }   
}

impl<T> From<smpsc::SendError<T>>
for CommsError
{
    fn from(err: smpsc::SendError<T>) -> CommsError {
        CommsError::SendError(err.to_string())
    }   
}

impl<T> From<tokio::sync::broadcast::error::SendError<T>>
for CommsError
{
    fn from(err: tokio::sync::broadcast::error::SendError<T>) -> CommsError {
        CommsError::SendError(err.to_string())
    }   
}

impl From<tokio::sync::broadcast::error::RecvError>
for CommsError
{
    fn from(err: tokio::sync::broadcast::error::RecvError) -> CommsError {
        CommsError::ReceiveError(err.to_string())
    }   
}

impl From<JoinError>
for CommsError
{
    fn from(err: JoinError) -> CommsError {
        CommsError::ReceiveError(err.to_string())
    }   
}

impl From<LoadError>
for CommsError
{
    fn from(err: LoadError) -> CommsError {
        CommsError::LoadError(err)
    }   
}

impl From<ChainCreationError>
for CommsError
{
    fn from(err: ChainCreationError) -> CommsError {
        CommsError::RootServerError(err.to_string())
    }   
}

impl From<CommitError>
for CommsError
{
    fn from(err: CommitError) -> CommsError {
        match err {
            CommitError::ValidationError(errs) => CommsError::ValidationError(errs),
            err => CommsError::InternalError(format!("commit-failed - {}", err.to_string())),
        }
    }   
}

impl From<bincode::Error>
for CommsError
{
    fn from(err: bincode::Error) -> CommsError {
        CommsError::SerializationError(SerializationError::BincodeError(err))
    }   
}

impl From<RmpDecodeError>
for CommsError {
    fn from(err: RmpDecodeError) -> CommsError {
        CommsError::SerializationError(SerializationError::DecodeError(err))
    }
}

impl From<JsonError>
for CommsError {
    fn from(err: JsonError) -> CommsError {
        CommsError::SerializationError(SerializationError::JsonError(err))
    }
}

impl std::fmt::Display
for CommsError {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        match self {
            CommsError::SerializationError(err) => {
                write!(f, "Serialization error while processing communication - {}", err)
            },
            CommsError::IO(err) => {
                write!(f, "IO error while processing communication - {}", err)
            },
            CommsError::SendError(err) => {
                write!(f, "Sending error while processing communication - {}", err)
            },
            CommsError::ReceiveError(err) => {
                write!(f, "Receiving error while processing communication - {}", err)
            },
            CommsError::NoReplyChannel => {
                write!(f, "Message has no reply channel attached to it")
            },
            CommsError::NoWireFormat => {
                write!(f, "Server did not send a wire format")
            },
            CommsError::ValidationError(errs) => {
                write!(f, "Message contained event data that failed validation")?;
                for err in errs.iter() {
                    write!(f, " - {}", err.to_string())?;
                }
                Ok(())
            },
            CommsError::Disconnected => {
                write!(f, "Channel has been disconnected")
            },
            CommsError::JoinError(err) => {
                write!(f, "Receiving error while processing communication - {}", err)
            },
            CommsError::LoadError(err) => {
                write!(f, "Load error occured while processing communication - {}", err)
            },
            CommsError::RootServerError(err) => {
                write!(f, "Error at the root server while processing communication - {}", err)
            },
            CommsError::InternalError(err) => {
                write!(f, "Internal comms error - {}", err)
            },
        }
    }
}

impl std::error::Error
for CommsError
{
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        None
    }
}

#[derive(Debug)]
#[allow(dead_code)]
pub enum BusError
{
    LoadError(LoadError),
    ReceiveError(String),
    ChannelClosed,
    SerializationError(SerializationError),
    LockError(LockError),
    TransformError(TransformError),
}

impl From<LoadError>
for BusError
{
    fn from(err: LoadError) -> BusError {
        BusError::LoadError(err)
    }   
}

impl From<TransformError>
for BusError
{
    fn from(err: TransformError) -> BusError {
        BusError::TransformError(err)
    }   
}

impl From<SerializationError>
for BusError
{
    fn from(err: SerializationError) -> BusError {
        BusError::SerializationError(err)
    }   
}

impl From<mpsc::error::RecvError>
for BusError
{
    fn from(err: mpsc::error::RecvError) -> BusError {
        BusError::ReceiveError(err.to_string())
    }   
}

impl From<smpsc::RecvError>
for BusError
{
    fn from(err: smpsc::RecvError) -> BusError {
        BusError::ReceiveError(err.to_string())
    }   
}

impl From<LockError>
for BusError
{
    fn from(err: LockError) -> BusError {
        BusError::LockError(err)
    }   
}

impl std::fmt::Display
for BusError {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        match self {
            BusError::LoadError(err) => {
                write!(f, "Failed to receive event from BUS due to an error loading the event - {}", err)
            },
            BusError::TransformError(err) => {
                write!(f, "Failed to receive event from BUS due to an error transforming the data - {}", err)
            },
            BusError::ReceiveError(err) => {
                write!(f, "Failed to receive event from BUS due to an internal error  - {}", err)
            },
            BusError::ChannelClosed => {
                write!(f, "Failed to receive event from BUS as the channel is closed")
            },
            BusError::SerializationError(err) => {
                write!(f, "Failed to send event to the BUS due to an error in serialization - {}", err)
            },
            BusError::LockError(err) => {
                write!(f, "Failed to receive event from BUS due to an error locking the data object - {}", err)
            },
        }
    }
}

impl std::error::Error
for BusError
{
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        None
    }
}

#[derive(Debug)]
pub enum LockError
{
    SerializationError(SerializationError),
    LintError(LintError),
    CommitError(String),
    ReceiveError(String),
}

impl From<SerializationError>
for LockError
{
    fn from(err: SerializationError) -> LockError {
        LockError::SerializationError(err)
    }   
}

impl From<LintError>
for LockError
{
    fn from(err: LintError) -> LockError {
        LockError::LintError(err)
    }   
}

impl From<CommitError>
for LockError
{
    fn from(err: CommitError) -> LockError {
        LockError::CommitError(err.to_string())
    }   
}

impl From<mpsc::error::RecvError>
for LockError
{
    fn from(err: mpsc::error::RecvError) -> LockError {
        LockError::ReceiveError(err.to_string())
    }   
}

impl From<smpsc::RecvError>
for LockError
{
    fn from(err: smpsc::RecvError) -> LockError {
        LockError::ReceiveError(err.to_string())
    }   
}

impl std::fmt::Display
for LockError {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        match self {
            LockError::SerializationError(err) => {
                write!(f, "Failed to lock the data object due to a serialization error - {}", err)
            },
            LockError::LintError(err) => {
                write!(f, "Failed to lock the data object due to issue linting the event - {}", err)
            },
            LockError::CommitError(err) => {
                write!(f, "Failed to lock the data object due to issue committing the event to the pipe - {}", err)
            },
            LockError::ReceiveError(err) => {
                write!(f, "Failed to lock the data object due to an error receiving on the pipe - {}", err)
            },
        }
    }
}

impl std::error::Error
for LockError
{
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        None
    }
}

#[derive(Debug)]
pub enum InvokeError<E>
{
    Reply(E),
    LoadError(LoadError),
    SerializationError(SerializationError),
    CommitError(CommitError),
    LockError(LockError),
    PipeError(String),
    ServiceError(String),
    Timeout,
    Aborted
}

impl<E> From<SerializationError>
for InvokeError<E>
{
    fn from(err: SerializationError) -> InvokeError<E> {
        InvokeError::SerializationError(err)
    }   
}

impl<E> From<LockError>
for InvokeError<E>
{
    fn from(err: LockError) -> InvokeError<E> {
        InvokeError::LockError(err)
    }   
}

impl<T, E> From<mpsc::error::SendError<T>>
for InvokeError<E>
{
    fn from(err: mpsc::error::SendError<T>) -> InvokeError<E> {
        InvokeError::PipeError(err.to_string())
    }   
}

impl<E> From<LoadError>
for InvokeError<E>
{
    fn from(err: LoadError) -> InvokeError<E> {
        InvokeError::LoadError(err)
    }   
}

impl<E> From<CommitError>
for InvokeError<E>
{
    fn from(err: CommitError) -> InvokeError<E> {
        InvokeError::CommitError(err)
    }   
}

impl<E> From<tokio::time::error::Elapsed>
for InvokeError<E>
{
    fn from(_elapsed: tokio::time::error::Elapsed) -> InvokeError<E> {
        InvokeError::Timeout
    }
}

impl<E> std::fmt::Display
for InvokeError<E>
where E: std::fmt::Debug
{
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        match self {
            InvokeError::LoadError(err) => {
                write!(f, "Command failed - {}", err)
            },
            InvokeError::SerializationError(err) => {
                write!(f, "Command failed - {}", err)
            },
            InvokeError::LockError(err) => {
                write!(f, "Command failed - {}", err)
            },
            InvokeError::CommitError(err) => {
                write!(f, "Command failed - {}", err)
            },
            InvokeError::PipeError(err) => {
                write!(f, "Command failed - {}", err)
            },
            InvokeError::Reply(_) => {
                write!(f, "Command failed for an unspecified reason")
            },
            InvokeError::ServiceError(err) => {
                write!(f, "Command failed - {}", err)
            },
            InvokeError::Timeout => {
                write!(f, "Command failed - Timeout")
            },
            InvokeError::Aborted => {
                write!(f, "Command failed - Aborted")
            },
        }
    }
}

#[derive(Debug, Serialize, Deserialize, Clone)]
pub enum ServiceErrorReply<E>
{
    Reply(E),
    ServiceError(String),
}

#[derive(Debug)]
pub enum ServiceError<E>
{
    Reply(E),
    IO(tokio::io::Error),
    LoadError(LoadError),
    SerializationError(SerializationError),
    ChainCreationError(ChainCreationError),
    CommitError(CommitError),
    LockError(LockError),
    PipeError(String),
    ServiceError(String),
    Timeout,
    Aborted
}

impl<E> From<SerializationError>
for ServiceError<E>
{
    fn from(err: SerializationError) -> ServiceError<E> {
        ServiceError::SerializationError(err)
    }   
}

impl<E> From<LockError>
for ServiceError<E>
{
    fn from(err: LockError) -> ServiceError<E> {
        ServiceError::LockError(err)
    }   
}

impl<T, E> From<mpsc::error::SendError<T>>
for ServiceError<E>
{
    fn from(err: mpsc::error::SendError<T>) -> ServiceError<E> {
        ServiceError::PipeError(err.to_string())
    }   
}

impl<E> From<LoadError>
for ServiceError<E>
{
    fn from(err: LoadError) -> ServiceError<E> {
        ServiceError::LoadError(err)
    }   
}

impl<E> From<CommitError>
for ServiceError<E>
{
    fn from(err: CommitError) -> ServiceError<E> {
        ServiceError::CommitError(err)
    }   
}

impl<E> From<ChainCreationError>
for ServiceError<E>
{
    fn from(err: ChainCreationError) -> ServiceError<E> {
        ServiceError::ChainCreationError(err)
    }   
}

impl<E> From<tokio::time::error::Elapsed>
for ServiceError<E>
{
    fn from(_elapsed: tokio::time::error::Elapsed) -> ServiceError<E> {
        ServiceError::Timeout
    }
}

impl<E> From<tokio::io::Error>
for ServiceError<E>
{
    fn from(err: tokio::io::Error) -> ServiceError<E> {
        ServiceError::IO(err)
    }   
}

impl<E> From<ServiceErrorReply<E>>
for ServiceError<E>
{
    fn from(err: ServiceErrorReply<E>) -> ServiceError<E> {
        match err {
            ServiceErrorReply::Reply(err) => ServiceError::Reply(err),
            ServiceErrorReply::ServiceError(err) => ServiceError::ServiceError(err)
        }
    } 
}

impl<E> ServiceError<E>
{
    pub fn as_reply(self) -> (ServiceErrorReply<E>, ServiceError<()>)
    {
        match self {
            ServiceError::Reply(e) => (ServiceErrorReply::Reply(e), ServiceError::Reply(())),
            err => {
                let err = err.strip();
                (
                    ServiceErrorReply::ServiceError(err.to_string()),
                    err
                )
            }
        }
    }

    pub fn strip(self) -> ServiceError<()>
    {
        match self {
            ServiceError::LoadError(a) => ServiceError::LoadError(a),
            ServiceError::SerializationError(a) => ServiceError::SerializationError(a),
            ServiceError::LockError(a) => ServiceError::LockError(a),
            ServiceError::CommitError(a) => ServiceError::CommitError(a),
            ServiceError::ChainCreationError(a) => ServiceError::ChainCreationError(a),
            ServiceError::PipeError(a) => ServiceError::PipeError(a),
            ServiceError::IO(a) => ServiceError::IO(a),
            ServiceError::Reply(_) => ServiceError::Reply(()),
            ServiceError::ServiceError(a) => ServiceError::ServiceError(a),
            ServiceError::Timeout => ServiceError::Timeout,
            ServiceError::Aborted => ServiceError::Aborted,
        }
    }
}

impl<E> std::fmt::Display
for ServiceError<E>
where E: std::fmt::Debug
{
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        match self {
            ServiceError::LoadError(err) => {
                write!(f, "Command failed - {}", err)
            },
            ServiceError::SerializationError(err) => {
                write!(f, "Command failed - {}", err)
            },
            ServiceError::LockError(err) => {
                write!(f, "Command failed - {}", err)
            },
            ServiceError::CommitError(err) => {
                write!(f, "Command failed - {}", err)
            },
            ServiceError::ChainCreationError(err) => {
                write!(f, "Command failed - {}", err)
            },
            ServiceError::PipeError(err) => {
                write!(f, "Command failed - {}", err)
            },
            ServiceError::IO(err) => {
                write!(f, "Command failed - {}", err)
            },
            ServiceError::ServiceError(err) => {
                write!(f, "Command failed - {}", err)
            },
            ServiceError::Reply(err) => {
                write!(f, "Command failed - {:?}", err)
            },
            ServiceError::Timeout => {
                write!(f, "Command failed - Timeout")
            },
            ServiceError::Aborted => {
                write!(f, "Command failed - Aborted")
            },
        }
    }
}

/// Super-set of all errors that could possibly happen within this ATE library
/// This error allows one to roll up all the errors into a clean object using
/// standard from conversions for cleaner code.
#[derive(Debug)]
pub enum AteError
{
    LockError(LockError),
    BusError(BusError),
    CommsError(CommsError),
    CommitError(CommitError),
    TimeError(TimeError),
    LintError(LintError),
    ChainCreationError(ChainCreationError),
    ProcessError(ProcessError),
    SerializationError(SerializationError),
    SinkError(SinkError),
    CompactError(CompactError),
    LoadError(LoadError),
    IO(tokio::io::Error),
    CryptoError(CryptoError),
    TransformError(TransformError),
    InvokeError(String),
    ServiceError(String),
    NotImplemented,
}

impl From<LockError>
for AteError
{
    fn from(err: LockError) -> AteError {
        AteError::LockError(err)
    }   
}

impl From<BusError>
for AteError
{
    fn from(err: BusError) -> AteError {
        AteError::BusError(err)
    }   
}

impl From<CommsError>
for AteError
{
    fn from(err: CommsError) -> AteError {
        AteError::CommsError(err)
    }   
}

impl From<CommitError>
for AteError
{
    fn from(err: CommitError) -> AteError {
        AteError::CommitError(err)
    }   
}

impl From<TimeError>
for AteError
{
    fn from(err: TimeError) -> AteError {
        AteError::TimeError(err)
    }   
}

impl From<LintError>
for AteError
{
    fn from(err: LintError) -> AteError {
        AteError::LintError(err)
    }   
}

impl From<ChainCreationError>
for AteError
{
    fn from(err: ChainCreationError) -> AteError {
        AteError::ChainCreationError(err)
    }   
}

impl From<ProcessError>
for AteError
{
    fn from(err: ProcessError) -> AteError {
        AteError::ProcessError(err)
    }   
}

impl From<SerializationError>
for AteError
{
    fn from(err: SerializationError) -> AteError {
        AteError::SerializationError(err)
    }   
}

impl From<SinkError>
for AteError
{
    fn from(err: SinkError) -> AteError {
        AteError::SinkError(err)
    }   
}

impl From<CompactError>
for AteError
{
    fn from(err: CompactError) -> AteError {
        AteError::CompactError(err)
    }   
}

impl From<LoadError>
for AteError
{
    fn from(err: LoadError) -> AteError {
        AteError::LoadError(err)
    }   
}

impl From<TransformError>
for AteError
{
    fn from(err: TransformError) -> AteError {
        AteError::TransformError(err)
    }   
}

impl From<CryptoError>
for AteError
{
    fn from(err: CryptoError) -> AteError {
        AteError::CryptoError(err)
    }   
}

impl From<tokio::io::Error>
for AteError
{
    fn from(err: tokio::io::Error) -> AteError {
        AteError::IO(err)
    }   
}

impl<E> From<InvokeError<E>>
for AteError
where E: std::fmt::Debug
{
    fn from(err: InvokeError<E>) -> AteError {
        AteError::InvokeError(err.to_string())
    }   
}

impl<E> From<ServiceError<E>>
for AteError
where E: std::fmt::Debug
{
    fn from(err: ServiceError<E>) -> AteError {
        AteError::ServiceError(err.to_string())
    }   
}

impl std::fmt::Display
for AteError {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        match self {
            AteError::BusError(err) => {
                write!(f, "{}", err)
            },
            AteError::ChainCreationError(err) => {
                write!(f, "{}", err)
            },
            AteError::CommitError(err) => {
                write!(f, "{}", err)
            },
            AteError::CommsError(err) => {
                write!(f, "{}", err)
            },
            AteError::CompactError(err) => {
                write!(f, "{}", err)
            },
            AteError::CryptoError(err) => {
                write!(f, "{}", err)
            },
            AteError::LintError(err) => {
                write!(f, "{}", err)
            },
            AteError::LoadError(err) => {
                write!(f, "{}", err)
            },
            AteError::LockError(err) => {
                write!(f, "{}", err)
            },
            AteError::ProcessError(err) => {
                write!(f, "{}", err)
            },
            AteError::SerializationError(err) => {
                write!(f, "{}", err)
            },
            AteError::SinkError(err) => {
                write!(f, "{}", err)
            },
            AteError::TimeError(err) => {
                write!(f, "{}", err)
            },
            AteError::TransformError(err) => {
                write!(f, "{}", err)
            },
            AteError::IO(err) => {
                write!(f, "{}", err)
            },
            AteError::InvokeError(err) => {
                write!(f, "{}", err)
            },
            AteError::ServiceError(err) => {
                write!(f, "{}", err)
            },
            AteError::NotImplemented => {
                write!(f, "Not implemented")
            },
        }
    }
}

impl std::error::Error
for AteError
{
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        None
    }
}

pub fn eat<T>(ret: Result<T, AteError>) -> Option<T> {
    match ret {
        Ok(a) => Some(a),
        Err(err) => {
            debug!("error: {}", err);
            None
        }
    }
}

pub fn eat_load<T>(ret: Result<T, LoadError>) -> Option<T> {
    match ret {
        Ok(a) => Some(a),
        Err(err) => {
            debug!("error: {}", err);
            None
        }
    }
}

pub fn eat_serialization<T>(ret: Result<T, SerializationError>) -> Option<T> {
    match ret {
        Ok(a) => Some(a),
        Err(err) => {
            debug!("error: {}", err);
            None
        }
    }
}

pub fn eat_commit<T>(ret: Result<T, CommitError>) -> Option<T> {
    match ret {
        Ok(a) => Some(a),
        Err(err) => {
            debug!("error: {}", err);
            None
        }
    }
}

pub fn eat_lock<T>(ret: Result<T, LockError>) -> Option<T> {
    match ret {
        Ok(a) => Some(a),
        Err(err) => {
            debug!("error: {}", err);
            None
        }
    }
}