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
#![allow(clippy::all)]
use std::{error::Error, ffi::OsString, io::Cursor};

use crate::verify::{is_valid_rewards_address, stake_key_hash, StakeKeyHash};

use bytekind::{Bytes, HexString};
use ciborium::value::Value;
use clap::builder::OsStr;
use hex::FromHexError;

use microtype::microtype;

use serde::{Deserialize, Serialize, Serializer};

pub use crypto2::{PubKey, Sig};
mod crypto2;

pub mod hex_bytes;
mod network_id;
pub use network_id::NetworkId;

use test_strategy::Arbitrary;

use hash::hash;
mod hash;

// Networks
const NETWORK_ID: usize = 0;

// 61284 entries
const KEY_61284: usize = 0;
const DELEGATIONS_OR_DIRECT: usize = 0;
const STAKE_ADDRESS: usize = 1;
const PAYMENT_ADDRESS: usize = 2;
const NONCE: usize = 3;
const VOTE_PURPOSE: usize = 4;

const VOTE_KEY: usize = 0;
const WEIGHT: usize = 1;

// 61285
const KEY_61285: usize = 0;
const WITNESS: usize = 0;

use crate::{
    verify::{validate_reg_cddl, validate_sig_cddl, CddlConfig},
    RegistrationError,
};

use cardano_serialization_lib::chain_crypto::Ed25519;
use cardano_serialization_lib::chain_crypto::{
    AsymmetricPublicKey, Verification, VerificationAlgorithm,
};

/// The source of voting power for a given registration
///
/// The voting power can either come from:
///  - a single wallet, OR
///  - a set of delegations
#[derive(Serialize, Deserialize)]
#[serde(untagged)]
#[derive(Debug, Clone, PartialEq)]
pub enum VotingKey {
    /// Direct voting
    ///
    /// Voting power is based on the staked ada of the given key
    Direct(VotingKeyHex),

    /// Delegated voting
    ///
    /// Voting power is based on the staked ada of the delegated keys
    /// order of elements is important and must be preserved.
    Delegated(Vec<(VotingKeyHex, u64)>),
}

impl VotingKey {
    /// Create a direct voting power source from a hex string representing a voting key
    ///
    /// # Errors
    ///
    /// Returns an error if `s` is not a hex string representing an array of 32 bytes (i.e. a 64
    /// character string)
    #[inline]
    pub fn direct_from_hex(s: &str) -> Result<Self, FromHexError> {
        let bytes = hex::decode(s)?;
        Ok(Self::Direct(PubKey(bytes).into()))
    }
}

/// A catalyst registration on Cardano in either CIP-15 or CIP-36 format
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
pub struct Registration {
    #[serde(rename = "1")]
    pub voting_key: VotingKey,
    #[serde(rename = "2")]
    pub stake_key: StakeKeyHex,
    #[serde(rename = "3", serialize_with = "ox_hex_")]
    pub rewards_address: RewardsAddress,
    // note, this must be monotonically increasing. Typically, the current slot
    // number is used
    #[serde(rename = "4")]
    pub nonce: Nonce,
    #[serde(rename = "5")]
    pub voting_purpose: Option<VotingPurpose>,
}

/// A signature for a registration as defined in CIP-15
///
/// This is compatible with CIP-36 registrations
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
pub struct Signature {
    /// The actual signature
    ///
    /// CIP-15 specifies this must be a field, so an extra layer of nesting is required
    #[serde(rename = "1", serialize_with = "ox_hex_sig")]
    pub inner: Sig,
}

fn ox_hex_sig<T, S>(v: &T, serializer: S) -> Result<S::Ok, S::Error>
where
    T: AsRef<[u8]>,
    S: Serializer,
{
    serializer.serialize_str(&format!("0x{}", hex::encode(v.as_ref())))
}

