zanolib 0.3.0

Zano wallet library: address handling, transaction parsing/signing, deposit scanning and threshold (MPC) signing.
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
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
//! Zano addresses: the base58-chunked encoding and the address types.

use crate::base::varint::{append_varint, take_varint};
use crate::error::{Error, Result};
use purecrypto::hash::keccak256;

/// The Bitcoin base58 alphabet, as used by Zano.
const ALPHABET: &[u8; 58] = b"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";

/// Encoded length of a chunk of `i` raw bytes.
const ENCODED_BLOCK_SIZES: [usize; 9] = [0, 2, 3, 5, 6, 7, 9, 10, 11];
/// Raw length of a chunk of `i` encoded characters, or `None` if impossible.
const DECODED_BLOCK_SIZES: [i8; 12] = [0, -1, 1, 2, -1, 3, 4, 5, -1, 6, 7, 8];
const FULL_BLOCK_SIZE: usize = 8;
const FULL_ENCODED_SIZE: usize = 11;

fn encode_block(block: &[u8], out: &mut String) {
    let size = block.len();
    assert!(
        (1..=FULL_BLOCK_SIZE).contains(&size),
        "invalid block length"
    );
    let mut num: u64 = 0;
    for b in block {
        num = (num << 8) | *b as u64;
    }
    let encoded_len = ENCODED_BLOCK_SIZES[size];
    let mut res = vec![ALPHABET[0]; encoded_len];
    let mut i = encoded_len;
    while num > 0 && i > 0 {
        i -= 1;
        res[i] = ALPHABET[(num % 58) as usize];
        num /= 58;
    }
    out.push_str(std::str::from_utf8(&res).expect("alphabet is ASCII"));
}

fn decode_digit(c: u8) -> Option<u64> {
    ALPHABET.iter().position(|a| *a == c).map(|v| v as u64)
}

fn decode_block(block: &str, out: &mut Vec<u8>) -> Result<()> {
    let size = block.len();
    if !(1..=FULL_ENCODED_SIZE).contains(&size) {
        return Err(Error::msg("base58: invalid block length"));
    }
    let raw_size = DECODED_BLOCK_SIZES[size];
    if raw_size < 0 {
        return Err(Error::msg("base58: invalid block length"));
    }
    let raw_size = raw_size as usize;

    let mut res_num: u64 = 0;
    for c in block.bytes() {
        if c > 127 {
            return Err(Error::msg("base58: non-ascii character"));
        }
        let idx =
            decode_digit(c).ok_or_else(|| crate::err!("base58: bad digit {:?}", c as char))?;
        if res_num > (u64::MAX - idx) / 58 {
            return Err(Error::msg("base58: overflow"));
        }
        res_num = res_num * 58 + idx;
    }
    if raw_size < 8 && res_num >= (1u64 << (raw_size * 8)) {
        return Err(Error::msg("base58: overflow"));
    }
    for n in (0..raw_size).rev() {
        out.push(((res_num >> (n * 8)) & 0xff) as u8);
    }
    Ok(())
}

/// Encodes bytes with Zano's chunked base58 (8-byte blocks -> 11 characters).
pub fn base58_encode_chunked(data: &[u8]) -> String {
    let mut out = String::new();
    for block in data.chunks(FULL_BLOCK_SIZE) {
        encode_block(block, &mut out);
    }
    out
}

/// Decodes Zano's chunked base58.
pub fn base58_decode_chunked(encoded: &str) -> Result<Vec<u8>> {
    let mut out = Vec::new();
    if encoded.is_empty() {
        return Ok(out);
    }
    let bytes = encoded.as_bytes();
    let full_blocks = bytes.len() / FULL_ENCODED_SIZE;
    for i in 0..full_blocks {
        let block = &encoded[i * FULL_ENCODED_SIZE..(i + 1) * FULL_ENCODED_SIZE];
        decode_block(block, &mut out)?;
    }
    if !bytes.len().is_multiple_of(FULL_ENCODED_SIZE) {
        decode_block(&encoded[full_blocks * FULL_ENCODED_SIZE..], &mut out)?;
    }
    Ok(out)
}

