dig-rpc-types 0.1.0

JSON-RPC wire types shared by the DIG Network fullnode + validator RPC servers and their clients. Pure types — no I/O, no async, no logic.
Documentation
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
//! Shared domain types used across multiple RPC methods.
//!
//! This module collects the wire types that more than one method consumes
//! or produces: hex-string hashes / pubkeys / signatures, XCH amounts,
//! block summaries, validator records.
//!
//! All hex-encoded types follow a single convention:
//!
//! - On **serialize**: emit `0x` + lowercase hex.
//! - On **deserialize**: accept upper / lower / mixed case, optional `0x`
//!   prefix.
//!
//! This matches the Chia wire format (where hashes are `0x`-prefixed) and
//! the Ethereum RPC convention, giving us maximum cross-ecosystem
//! compatibility.

use std::fmt;
use std::str::FromStr;

use serde::{Deserialize, Serialize};

// ===========================================================================
// Hex-encoded fixed-length byte arrays
// ===========================================================================

/// A 32-byte hex-encoded value (block hash, coin id, state root, etc).
///
/// Wire form is `"0x"` followed by 64 lowercase hex chars. Deserialization
/// accepts mixed case and optional `0x` prefix.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct HashHex(
    /// Raw 32-byte value.
    pub [u8; 32],
);

impl HashHex {
    /// Construct from a raw 32-byte array.
    pub const fn new(bytes: [u8; 32]) -> Self {
        Self(bytes)
    }

    /// Borrow the underlying 32 bytes.
    pub fn as_bytes(&self) -> &[u8; 32] {
        &self.0
    }
}

impl fmt::Display for HashHex {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "0x{}", hex::encode(self.0))
    }
}

impl FromStr for HashHex {
    type Err = HexParseError;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let bytes = parse_hex_fixed::<32>(s)?;
        Ok(Self(bytes))
    }
}

impl Serialize for HashHex {
    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
        s.collect_str(self)
    }
}

impl<'de> Deserialize<'de> for HashHex {
    fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
        String::deserialize(d)?
            .parse()
            .map_err(serde::de::Error::custom)
    }
}

/// A 48-byte BLS12-381 G1 compressed public key.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct PubkeyHex(
    /// Raw 48-byte compressed G1 element.
    pub [u8; 48],
);

impl PubkeyHex {
    /// Construct from a raw 48-byte array.
    pub const fn new(bytes: [u8; 48]) -> Self {
        Self(bytes)
    }

    /// Borrow the underlying 48 bytes.
    pub fn as_bytes(&self) -> &[u8; 48] {
        &self.0
    }
}

impl fmt::Display for PubkeyHex {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "0x{}", hex::encode(self.0))
    }
}

impl FromStr for PubkeyHex {
    type Err = HexParseError;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let bytes = parse_hex_fixed::<48>(s)?;
        Ok(Self(bytes))
    }
}

impl Serialize for PubkeyHex {
    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
        s.collect_str(self)
    }
}

impl<'de> Deserialize<'de> for PubkeyHex {
    fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
        String::deserialize(d)?
            .parse()
            .map_err(serde::de::Error::custom)
    }
}

/// A 96-byte BLS12-381 G2 compressed signature.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct SignatureHex(
    /// Raw 96-byte compressed G2 element.
    pub [u8; 96],
);

impl SignatureHex {
    /// Construct from a raw 96-byte array.
    pub const fn new(bytes: [u8; 96]) -> Self {
        Self(bytes)
    }

    /// Borrow the underlying 96 bytes.
    pub fn as_bytes(&self) -> &[u8; 96] {
        &self.0
    }
}

impl fmt::Display for SignatureHex {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "0x{}", hex::encode(self.0))
    }
}

impl FromStr for SignatureHex {
    type Err = HexParseError;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let bytes = parse_hex_fixed::<96>(s)?;
        Ok(Self(bytes))
    }
}

impl Serialize for SignatureHex {
    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
        s.collect_str(self)
    }
}

impl<'de> Deserialize<'de> for SignatureHex {
    fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
        String::deserialize(d)?
            .parse()
            .map_err(serde::de::Error::custom)
    }
}

// ===========================================================================
// Scalars
// ===========================================================================

/// A Chia amount in mojos (1 XCH = 10^12 mojos).
///
/// Encoded as a JSON number — safe for amounts up to 2^53 − 1 mojos
/// (~9000 XCH) before float round-trip issues. Larger amounts would need
/// string encoding; not a current concern.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Ord, PartialOrd, Hash, Serialize, Deserialize)]
#[serde(transparent)]
pub struct Amount(
    /// Raw mojo count.
    pub u64,
);

impl Amount {
    /// Zero mojos.
    pub const ZERO: Self = Self(0);
}

// ===========================================================================
// Block / validator summaries
// ===========================================================================