/// A Catalyst registration in either CIP-15 or CIP-36 format, along with its signature
///
/// The signature is generated by:
///  - CBOR encoding the registration as a single entry map with a key of `61284` and a value of
///  the registration
///  - Hashing the bytes of the CBOR encoding with `blake2b_256`
///  - Signing the hash with the public key
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
pub struct SignedRegistration {
    /// The registration
    #[serde(rename = "61284")]
    pub registration: Registration,
    /// The signature
    #[serde(rename = "61285")]
    pub signature: Signature,

    /// Stake Key Hash
    #[serde(serialize_with = "ox_hex")]
    pub stake_key_hash: StakeKeyHash,

    /// The id of the transaction that created this registration
    pub tx_id: TxId,

    /// The slot the registration was found in.
    pub slot: u64,
}

fn ox_hex<T, S>(v: &T, serializer: S) -> Result<S::Ok, S::Error>
where
    T: AsRef<[u8]>,
    S: Serializer,
{
    serializer.serialize_str(&format!("0x{}", hex::encode(v.as_ref())))
}

impl SignedRegistration {
    /// The signature is generated by:
    ///  - CBOR encoding the registration
    ///  - blake2b-256 hashing those bytes
    ///  - signing the hash with the private key used to generate the stake key
    pub fn validate_signature_bin(&self, bin_reg: Vec<u8>) -> Result<(), RegistrationError> {
        let bytes = bin_reg;
        let hash_bytes = hash(&bytes);

        let pub_key = Ed25519::public_from_binary(self.registration.stake_key.as_ref())
            .map_err(|e| RegistrationError::StakePublicKeyError { err: e.to_string() })?;
        let sig = Ed25519::signature_from_bytes(self.signature.inner.as_ref())
            .map_err(|e| RegistrationError::SignatureError { err: e.to_string() })?;

        match Ed25519::verify_bytes(&pub_key, &sig, &hash_bytes) {
            Verification::Success => Ok(()),
            Verification::Failed => Err(RegistrationError::MismatchedSignature { hash_bytes }),
        }
    }

    pub fn validate_multi_delegation(
        &self,
        multi_delegation_enabled: bool,
    ) -> Result<(), RegistrationError> {
        match &self.registration.voting_key {
            VotingKey::Direct(_) => (),
            VotingKey::Delegated(delegation) => {
                if !multi_delegation_enabled && delegation.len() != 1 {
                    return Err(RegistrationError::DelegationError {
                        err: "CIP-36 Multiple Delegations are unsupported.".to_string(),
                    });
                }
            }
        }
        Ok(())
    }
}

/// A Raw Registration from the `DB.arbitrary_signed_registration`
///
#[derive(Debug, Clone)]
pub struct RawRegistration {
    /// cip 15/36: 61284 json from DB.
    pub json_reg: serde_json::Value,

    /// cip 15/36: 61285 json from DB.
    pub json_sig: serde_json::Value,

    /// cip 15/36: 61284 raw binary
    pub bin_reg: Vec<u8>,

    /// cip 15/36: 61285 raw binary
    pub bin_sig: Vec<u8>,

    /// registration tx_id
    pub tx_id: TxId,

    /// The slot the registration was found in.
    pub slot: u64,
}

impl RawRegistration {
    pub fn to_signed(
        &self,
        cddl_config: &CddlConfig,
        network_id: NetworkId,
    ) -> Result<SignedRegistration, Box<dyn Error>> {
        // validate cddl: 61284
        validate_reg_cddl(&self.bin_reg, cddl_config)?;

        // validate cddl: 61285
        validate_sig_cddl(&self.bin_sig, cddl_config)?;

        let registration = self.raw_reg_conversion(network_id)?;

        let signature = self.raw_sig_conversion()?;

        Ok(SignedRegistration {
            registration: registration.clone(),
            signature,
            stake_key_hash: stake_key_hash(&registration.stake_key, network_id),
            tx_id: self.tx_id,
            slot: self.slot,
        })
    }