/// The kind of a Zano address, encoded as a varint prefix.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum AddressType {
    /// `Zx` — standard public address.
    Public,
    /// `iZ` — integrated address with a payment id.
    IntegratedV1,
    /// `iZ` — integrated address, v2 (carries flags).
    IntegratedV2,
    /// `aZx` — auditable public address.
    Audit,
    /// `aiZX` — auditable integrated address.
    AuditIntegrated,
    /// `gwZ` — gateway address (HF6).
    Gateway,
    /// `gwiZ` — gateway address with a payment id (HF6).
    GatewayIntegrated,
    /// Any other prefix, preserved verbatim.
    Unknown(u64),
}

impl AddressType {
    /// The numeric prefix.
    pub fn prefix(&self) -> u64 {
        match self {
            AddressType::Public => 0xc5,
            AddressType::IntegratedV1 => 0x3678,
            AddressType::IntegratedV2 => 0x36f8,
            AddressType::Audit => 0x98c8,
            AddressType::AuditIntegrated => 0x8a49,
            AddressType::Gateway => 0x656e,
            AddressType::GatewayIntegrated => 0x14276e,
            AddressType::Unknown(v) => *v,
        }
    }

    /// Builds a type from its numeric prefix.
    pub fn from_prefix(v: u64) -> AddressType {
        match v {
            0xc5 => AddressType::Public,
            0x3678 => AddressType::IntegratedV1,
            0x36f8 => AddressType::IntegratedV2,
            0x98c8 => AddressType::Audit,
            0x8a49 => AddressType::AuditIntegrated,
            0x656e => AddressType::Gateway,
            0x14276e => AddressType::GatewayIntegrated,
            other => AddressType::Unknown(other),
        }
    }

    /// Whether this is an auditable address.
    pub fn auditable(&self) -> bool {
        matches!(self, AddressType::Audit | AddressType::AuditIntegrated)
    }

    /// Whether this is a gateway address, which names a gateway address id
    /// rather than a spend/view key pair.
    pub fn is_gateway(&self) -> bool {
        matches!(self, AddressType::Gateway | AddressType::GatewayIntegrated)
    }

    /// Whether the encoding carries a flags byte.
    pub fn has_flags(&self) -> bool {
        matches!(
            self,
            AddressType::IntegratedV2 | AddressType::Audit | AddressType::AuditIntegrated
        )
    }
}

impl std::fmt::Display for AddressType {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            AddressType::Public => f.write_str("Public Address (Zx)"),
            AddressType::IntegratedV1 => f.write_str("Integrated Address (iZ)"),
            AddressType::IntegratedV2 => f.write_str("Integrated Address V2 (iZ)"),
            AddressType::Audit => f.write_str("Audit Address (aZx)"),
            AddressType::AuditIntegrated => f.write_str("Audit Integrated Address (aiZX)"),
            AddressType::Gateway => f.write_str("Gateway Address (gwZ)"),
            AddressType::GatewayIntegrated => f.write_str("Integrated Gateway Address (gwiZ)"),
            AddressType::Unknown(v) => write!(f, "Unknown Address type ({v:x})"),
        }
    }
}

/// `CURRENCY_HF6_INTRINSIC_PAYMENT_ID_SIZE`: the largest payment id that fits
/// an output's `encrypted_payment_id`.
pub const CURRENCY_HF6_INTRINSIC_PAYMENT_ID_SIZE: usize = 8;

/// Converts a payment id to its intrinsic (per-output) form, as zano's
/// `convert_payment_id` does: left-pad with zeros to 8 bytes and read as a
/// little-endian integer. An empty payment id converts to 0.
pub fn payment_id_to_intrinsic(payment_id: &[u8]) -> Result<u64> {
    if payment_id.len() > CURRENCY_HF6_INTRINSIC_PAYMENT_ID_SIZE {
        return Err(crate::err!(
            "payment id is {} bytes, at most {CURRENCY_HF6_INTRINSIC_PAYMENT_ID_SIZE} fit in an output",
            payment_id.len()
        ));
    }
    let mut buf = [0u8; 8];
    buf[8 - payment_id.len()..].copy_from_slice(payment_id);
    Ok(u64::from_le_bytes(buf))
}

/// The inverse of [`payment_id_to_intrinsic`]: the 8 little-endian bytes of a
/// non-zero intrinsic payment id, or an empty payment id for 0.
///
/// A payment id shorter than 8 bytes comes back left-padded with zeros, as it
/// does from zano.
pub fn payment_id_from_intrinsic(intrinsic: u64) -> Vec<u8> {
    if intrinsic == 0 {
        return Vec::new();
    }
    intrinsic.to_le_bytes().to_vec()
}