/// Compact metadata for a single L2 block. Returned by `get_block_records`
/// and embedded in larger envelopes like `get_blockchain_state`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BlockSummary {
    /// Block height on the L2 chain.
    pub height: u64,
    /// Canonical block hash.
    pub hash: HashHex,
    /// Parent block hash.
    pub parent_hash: HashHex,
    /// Unix timestamp (seconds) from the proposer's signed header.
    pub timestamp: u64,
    /// Block proposer's BLS public key.
    pub proposer: PubkeyHex,
    /// Number of transactions included.
    pub tx_count: u32,
    /// Cumulative attestation weight.
    pub weight: u64,
}

/// Validator lifecycle state.
///
/// Values match the state machine in
/// [`docs/superpowers/specs/2026-04-20-validator-lifecycle-checkpoint-gated-design.md`](https://github.com/DIG-Network/dig-network/tree/main/docs)
/// and pair with the [`ValidatorSummary`] struct below.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum ValidatorStatus {
    /// Validator has an L1 registration coin but is not yet in the VMR.
    PendingRegister,
    /// Validator is in the current checkpoint's VMR and may sign.
    Active,
    /// Validator submitted a voluntary-exit signal; waiting for next checkpoint.
    ExitingVoluntary,
    /// Validator force-exited by L2 (inactivity / slashing / governance).
    ExitingForced,
    /// Validator's exit was committed to an exit-ledger leaf.
    Exited,
    /// Registration coin was spent to a withdraw-delay coin; waiting for delay.
    WithdrawalPending,
    /// Withdraw-delay coin was released; collateral paid out.
    Withdrawn,
}

/// Summary record for a single validator, returned by `get_validator` /
/// `get_active_validators`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ValidatorSummary {
    /// BLS12-381 G1 public key — the canonical validator identifier.
    pub pubkey: PubkeyHex,
    /// Current lifecycle state.
    pub status: ValidatorStatus,
    /// Leaf index in the validator-merkle-root, if active. `None` until activation.
    pub validator_index: Option<u32>,
    /// Effective balance (Ethereum-parity hysteresis). In mojos.
    pub effective_balance: Amount,
    /// Cumulative slashed amount. In mojos.
    pub slashed_amount: Amount,
    /// Epoch in which activation committed. `None` if not yet active.
    pub activation_epoch: Option<u64>,
    /// Epoch in which exit committed. `None` if not yet exiting.
    pub exit_epoch: Option<u64>,
}

// ===========================================================================
// Hex parsing helper
// ===========================================================================

/// Errors from parsing a hex string into a fixed-size byte array.
#[derive(Debug, thiserror::Error)]
pub enum HexParseError {
    /// The hex string (after stripping `0x`) had the wrong length.
    #[error(
        "wrong hex length: expected {expected} bytes ({expected_hex_chars} hex chars), got {got}"
    )]
    WrongLength {
        /// Required byte length.
        expected: usize,
        /// Required hex-char length (`expected * 2`).
        expected_hex_chars: usize,
        /// Actual hex-char length observed.
        got: usize,
    },
    /// The hex string contained a non-hex character.
    #[error("invalid hex: {0}")]
    InvalidHex(#[from] hex::FromHexError),
}