    fn raw_reg_conversion(&self, network_id: NetworkId) -> Result<Registration, Box<dyn Error>> {
        let decoded: ciborium::value::Value =
            ciborium::de::from_reader(Cursor::new(&self.bin_reg))?;

        // CBOR representation of a map containing a single entry with key 61284. See CIP-36 for context.
        let spec_61284 = match inspect_cip36_reg(&decoded) {
            Ok(value) => value,
            Err(value) => return value,
        };

        // 4 entries inside metadata map with one optional entry for the voting purpose
        let metamap = match inspect_metamap_reg(&spec_61284) {
            Ok(value) => value,
            Err(value) => return value,
        };

        // voting key: simply an ED25519 public key. This is the spending credential in the sidechain that will receive voting power
        // from this delegation. For direct voting it's necessary to have the corresponding private key to cast votes in the sidechain
        let voting_key = match inspect_voting_key(metamap) {
            Ok(value) => value,
            Err(value) => return value,
        };

        // A stake address for the network that this transaction is submitted to (to point to the Ada that is being delegated);
        let stake_key = match inspect_stake_key(metamap) {
            Ok(value) => value,
            Err(value) => return value,
        };

        // A Shelley payment address (see CIP-0019) discriminated for the same network
        // this transaction is submitted to, to receive rewards.
        let rewards_address = match inspect_rewards_addr(metamap, network_id) {
            Ok(value) => value,
            Err(value) => return value,
        };

        // A nonce that identifies that most recent delegation
        let nonce = match inspect_nonce(metamap) {
            Ok(value) => value,
            Err(value) => return value,
        };

        // A non-negative integer that indicates the purpose of the vote.
        // This is an optional field to allow for compatibility with CIP-15
        // 4 entries inside metadata map with one optional entry for the voting purpose
        let voting_purpose = inspect_voting_purpose(metamap);

        Ok(Registration {
            voting_key,
            stake_key,
            rewards_address,
            nonce,
            voting_purpose,
        })
    }

    fn raw_sig_conversion(&self) -> Result<Signature, Box<dyn Error>> {
        let decoded: ciborium::value::Value =
            ciborium::de::from_reader(Cursor::new(&self.bin_sig))?;

        let spec_61285 = match inspect_cip36_sig(decoded) {
            Ok(value) => value,
            Err(value) => return value,
        };

        let metamap = match inspect_metamap_sig(&spec_61285) {
            Ok(value) => value,
            Err(value) => return value,
        };

        // ED25119 signature
        let sig = match inspect_witness(metamap) {
            Ok(value) => value,
            Err(value) => return value,
        };

        Ok(Signature { inner: Sig(sig) })
    }
}

///
/// To produce the witness field in the case of a staking public key,
/// the CBOR representation of a map containing a single entry with key 61284
/// and the registration metadata map is signed with the staking key as follows:
/// first, the blake2b-256 hash of the data is obtained. This hash is then signed using the Ed25519 signature algorithm.
/// The witness metadata entry is added to the transaction under key 61285.
/// This function extracts and verifies the witness signature provided in the registration.
fn inspect_witness(
    metamap: &[(Value, Value)],
) -> Result<[u8; 64], Result<Signature, Box<dyn Error>>> {
    let witness = match &metamap[WITNESS] {
        (Value::Integer(_one), Value::Bytes(witness)) => witness.as_slice(),
        _ => {
            return Err(Err(Box::new(
                RegistrationError::RawBinCborSignatureFailure {
                    err: "Unable to extract witness".to_string(),
                },
            )))
        }
    };
    let sig: [u8; 64] = match witness.try_into() {
        Ok(bytes) => bytes,
        Err(err) => {
            return Err(Err(Box::new(
                RegistrationError::RawBinCborSignatureFailure {
                    err: format!("ED25119 signature should be 64 bytes {err}"),
                },
            )))
        }
    };
    Ok(sig)
}