/// A parsed Zano address.
///
/// For a gateway address ([`AddressType::is_gateway`]) `spend_key` holds the
/// 32-byte gateway address id, `view_key` is empty and `payment_id`, if any,
/// is the 8 little-endian bytes of its intrinsic payment id.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Address {
    /// The address type.
    pub typ: AddressType,
    /// Address flags (bit 0 = auditable).
    pub flags: u8,
    /// Public spend key (32 bytes), or the gateway address id.
    pub spend_key: Vec<u8>,
    /// Public view key (32 bytes); empty for gateway addresses.
    pub view_key: Vec<u8>,
    /// Integrated payment id, if any.
    pub payment_id: Vec<u8>,
}

impl Address {
    /// Parses a base58 Zano address, verifying its checksum.
    pub fn parse(addr: &str) -> Result<Address> {
        let payload = base58_decode_chunked(addr)?;
        if payload.len() < 4 + 1 {
            return Err(Error::msg("address is too short"));
        }
        let (body, cksum) = payload.split_at(payload.len() - 4);
        if keccak256(body)[..4] != *cksum {
            return Err(Error::msg("invalid checksum in address"));
        }

        let (typ_prefix, rest) = take_varint(body)?;
        let typ = AddressType::from_prefix(typ_prefix);
        if typ.is_gateway() {
            return Address::parse_gateway(typ, rest);
        }
        if rest.len() < 64 {
            return Err(Error::msg("address is too short"));
        }
        let mut res = Address {
            typ,
            flags: 0,
            spend_key: rest[..32].to_vec(),
            view_key: rest[32..64].to_vec(),
            payment_id: rest[64..].to_vec(),
        };
        if typ.has_flags() {
            if res.payment_id.is_empty() {
                return Err(Error::msg("address is too short while reading flags"));
            }
            res.flags = res.payment_id.remove(0);
        } else if typ == AddressType::Public && !res.payment_id.is_empty() {
            // A public address carries no payment id, so trailing data is flags.
            res.flags = res.payment_id.remove(0);
        }
        Ok(res)
    }

    /// Parses the body of a gateway address (`gateway_address_serialized_to_str`):
    /// a version, the gateway address id and an optional 64-bit payment id.
    fn parse_gateway(typ: AddressType, body: &[u8]) -> Result<Address> {
        let (version, rest) = take_varint(body)?;
        if version != 0 {
            return Err(crate::err!("unsupported gateway address version {version}"));
        }
        if rest.len() < 32 + 1 {
            return Err(Error::msg("gateway address is too short"));
        }
        let (id, rest) = rest.split_at(32);
        // boost::optional: an "is none" flag, then the value if present.
        let payment_id = match rest {
            [1] => Vec::new(),
            [0, pid @ ..] if pid.len() == 8 => pid.to_vec(),
            _ => return Err(Error::msg("malformed gateway address payment id")),
        };
        if (typ == AddressType::GatewayIntegrated) == payment_id.is_empty() {
            return Err(Error::msg(
                "gateway address type does not match its payment id",
            ));
        }
        Ok(Address {
            typ,
            flags: 0,
            spend_key: id.to_vec(),
            view_key: Vec::new(),
            payment_id,
        })
    }

    /// The gateway address id, for a gateway address.
    pub fn gateway_id(&self) -> Option<crate::base::Value256> {
        if !self.typ.is_gateway() {
            return None;
        }
        let id: [u8; 32] = self.spend_key.as_slice().try_into().ok()?;
        Some(crate::base::Value256(id))
    }

    /// Sets (or clears, when empty) the integrated payment id, adjusting the
    /// address type accordingly.
    ///
    /// Gateway addresses only take payment ids of up to
    /// [`CURRENCY_HF6_INTRINSIC_PAYMENT_ID_SIZE`] bytes; they are stored as
    /// the 8 little-endian bytes of the intrinsic value, as zano does.
    pub fn set_payment_id(&mut self, payment_id: &[u8]) -> Result<()> {
        if payment_id.len() > 128 {
            return Err(Error::msg("payment id is too long"));
        }
        if payment_id.is_empty() {
            self.payment_id.clear();
            self.typ = match self.typ {
                AddressType::IntegratedV1 | AddressType::IntegratedV2 => AddressType::Public,
                AddressType::AuditIntegrated => AddressType::Audit,
                AddressType::GatewayIntegrated => AddressType::Gateway,
                other => other,
            };
            return Ok(());
        }
        if self.typ.is_gateway() {
            let intrinsic = payment_id_to_intrinsic(payment_id)?;
            self.payment_id = intrinsic.to_le_bytes().to_vec();
            self.typ = AddressType::GatewayIntegrated;
            return Ok(());
        }
        self.payment_id = payment_id.to_vec();
        self.typ = match self.typ {
            AddressType::Public if self.flags != 0 => AddressType::IntegratedV2,
            AddressType::Public => AddressType::IntegratedV1,
            AddressType::Audit => AddressType::AuditIntegrated,
            other => other,
        };
        Ok(())
    }