fn parse_hex_fixed<const N: usize>(s: &str) -> Result<[u8; N], HexParseError> {
    let stripped = s
        .strip_prefix("0x")
        .or_else(|| s.strip_prefix("0X"))
        .unwrap_or(s);
    if stripped.len() != N * 2 {
        return Err(HexParseError::WrongLength {
            expected: N,
            expected_hex_chars: N * 2,
            got: stripped.len(),
        });
    }
    let mut out = [0u8; N];
    hex::decode_to_slice(stripped, &mut out)?;
    Ok(out)
}

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

    /// **Proves:** a 32-byte `HashHex` serializes as `"0x"` + 64 lowercase
    /// hex chars.
    ///
    /// **Why it matters:** External tooling (explorers, dashboards,
    /// light-clients) identifies coins and blocks by this exact string
    /// form. Any case change or prefix drop would break equality checks
    /// across the ecosystem.
    ///
    /// **Catches:** a regression where `Display` uses uppercase (`{:X}`),
    /// or drops the `0x` prefix.
    #[test]
    fn hash_hex_display() {
        let h = HashHex::new([0xAB; 32]);
        let s = h.to_string();
        assert_eq!(s.len(), 2 + 64);
        assert!(s.starts_with("0x"));
        assert_eq!(s, format!("0x{}", "ab".repeat(32)));
    }

    /// **Proves:** `HashHex::from_str` accepts `0x`-prefixed lowercase,
    /// `0x`-prefixed uppercase, bare lowercase, and mixed case.
    ///
    /// **Why it matters:** JSON ecosystems are inconsistent about hex case
    /// — Rust tends to emit lowercase, JavaScript and Java often emit
    /// mixed. Accepting all forms at deserialize time makes the RPC
    /// resilient to client-library quirks.
    ///
    /// **Catches:** a regression that tightens parsing to one canonical
    /// form, silently breaking some clients.
    #[test]
    fn hash_hex_parse_accepts_case_and_prefix_variations() {
        let want = HashHex::new([0xAB; 32]);

        let inputs = [
            format!("0x{}", "ab".repeat(32)),
            format!("0X{}", "AB".repeat(32)),
            "ab".repeat(32),
            "AB".repeat(32),
        ];

        for s in inputs {
            let parsed: HashHex = s.parse().expect(&s);
            assert_eq!(parsed, want, "parse of {s:?} mismatched");
        }
    }

    /// **Proves:** parsing a hex string of the wrong length (62 chars
    /// instead of 64) returns [`HexParseError::WrongLength`].
    ///
    /// **Why it matters:** Hex-length checks catch truncated values early.
    /// Without this, a shortened hash silently rounded up to 32 bytes
    /// would produce wrong-but-valid-looking coin IDs.
    ///
    /// **Catches:** removing the length check; using `decode` (which ignores
    /// truncation) instead of `decode_to_slice`.
    #[test]
    fn hash_hex_parse_rejects_wrong_length() {
        let short = format!("0x{}", "a".repeat(62));
        let err = short.parse::<HashHex>().unwrap_err();
        assert!(matches!(err, HexParseError::WrongLength { .. }));
    }

    /// **Proves:** `HashHex` and its siblings round-trip through serde JSON
    /// unchanged.
    ///
    /// **Why it matters:** This is the actual wire exercise — serialize to
    /// JSON and deserialize back, checking bit-exact equality.
    ///
    /// **Catches:** a regression where `Serialize`/`Deserialize` impls drift
    /// out of sync (e.g., serializer uses lowercase but deserializer
    /// requires `0x` prefix that the serializer emits).
    #[test]
    fn fixed_hex_types_roundtrip_via_serde() {
        let h = HashHex::new([1u8; 32]);
        let j = serde_json::to_string(&h).unwrap();
        let back: HashHex = serde_json::from_str(&j).unwrap();
        assert_eq!(h, back);

        let p = PubkeyHex::new([2u8; 48]);
        let j = serde_json::to_string(&p).unwrap();
        let back: PubkeyHex = serde_json::from_str(&j).unwrap();
        assert_eq!(p, back);

        let s = SignatureHex::new([3u8; 96]);
        let j = serde_json::to_string(&s).unwrap();
        let back: SignatureHex = serde_json::from_str(&j).unwrap();
        assert_eq!(s, back);
    }

    /// **Proves:** `Amount` serializes as a bare number (transparent
    /// `u64`), not as an object.
    ///
    /// **Why it matters:** An `Amount` of 42 should serialize as `42`, not
    /// `{"0": 42}`. The `#[serde(transparent)]` attribute pins this.
    ///
    /// **Catches:** dropping `#[serde(transparent)]` — which would produce
    /// object form and break every client that expects a bare number.
    #[test]
    fn amount_transparent_serde() {
        let a = Amount(42);
        let s = serde_json::to_string(&a).unwrap();
        assert_eq!(s, "42");
    }

    /// **Proves:** `ValidatorStatus` serializes in snake_case — e.g.,
    /// `"pending_register"`, not `"PendingRegister"`.
    ///
    /// **Why it matters:** JSON conventions favour snake_case for enum
    /// variants; the rest of the crate's types already follow this. Clients
    /// will pattern-match on the exact string.
    ///
    /// **Catches:** a regression that drops `#[serde(rename_all = "snake_case")]`.
    #[test]
    fn validator_status_serialises_snake_case() {
        let s = serde_json::to_string(&ValidatorStatus::PendingRegister).unwrap();
        assert_eq!(s, "\"pending_register\"");

        let s = serde_json::to_string(&ValidatorStatus::WithdrawalPending).unwrap();
        assert_eq!(s, "\"withdrawal_pending\"");
    }

    /// **Proves:** `BlockSummary` + `ValidatorSummary` round-trip through
    /// JSON unchanged when populated with realistic values.
    ///
    /// **Why it matters:** These are the two most-referenced domain types.
    /// If they drift (a field renamed, dropped, or re-typed) every method
    /// that returns them breaks in lockstep.
    ///
    /// **Catches:** accidentally making a field `serde(skip)` that clients
    /// depend on; reordering tuple-like struct fields (which would break
    /// wire form even though compilation succeeds).
    #[test]
    fn summaries_roundtrip() {
        let b = BlockSummary {
            height: 123,
            hash: HashHex::new([1u8; 32]),
            parent_hash: HashHex::new([0u8; 32]),
            timestamp: 1_700_000_000,
            proposer: PubkeyHex::new([9u8; 48]),
            tx_count: 7,
            weight: 10_000,
        };
        let j = serde_json::to_string(&b).unwrap();
        let back: BlockSummary = serde_json::from_str(&j).unwrap();
        assert_eq!(b.height, back.height);
        assert_eq!(b.hash, back.hash);

        let v = ValidatorSummary {
            pubkey: PubkeyHex::new([5u8; 48]),
            status: ValidatorStatus::Active,
            validator_index: Some(42),
            effective_balance: Amount(32_000_000_000_000),
            slashed_amount: Amount::ZERO,
            activation_epoch: Some(7),
            exit_epoch: None,
        };
        let j = serde_json::to_string(&v).unwrap();
        let back: ValidatorSummary = serde_json::from_str(&j).unwrap();
        assert_eq!(back.pubkey, v.pubkey);
        assert_eq!(back.status, v.status);
    }
}