#[allow(clippy::manual_let_else)]
fn inspect_metamap_sig(
    spec_61285: &[Value],
) -> Result<&Vec<(Value, Value)>, Result<Signature, Box<dyn Error>>> {
    let metamap = match &spec_61285[KEY_61285] {
        Value::Map(metamap) => metamap,
        _ => {
            return Err(Err(Box::new(
                RegistrationError::RawBinCborSignatureFailure {
                    err: "Not congruent with CIP-36".to_string(),
                },
            )))
        }
    };
    Ok(metamap)
}

fn inspect_cip36_sig(decoded: Value) -> Result<Vec<Value>, Result<Signature, Box<dyn Error>>> {
    let spec_61285 = match decoded {
        Value::Map(m) => m.iter().map(|entry| entry.1.clone()).collect::<Vec<_>>(),
        _ => {
            return Err(Err(Box::new(
                RegistrationError::RawBinCborSignatureFailure {
                    err: format!("Not congruent with CIP-36 {decoded:?}"),
                },
            )))
        }
    };
    Ok(spec_61285)
}

fn inspect_voting_purpose(metamap: &Vec<(Value, Value)>) -> Option<VotingPurpose> {
    if metamap.len() == 5 {
        match metamap[VOTE_PURPOSE] {
            (Value::Integer(_five), Value::Integer(purpose)) => {
                Some(VotingPurpose(purpose.try_into().unwrap()))
            }
            _ => None,
        }
    } else {
        None
    }
}

fn inspect_nonce(
    metamap: &[(Value, Value)],
) -> Result<Nonce, Result<Registration, Box<dyn Error>>> {
    let nonce = match metamap[NONCE] {
        (Value::Integer(_four), Value::Integer(nonce)) => Nonce(nonce.try_into().unwrap()),
        _ => {
            return Err(Err(Box::new(
                RegistrationError::RawBinCborRegistrationFailure {
                    err: "Unable to extract Nonce".to_string(),
                },
            )))
        }
    };
    Ok(nonce)
}

fn inspect_rewards_addr(
    metamap: &[(Value, Value)],
    network_id: NetworkId,
) -> Result<RewardsAddress, Result<Registration, Box<dyn Error>>> {
    let rewards_address = match &metamap[PAYMENT_ADDRESS] {
        (Value::Integer(_three), Value::Bytes(rewards_addr)) => {
            RewardsAddress::from_hex(&hex::encode(rewards_addr)).unwrap()
        }
        _ => {
            return Err(Err(Box::new(
                RegistrationError::RawBinCborRegistrationFailure {
                    err: "Unable to extract rewards addr".to_string(),
                },
            )))
        }
    };

    if !is_valid_rewards_address(&rewards_address.0[NETWORK_ID], network_id) {
        return Err(Err(Box::new(RegistrationError::InvalidAddressPrefix {
            err: format!(
                "Invalid rewards address: address prefix is: {:?}\n the first hex char should be in the range\n
                0x0? - 0x7? or 0xE? , 0xF?\n
                followed by 0 or 1 which defines the network id",
                format!("{:x}", &rewards_address.0[NETWORK_ID]),
            ),
        })));
    }
    Ok(rewards_address)
}

fn inspect_stake_key(
    metamap: &[(Value, Value)],
) -> Result<StakeKeyHex, Result<Registration, Box<dyn Error>>> {
    let stake_key = match &metamap[STAKE_ADDRESS] {
        (Value::Integer(_two), Value::Bytes(stake_addr)) => {
            // assert!((*two == Value::Integer(2.into()).as_integer().unwrap()));
            StakeKeyHex(PubKey(stake_addr.clone()))
        }
        _ => {
            return Err(Err(Box::new(
                RegistrationError::RawBinCborRegistrationFailure {
                    err: "Unable to extract stake key".to_string(),
                },
            )))
        }
    };
    Ok(stake_key)
}