    /// The integrated payment id as an intrinsic (per-output) payment id, the
    /// form HF6 transactions carry it in; 0 when the address has none.
    ///
    /// Fails for payment ids longer than
    /// [`CURRENCY_HF6_INTRINSIC_PAYMENT_ID_SIZE`] bytes, which only fit the
    /// legacy tx-wide attachment.
    pub fn intrinsic_payment_id(&self) -> Result<u64> {
        payment_id_to_intrinsic(&self.payment_id)
    }

    /// A compact debug rendering of the address' fields.
    pub fn debug_string(&self) -> String {
        format!(
            "type={} spendKey={} viewKey={} flags={:x} paymentId={}",
            self.typ,
            hex::encode(&self.spend_key),
            hex::encode(&self.view_key),
            self.flags,
            hex::encode(&self.payment_id)
        )
    }
}

impl std::fmt::Display for Address {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let mut buf = Vec::new();
        append_varint(&mut buf, self.typ.prefix());
        if self.typ.is_gateway() {
            append_varint(&mut buf, 0); // gateway_address_serialized_to_str version
            buf.extend_from_slice(&self.spend_key);
            if self.payment_id.is_empty() {
                buf.push(1); // optional payment id: none
            } else {
                buf.push(0);
                let pid = payment_id_to_intrinsic(&self.payment_id).map_err(|_| std::fmt::Error)?;
                buf.extend_from_slice(&pid.to_le_bytes());
            }
            let cksum = keccak256(&buf);
            buf.extend_from_slice(&cksum[..4]);
            return f.write_str(&base58_encode_chunked(&buf));
        }
        buf.extend_from_slice(&self.spend_key);
        buf.extend_from_slice(&self.view_key);
        match self.typ {
            AddressType::Public => {
                // No payment id here, so any extra data means flags.
                if self.flags != 0 {
                    buf.push(self.flags);
                }
            }
            _ => {
                if self.typ.has_flags() {
                    buf.push(self.flags);
                }
                buf.extend_from_slice(&self.payment_id);
            }
        }
        let cksum = keccak256(&buf);
        buf.extend_from_slice(&cksum[..4]);
        f.write_str(&base58_encode_chunked(&buf))
    }
}

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

    #[test]
    fn base58_block_sizes() {
        // 8 raw bytes always encode to 11 characters.
        assert_eq!(base58_encode_chunked(&[0u8; 8]).len(), 11);
        assert_eq!(base58_encode_chunked(&[0xff; 8]).len(), 11);
        // Partial blocks use the size table.
        for (raw, enc) in [
            (1usize, 2usize),
            (2, 3),
            (3, 5),
            (4, 6),
            (5, 7),
            (6, 9),
            (7, 10),
        ] {
            assert_eq!(base58_encode_chunked(&vec![0xab; raw]).len(), enc);
        }
    }

    #[test]
    fn base58_round_trip() {
        for len in 1..40usize {
            let data: Vec<u8> = (0..len).map(|i| (i as u8).wrapping_mul(37)).collect();
            let enc = base58_encode_chunked(&data);
            assert_eq!(base58_decode_chunked(&enc).unwrap(), data, "len {len}");
        }
    }

    /// The vectors from the Go `TestAddressParse`, covering every address type.
    const VECTORS: &[(&str, &str, &str, &str, u8)] = &[
        (
            "ZxD5aoLDPTdcaRx4uCpyW4XiLfEXejepAVz8cSY2fwHNEiJNu6NmpBBDLGTJzCsUvn3acCVDVDPMV8yQXdPooAp338Se7AxeH",
            "9f5e1fa93630d4b281b18bb67a3db79e9622fc703cc3ad4a453a82e0a36d51fa",
            "a3f208c8f9ba49bab28eed62b35b0f6be0a297bcd85c2faa1eb1820527bcf7e3",
            "",
            0,
        ),
        (
            "iZ2Zi6RmTWwcaRx4uCpyW4XiLfEXejepAVz8cSY2fwHNEiJNu6NmpBBDLGTJzCsUvn3acCVDVDPMV8yQXdPooAp3iTqEsjvJoco1aLSZXS6T",
            "9f5e1fa93630d4b281b18bb67a3db79e9622fc703cc3ad4a453a82e0a36d51fa",
            "a3f208c8f9ba49bab28eed62b35b0f6be0a297bcd85c2faa1eb1820527bcf7e3",
            "87440d0b9acc42f1",
            0,
        ),
        (
            "ZxD5aoLDPTdcaRx4uCpyW4XiLfEXejepAVz8cSY2fwHNEiJNu6NmpBBDLGTJzCsUvn3acCVDVDPMV8yQXdPooAp3APrDvRoL5C",
            "9f5e1fa93630d4b281b18bb67a3db79e9622fc703cc3ad4a453a82e0a36d51fa",
            "a3f208c8f9ba49bab28eed62b35b0f6be0a297bcd85c2faa1eb1820527bcf7e3",
            "",
            0xfe,
        ),
        (
            "iZ4mBxubNfqcaRx4uCpyW4XiLfEXejepAVz8cSY2fwHNEiJNu6NmpBBDLGTJzCsUvn3acCVDVDPMV8yQXdPooAp3iTrG7nU5rRCWmcozLaMoY95sAbo6",
            "9f5e1fa93630d4b281b18bb67a3db79e9622fc703cc3ad4a453a82e0a36d51fa",
            "a3f208c8f9ba49bab28eed62b35b0f6be0a297bcd85c2faa1eb1820527bcf7e3",
            "3ba0527bcfb1fa93630d28eed6",
            0xfe,
        ),
        (
            "aZxb9Et6FhP9AinRwcPqSqBKjckre7PgoZjK3q5YG2fUKHYWFZMWjB6YAEAdw4yDDUGEQ7CGEgbqhGRKeadGV1jLYcEJMEmqQFn",
            "9f5e1fa93630d4b281b18bb67a3db79e9622fc703cc3ad4a453a82e0a36d51fa",
            "a3f208c8f9ba49bab28eed62b35b0f6be0a297bcd85c2faa1eb1820527bcf7e3",
            "",
            0x01,
        ),
        (
            "aiZXDondHWu9AinRwcPqSqBKjckre7PgoZjK3q5YG2fUKHYWFZMWjB6YAEAdw4yDDUGEQ7CGEgbqhGRKeadGV1jLYcEJM9xJH8EbjuRiMJgFmPRATsEV9",
            "9f5e1fa93630d4b281b18bb67a3db79e9622fc703cc3ad4a453a82e0a36d51fa",
            "a3f208c8f9ba49bab28eed62b35b0f6be0a297bcd85c2faa1eb1820527bcf7e3",
            "3ba0527bcfb1fa93630d28eed6",
            0x01,
        ),
    ];

    #[test]
    fn known_addresses_parse_and_reencode() {
        for (addr_str, spend, view, pid, flags) in VECTORS {
            // The base58 layer must round-trip on its own.
            let raw = base58_decode_chunked(addr_str).unwrap();
            assert_eq!(&base58_encode_chunked(&raw), addr_str);

            let addr = Address::parse(addr_str).unwrap_or_else(|e| panic!("{addr_str}: {e}"));
            assert_eq!(hex::encode(&addr.spend_key), *spend);
            assert_eq!(hex::encode(&addr.view_key), *view);
            assert_eq!(hex::encode(&addr.payment_id), *pid);
            assert_eq!(addr.flags, *flags);
            assert_eq!(&addr.to_string(), addr_str);
        }
    }

    #[test]
    fn address_types_are_recognized() {
        assert_eq!(
            Address::parse(VECTORS[0].0).unwrap().typ,
            AddressType::Public
        );
        assert_eq!(
            Address::parse(VECTORS[1].0).unwrap().typ,
            AddressType::IntegratedV1
        );
        assert_eq!(
            Address::parse(VECTORS[3].0).unwrap().typ,
            AddressType::IntegratedV2
        );
        assert_eq!(
            Address::parse(VECTORS[4].0).unwrap().typ,
            AddressType::Audit
        );
        assert_eq!(
            Address::parse(VECTORS[5].0).unwrap().typ,
            AddressType::AuditIntegrated
        );
    }

    #[test]
    fn set_payment_id_switches_type() {
        let mut addr = Address::parse(VECTORS[0].0).unwrap();
        assert_eq!(addr.typ, AddressType::Public);
        addr.set_payment_id(&[1, 2, 3, 4]).unwrap();
        assert_eq!(addr.typ, AddressType::IntegratedV1);
        let parsed = Address::parse(&addr.to_string()).unwrap();
        assert_eq!(parsed.payment_id, vec![1, 2, 3, 4]);
        addr.set_payment_id(&[]).unwrap();
        assert_eq!(addr.typ, AddressType::Public);
        assert!(addr.set_payment_id(&[0u8; 129]).is_err());
    }

    #[test]
    fn invalid_address_is_rejected() {
        assert!(Address::parse("invalid").is_err());
        assert!(Address::parse("").is_err());
    }

    #[test]
    fn address_round_trip() {
        let addr = Address {
            typ: AddressType::Public,
            flags: 0,
            spend_key: vec![1u8; 32],
            view_key: vec![2u8; 32],
            payment_id: Vec::new(),
        };
        let s = addr.to_string();
        assert!(s.starts_with("Zx"), "unexpected prefix in {s}");
        assert_eq!(Address::parse(&s).unwrap(), addr);
    }

    #[test]
    fn integrated_address_round_trip() {
        let mut addr = Address {
            typ: AddressType::Public,
            flags: 0,
            spend_key: vec![3u8; 32],
            view_key: vec![4u8; 32],
            payment_id: Vec::new(),
        };
        addr.set_payment_id(b"payment-id-1").unwrap();
        assert_eq!(addr.typ, AddressType::IntegratedV1);
        let parsed = Address::parse(&addr.to_string()).unwrap();
        assert_eq!(parsed.payment_id, b"payment-id-1");
        assert_eq!(parsed.spend_key, vec![3u8; 32]);
    }

    #[test]
    fn auditable_address_keeps_flags() {
        let addr = Address {
            typ: AddressType::Audit,
            flags: 1,
            spend_key: vec![5u8; 32],
            view_key: vec![6u8; 32],
            payment_id: Vec::new(),
        };
        let parsed = Address::parse(&addr.to_string()).unwrap();
        assert_eq!(parsed.flags, 1);
        assert_eq!(parsed.typ, AddressType::Audit);
        assert!(parsed.typ.auditable());
    }

    #[test]
    fn gateway_addresses_parse_and_reencode() {
        // The example address from zano's RPC documentation.
        let s = "gwZ5sqZkre33rxhoo9ht5xcmzy5khvr2hFSfvk7TeXeMXxby7acC3fs1D";
        let addr = Address::parse(s).unwrap();
        assert_eq!(addr.typ, AddressType::Gateway);
        assert!(addr.typ.is_gateway());
        assert!(addr.gateway_id().is_some());
        assert!(addr.view_key.is_empty() && addr.payment_id.is_empty());
        assert_eq!(addr.to_string(), s);

        // Adding a payment id makes it an integrated gateway address.
        let mut integ = addr.clone();
        integ.set_payment_id(&[0xaa, 0xbb]).unwrap();
        assert_eq!(integ.typ, AddressType::GatewayIntegrated);
        let encoded = integ.to_string();
        assert!(encoded.starts_with("gwiZ"), "{encoded}");
        let back = Address::parse(&encoded).unwrap();
        assert_eq!(back, integ);
        assert_eq!(back.intrinsic_payment_id().unwrap(), 0xbbaa_0000_0000_0000);
        assert!(integ.clone().set_payment_id(&[0u8; 9]).is_err());

        integ.set_payment_id(&[]).unwrap();
        assert_eq!(integ, addr);
    }

    #[test]
    fn corrupt_checksum_is_rejected() {
        let addr = Address {
            typ: AddressType::Public,
            flags: 0,
            spend_key: vec![1u8; 32],
            view_key: vec![2u8; 32],
            payment_id: Vec::new(),
        };
        let s = addr.to_string();
        let mut chars: Vec<char> = s.chars().collect();
        let last = chars.len() - 1;
        chars[last] = if chars[last] == 'A' { 'B' } else { 'A' };
        let broken: String = chars.into_iter().collect();
        assert!(Address::parse(&broken).is_err());
    }
}