#[allow(clippy::manual_let_else)]
fn inspect_voting_key(
    metamap: &[(Value, Value)],
) -> Result<VotingKey, Result<Registration, Box<dyn Error>>> {
    let voting_key = match &metamap[DELEGATIONS_OR_DIRECT] {
        (Value::Integer(_one), Value::Bytes(direct)) => {
            VotingKey::Direct(PubKey(direct.clone()).into())
        }
        (Value::Integer(_one), Value::Array(delegations)) => {
            let mut delegations_map: Vec<(VotingKeyHex, u64)> = Vec::new();
            for d in delegations {
                match d {
                    Value::Array(delegations) => {
                        let voting_key = match delegations[VOTE_KEY].as_bytes() {
                            Some(key) => key,
                            None => {
                                return Err(Err(Box::new(
                                    RegistrationError::RawBinCborRegistrationFailure {
                                        err: "Unable to extract voting key from delegation"
                                            .to_string(),
                                    },
                                )))
                            }
                        };

                        let weight = match delegations[WEIGHT].as_integer() {
                            Some(weight) => match weight.try_into() {
                                Ok(weight) => weight,
                                Err(err) => {
                                    return Err(Err(Box::new(
                                        RegistrationError::RawBinCborRegistrationFailure {
                                            err: format!(
                                                "Unable to extract weight for delegation {err}"
                                            ),
                                        },
                                    )))
                                }
                            },
                            None => {
                                return Err(Err(Box::new(
                                    RegistrationError::RawBinCborRegistrationFailure {
                                        err: "Unable to extract voting key from delegation"
                                            .to_string(),
                                    },
                                )))
                            }
                        };

                        delegations_map.push((VotingKeyHex(PubKey(voting_key.clone())), weight));
                    }

                    _ => {
                        return Err(Err(Box::new(
                            RegistrationError::RawBinCborRegistrationFailure {
                                err: "Not congruent with CIP-36".to_string(),
                            },
                        )))
                    }
                }
            }

            VotingKey::Delegated(delegations_map)
        }

        _ => {
            return Err(Err(Box::new(
                RegistrationError::RawBinCborRegistrationFailure {
                    err: "Unable to ascertain direct or delegated voting keys".to_string(),
                },
            )))
        }
    };
    Ok(voting_key)
}

#[allow(clippy::manual_let_else)]
fn inspect_metamap_reg(
    spec_61284: &[Value],
) -> Result<&Vec<(Value, Value)>, Result<Registration, Box<dyn Error>>> {
    let metamap = match &spec_61284[KEY_61284] {
        Value::Map(metamap) => metamap,
        _ => {
            return Err(Err(Box::new(
                RegistrationError::RawBinCborRegistrationFailure {
                    err: "Unable to obtain metadata map".to_string(),
                },
            )))
        }
    };
    Ok(metamap)
}

fn inspect_cip36_reg(decoded: &Value) -> Result<Vec<Value>, Result<Registration, Box<dyn Error>>> {
    let spec_61284 = match decoded {
        Value::Map(m) => m.iter().map(|entry| entry.1.clone()).collect::<Vec<_>>(),
        _ => {
            return Err(Err(Box::new(
                RegistrationError::RawBinCborRegistrationFailure {
                    err: format!("Not congruent with CIP-36 {decoded:?}"),
                },
            )))
        }
    };
    Ok(spec_61284)
}

/// Single element in a snapshot
#[derive(Debug, PartialEq, Serialize, Deserialize)]
pub struct SnapshotEntry {
    /// Registration content
    #[serde(rename = "delegations")]
    pub voting_key: VotingKey,

    /// Mainnet rewards address
    #[serde(serialize_with = "ox_hex_")]
    pub rewards_address: RewardsAddress,

    /// Stake public key
    #[serde(rename = "stake_public_key")]
    pub stake_key: StakeKeyHex,

    /// Voting power expressed in ada
    ///
    /// This is computed from `voting_key`
    pub voting_power: u128,

    /// Voting purpose
    ///
    /// Catalyst expects the voting purpose is set to `0`
    pub voting_purpose: Option<VotingPurpose>,

    /// Registration transaction id
    pub tx_id: TxId,

    /// Registration Nonce
    pub nonce: u64,
}

fn ox_hex_<T, S>(v: &T, serializer: S) -> Result<S::Ok, S::Error>
where
    T: AsRef<[u8]>,
    S: Serializer,
{
    serializer.serialize_str(&format!("0x{}", hex::encode(v.as_ref())))
}

// Create newtype wrappers for better type safety
microtype! {
    #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Arbitrary)]
    pub PubKey {
        VotingKeyHex,
        StakeKeyHex,
    }

    #[derive(Debug, PartialEq, Clone)]
    #[string]
    pub String {
        /// Database name
        DbName,
        /// Database user
        DbUser,
        /// Database host
        DbHost,
        StakeAddr,
        StakePubKey,
    }

    #[secret]
    #[string]
    pub String {
        /// Database password
        DbPass,
    }

    #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Default, Arbitrary)]
    #[int]
    pub u64 {
        Nonce,
        /// A slot number
        SlotNo,

        /// A `u64` used to identify the purpose of a particular registration
        ///
        /// `0` is used for catalyst voting
        VotingPurpose,
        TxId,
    }

    #[derive(Debug, Clone, PartialEq, Eq)]
    pub Bytes<HexString> {
        /// A rewards address in a catalyst registation
        ///
        /// This type deliberately does not enforce a particular format for addresses, since the
        /// spec only requires this field to be a byte array, with no other constraints
        RewardsAddress,
    }
}

impl VotingPurpose {
    /// The voting purpose for catalyst registrations
    pub const CATALYST: VotingPurpose = VotingPurpose(0);
}

impl From<VotingPurpose> for OsStr {
    fn from(purpose: VotingPurpose) -> Self {
        OsStr::from(OsString::from(purpose.to_string()))
    }
}

impl From<NetworkId> for OsStr {
    fn from(id: NetworkId) -> Self {
        OsStr::from(match id {
            NetworkId::Mainnet => "mainnet",
            NetworkId::Testnet => "testnet",
        })
    }
}

impl SlotNo {
    /// Attempt to convert this to an `i64`
    ///
    /// Returns none if the underlying `u64` doesn't fit into an `i64`
    #[inline]
    #[must_use]
    pub fn into_i64(self) -> Option<i64> {
        self.0.try_into().ok()
    }
}

impl RewardsAddress {
    /// Decode a [`RewardsAddress`] from a hex string
    ///
    /// Errors if the string is not valid hex
    ///
    ///
    /// Test broken, can not import `data` crate, it's private.
    /// # use `crate::voting_tools_rs::data::RewardsAddress`;
    /// let address = `RewardsAddress::from_hex("0000").unwrap`();
    /// `assert_eq!(address.0`, vec![0, 0]);
    ///
    #[inline]
    pub fn from_hex(s: &str) -> Result<Self, FromHexError> {
        let bytes = hex::decode(s)?;
        Ok(Self(bytes.into()))
    }
}

impl AsRef<[u8]> for RewardsAddress {
    fn as_ref(&self) -> &[u8] {
        self.0.as_ref()
    }
}

macro_rules! hex_impls {
    ($t:ty) => {
        impl core::fmt::Display for $t {
            fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
                write!(f, "0x{}", hex::encode(&self.0))
            }
        }

        impl AsRef<[u8]> for $t {
            fn as_ref(&self) -> &[u8] {
                self.0.as_ref()
            }
        }
    };
}

hex_impls!(VotingKeyHex);
hex_impls!(StakeKeyHex);