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
// This file was code-generated using an experimental CDDL to rust tool:
// https://github.com/dcSpark/cddl-codegen

use super::*;
use cbor_event::de::Deserializer;
use cbor_event::se::Serializer;
use cbor_event::{self, LenSz};
use cml_core::serialization::fit_sz;
use cml_core::{
    error::{DeserializeError, DeserializeFailure, Key},
    serialization::{CBORReadLen, Deserialize},
};
use cml_crypto::RawBytesEncoding;
use std::io::{BufRead, Seek, SeekFrom, Write};

impl cbor_event::se::Serialize for AddrAttributes {
    fn serialize<'se, W: Write>(
        &self,
        serializer: &'se mut Serializer<W>,
    ) -> cbor_event::Result<&'se mut Serializer<W>> {
        // NOTE: This was manually modified *slightly*
        // The direct cddl-codegen code will always include the stake distribution
        // but the old byron code seems to only put it in when it's not bootstrap.
        serializer.write_map(cbor_event::Len::Len(
            match &self.stake_distribution {
                Some(StakeDistribution::SingleKey(_)) => 1,
                _ => 0,
            } + match &self.derivation_path {
                Some(_) => 1,
                None => 0,
            } + match &self.protocol_magic {
                Some(_) => 1,
                None => 0,
            },
        ))?;
        if let Some(StakeDistribution::SingleKey(_)) = &self.stake_distribution {
            serializer.write_unsigned_integer(0u64)?;
            let mut stake_distribution_inner_se = Serializer::new_vec();
            self.stake_distribution
                .as_ref()
                .unwrap()
                .serialize(&mut stake_distribution_inner_se)?;
            let stake_distribution_bytes = stake_distribution_inner_se.finalize();
            serializer.write_bytes(&stake_distribution_bytes)?;
        }
        if let Some(field) = &self.derivation_path {
            serializer.write_unsigned_integer(1u64)?;
            let mut derivation_path_inner_se = Serializer::new_vec();
            field.serialize(&mut derivation_path_inner_se)?;
            let derivation_path_bytes = derivation_path_inner_se.finalize();
            serializer.write_bytes(&derivation_path_bytes)?;
        }
        if let Some(field) = &self.protocol_magic {
            serializer.write_unsigned_integer(2u64)?;
            let mut protocol_magic_inner_se = Serializer::new_vec();
            field.serialize(&mut protocol_magic_inner_se)?;
            let protocol_magic_bytes = protocol_magic_inner_se.finalize();
            serializer.write_bytes(&protocol_magic_bytes)?;
        }
        Ok(serializer)
    }
}

impl Deserialize for AddrAttributes {
    fn deserialize<R: BufRead + Seek>(raw: &mut Deserializer<R>) -> Result<Self, DeserializeError> {
        let len = raw.map()?;
        let mut read_len = CBORReadLen::from(len);
        (|| -> Result<_, DeserializeError> {
            let mut stake_distribution = None;
            let mut derivation_path = None;
            let mut protocol_magic = None;
            let mut read = 0;
            while match len {
                cbor_event::Len::Len(n) => read < n,
                cbor_event::Len::Indefinite => true,
            } {
                match raw.cbor_type()? {
                    cbor_event::Type::UnsignedInteger => match raw.unsigned_integer()? {
                        0 => {
                            if stake_distribution.is_some() {
                                return Err(DeserializeFailure::DuplicateKey(Key::Uint(0)).into());
                            }
                            stake_distribution = Some(
                                (|| -> Result<_, DeserializeError> {
                                    let stake_distribution_bytes = raw.bytes()?;
                                    let inner_de = &mut Deserializer::from(std::io::Cursor::new(
                                        stake_distribution_bytes,
                                    ));
                                    read_len.read_elems(1)?;
                                    StakeDistribution::deserialize(inner_de)
                                })()
                                .map_err(|e| e.annotate("stake_distribution"))?,
                            );
                        }
                        1 => {
                            if derivation_path.is_some() {
                                return Err(DeserializeFailure::DuplicateKey(Key::Uint(1)).into());
                            }
                            derivation_path = Some(
                                (|| -> Result<_, DeserializeError> {
                                    let derivation_path_bytes = raw.bytes()?;
                                    let inner_de = &mut Deserializer::from(std::io::Cursor::new(
                                        derivation_path_bytes,
                                    ));
                                    read_len.read_elems(1)?;
                                    HDAddressPayload::deserialize(inner_de)
                                })()
                                .map_err(|e| e.annotate("derivation_path"))?,
                            );
                        }
                        2 => {
                            if protocol_magic.is_some() {
                                return Err(DeserializeFailure::DuplicateKey(Key::Uint(2)).into());
                            }
                            protocol_magic = Some(
                                (|| -> Result<_, DeserializeError> {
                                    let protocol_magic_bytes = raw.bytes()?;
                                    let inner_de = &mut Deserializer::from(std::io::Cursor::new(
                                        protocol_magic_bytes,
                                    ));
                                    read_len.read_elems(1)?;
                                    ProtocolMagic::deserialize(inner_de)
                                })()
                                .map_err(|e| e.annotate("protocol_magic"))?,
                            );
                        }
                        unknown_key => {
                            return Err(
                                DeserializeFailure::UnknownKey(Key::Uint(unknown_key)).into()
                            )
                        }
                    },
                    cbor_event::Type::Text => {
                        return Err(DeserializeFailure::UnknownKey(Key::Str(raw.text()?)).into())
                    }
                    cbor_event::Type::Special => match len {
                        cbor_event::Len::Len(_) => {
                            return Err(DeserializeFailure::BreakInDefiniteLen.into())
                        }
                        cbor_event::Len::Indefinite => match raw.special()? {
                            cbor_event::Special::Break => break,
                            _ => return Err(DeserializeFailure::EndingBreakMissing.into()),
                        },
                    },
                    other_type => {
                        return Err(DeserializeFailure::UnexpectedKeyType(other_type).into())
                    }
                }
                read += 1;
            }
            read_len.finish()?;
            Ok(Self {
                stake_distribution,
                derivation_path,
                protocol_magic,
            })
        })()
        .map_err(|e| e.annotate("AddrAttributes"))
    }
}

impl cbor_event::se::Serialize for AddressContent {
    fn serialize<'se, W: Write>(
        &self,
        serializer: &'se mut Serializer<W>,
    ) -> cbor_event::Result<&'se mut Serializer<W>> {
        serializer.write_array(cbor_event::Len::Len(3))?;
        serializer.write_bytes(self.address_id.to_raw_bytes())?;
        self.addr_attributes.serialize(serializer)?;
        match &self.addr_type {
            ByronAddrType::PublicKey => serializer.write_unsigned_integer(0u64),
            ByronAddrType::Script => serializer.write_unsigned_integer(1u64),
            ByronAddrType::Redeem => serializer.write_unsigned_integer(2u64),
        }?;
        Ok(serializer)
    }
}

impl Deserialize for AddressContent {
    fn deserialize<R: BufRead + Seek>(raw: &mut Deserializer<R>) -> Result<Self, DeserializeError> {
        let len = raw.array()?;
        let mut read_len = CBORReadLen::new(match len {
            cbor_event::Len::Len(n) => LenSz::Len(n, fit_sz(n, None, true)),
            cbor_event::Len::Indefinite => LenSz::Indefinite,
        });
        read_len.read_elems(3)?;
        (|| -> Result<_, DeserializeError> {
            let address_id = raw
                .bytes()
                .map_err(Into::<DeserializeError>::into)
                .and_then(|bytes| {
                    AddressId::from_raw_bytes(&bytes)
                        .map_err(|e| DeserializeFailure::InvalidStructure(Box::new(e)).into())
                })
                .map_err(|e: DeserializeError| e.annotate("address_id"))?;
            let addr_attributes = AddrAttributes::deserialize(raw)
                .map_err(|e: DeserializeError| e.annotate("addr_attributes"))?;
            let addr_type = (|| -> Result<_, DeserializeError> {
                let initial_position = raw.as_mut_ref().stream_position().unwrap();
                match (|raw: &mut Deserializer<_>| -> Result<_, DeserializeError> {
                    let public_key_value = raw.unsigned_integer()?;
                    if public_key_value != 0 {
                        return Err(DeserializeFailure::FixedValueMismatch {
                            found: Key::Uint(public_key_value),
                            expected: Key::Uint(0),
                        }
                        .into());
                    }
                    Ok(())
                })(raw)
                {
                    Ok(()) => return Ok(ByronAddrType::PublicKey),
                    Err(_) => raw
                        .as_mut_ref()
                        .seek(SeekFrom::Start(initial_position))
                        .unwrap(),
                };
                match (|raw: &mut Deserializer<_>| -> Result<_, DeserializeError> {
                    let script_value = raw.unsigned_integer()?;
                    if script_value != 1 {
                        return Err(DeserializeFailure::FixedValueMismatch {
                            found: Key::Uint(script_value),
                            expected: Key::Uint(1),
                        }
                        .into());
                    }
                    Ok(())
                })(raw)
                {
                    Ok(()) => return Ok(ByronAddrType::Script),
                    Err(_) => raw
                        .as_mut_ref()
                        .seek(SeekFrom::Start(initial_position))
                        .unwrap(),
                };
                match (|raw: &mut Deserializer<_>| -> Result<_, DeserializeError> {
                    let redeem_value = raw.unsigned_integer()?;
                    if redeem_value != 2 {
                        return Err(DeserializeFailure::FixedValueMismatch {
                            found: Key::Uint(redeem_value),
                            expected: Key::Uint(2),
                        }
                        .into());
                    }
                    Ok(())
                })(raw)
                {
                    Ok(()) => return Ok(ByronAddrType::Redeem),
                    Err(_) => raw
                        .as_mut_ref()
                        .seek(SeekFrom::Start(initial_position))
                        .unwrap(),
                };
                Err(DeserializeError::new(
                    "ByronAddrType",
                    DeserializeFailure::NoVariantMatched,
                ))
            })()
            .map_err(|e| e.annotate("addr_type"))?;
            match len {
                cbor_event::Len::Len(_) => (),
                cbor_event::Len::Indefinite => match raw.special()? {
                    cbor_event::Special::Break => (),
                    _ => return Err(DeserializeFailure::EndingBreakMissing.into()),
                },
            }
            Ok(AddressContent {
                address_id,
                addr_attributes,
                addr_type,
            })
        })()
        .map_err(|e| e.annotate("AddressContent"))
    }
}

impl cbor_event::se::Serialize for ByronAddress {
    fn serialize<'se, W: Write>(
        &self,
        serializer: &'se mut Serializer<W>,
    ) -> cbor_event::Result<&'se mut Serializer<W>> {
        serializer.write_array(cbor_event::Len::Len(2))?;
        serializer.write_tag(24u64)?;
        let mut content_inner_se = Serializer::new_vec();
        self.content.serialize(&mut content_inner_se)?;
        let content_bytes = content_inner_se.finalize();
        serializer.write_bytes(&content_bytes)?;
        self.crc.serialize(serializer)?;
        Ok(serializer)
    }
}

impl Deserialize for ByronAddress {
    fn deserialize<R: BufRead + Seek>(raw: &mut Deserializer<R>) -> Result<Self, DeserializeError> {
        let len = raw.array()?;
        let mut read_len = CBORReadLen::from(len);
        read_len.read_elems(2)?;
        (|| -> Result<_, DeserializeError> {
            let (content, content_crc) = (|| -> Result<_, DeserializeError> {
                match raw.tag()? {
                    24 => {
                        let content_bytes = raw.bytes()?;
                        let crc = crate::byron::crc32::crc32(&content_bytes);
                        let inner_de = &mut Deserializer::from(std::io::Cursor::new(content_bytes));
                        Ok((AddressContent::deserialize(inner_de)?, crc))
                    }
                    tag => Err(DeserializeFailure::TagMismatch {
                        found: tag,
                        expected: 24,
                    }
                    .into()),
                }
            })()
            .map_err(|e| e.annotate("content"))?;
            let crc = Crc32::deserialize(raw).map_err(|e: DeserializeError| e.annotate("crc"))?;
            if Into::<u32>::into(crc) != content_crc {
                return Err(DeserializeFailure::InvalidStructure(Box::new(
                    ByronAddressError::InvalidCRC {
                        found: crc,
                        expected: content_crc.into(),
                    },
                ))
                .into());
            }
            match len {
                cbor_event::Len::Len(_) => (),
                cbor_event::Len::Indefinite => match raw.special()? {
                    cbor_event::Special::Break => (),
                    _ => return Err(DeserializeFailure::EndingBreakMissing.into()),
                },
            }
            Ok(ByronAddress { content, crc })
        })()
        .map_err(|e| e.annotate("ByronAddress"))
    }
}

impl cbor_event::se::Serialize for ByronTxOut {
    fn serialize<'se, W: Write>(
        &self,
        serializer: &'se mut Serializer<W>,
    ) -> cbor_event::Result<&'se mut Serializer<W>> {
        serializer.write_array(cbor_event::Len::Len(2))?;
        self.address.serialize(serializer)?;
        serializer.write_unsigned_integer(self.amount)?;
        Ok(serializer)
    }
}

impl Deserialize for ByronTxOut {
    fn deserialize<R: BufRead + Seek>(raw: &mut Deserializer<R>) -> Result<Self, DeserializeError> {
        let len = raw.array()?;
        let mut read_len = CBORReadLen::from(len);
        read_len.read_elems(2)?;
        (|| -> Result<_, DeserializeError> {
            let address = ByronAddress::deserialize(raw)
                .map_err(|e: DeserializeError| e.annotate("address"))?;
            let amount =
                Ok(raw.unsigned_integer()?).map_err(|e: DeserializeError| e.annotate("amount"))?;
            match len {
                cbor_event::Len::Len(_) => (),
                cbor_event::Len::Indefinite => match raw.special()? {
                    cbor_event::Special::Break => (),
                    _ => return Err(DeserializeFailure::EndingBreakMissing.into()),
                },
            }
            Ok(ByronTxOut { address, amount })
        })()
        .map_err(|e| e.annotate("ByronTxOut"))
    }
}

impl cbor_event::se::Serialize for HDAddressPayload {
    fn serialize<'se, W: Write>(
        &self,
        serializer: &'se mut Serializer<W>,
    ) -> cbor_event::Result<&'se mut Serializer<W>> {
        serializer.write_bytes(&self.0)
    }
}

impl Deserialize for HDAddressPayload {
    fn deserialize<R: BufRead + Seek>(raw: &mut Deserializer<R>) -> Result<Self, DeserializeError> {
        Ok(Self(raw.bytes()? as Vec<u8>))
    }
}

impl cbor_event::se::Serialize for SpendingData {
    fn serialize<'se, W: Write>(
        &self,
        serializer: &'se mut Serializer<W>,
    ) -> cbor_event::Result<&'se mut Serializer<W>> {
        match self {
            SpendingData::SpendingDataPubKey(pubkey) => {
                serializer.write_array(cbor_event::Len::Len(2))?;
                serializer.write_unsigned_integer(0u64)?;
                serializer.write_bytes(pubkey.to_raw_bytes())?;
                Ok(serializer)
            }
            SpendingData::SpendingDataScript(script) => {
                serializer.write_array(cbor_event::Len::Len(2))?;
                serializer.write_unsigned_integer(1u64)?;
                serializer.write_bytes(script.to_raw_bytes())?;
                Ok(serializer)
            }
            SpendingData::SpendingDataRedeem(redeem) => {
                serializer.write_array(cbor_event::Len::Len(2))?;
                serializer.write_unsigned_integer(2u64)?;
                serializer.write_bytes(redeem.to_raw_bytes())?;
                Ok(serializer)
            }
        }
    }
}

impl Deserialize for SpendingData {
    fn deserialize<R: BufRead + Seek>(raw: &mut Deserializer<R>) -> Result<Self, DeserializeError> {
        (|| -> Result<_, DeserializeError> {
            let len = raw.array()?;
            let _read_len = CBORReadLen::from(len);
            let initial_position = raw.as_mut_ref().stream_position().unwrap();
            match (|raw: &mut Deserializer<_>| -> Result<_, DeserializeError> {
                (|| -> Result<_, DeserializeError> {
                    let tag_value = raw.unsigned_integer()?;
                    if tag_value != 0 {
                        return Err(DeserializeFailure::FixedValueMismatch {
                            found: Key::Uint(tag_value),
                            expected: Key::Uint(0),
                        }
                        .into());
                    }
                    Ok(())
                })()
                .map_err(|e| e.annotate("tag"))?;
                let pubkey = raw
                    .bytes()
                    .map_err(Into::<DeserializeError>::into)
                    .and_then(|bytes| {
                        Bip32PublicKey::from_raw_bytes(&bytes)
                            .map_err(|e| DeserializeFailure::InvalidStructure(Box::new(e)).into())
                    })
                    .map_err(|e: DeserializeError| e.annotate("pubkey"))?;
                match len {
                    cbor_event::Len::Len(_) => (),
                    cbor_event::Len::Indefinite => match raw.special()? {
                        cbor_event::Special::Break => (),
                        _ => return Err(DeserializeFailure::EndingBreakMissing.into()),
                    },
                }
                Ok(Self::SpendingDataPubKey(pubkey))
            })(raw)
            {
                Ok(variant) => return Ok(variant),
                Err(_) => raw
                    .as_mut_ref()
                    .seek(SeekFrom::Start(initial_position))
                    .unwrap(),
            };
            match (|raw: &mut Deserializer<_>| -> Result<_, DeserializeError> {
                (|| -> Result<_, DeserializeError> {
                    let tag_value = raw.unsigned_integer()?;
                    if tag_value != 1 {
                        return Err(DeserializeFailure::FixedValueMismatch {
                            found: Key::Uint(tag_value),
                            expected: Key::Uint(1),
                        }
                        .into());
                    }
                    Ok(())
                })()
                .map_err(|e| e.annotate("tag"))?;
                let script = raw
                    .bytes()
                    .map_err(Into::<DeserializeError>::into)
                    .and_then(|bytes| {
                        ByronScript::from_raw_bytes(&bytes)
                            .map_err(|e| DeserializeFailure::InvalidStructure(Box::new(e)).into())
                    })
                    .map_err(|e: DeserializeError| e.annotate("script"))?;
                match len {
                    cbor_event::Len::Len(_) => (),
                    cbor_event::Len::Indefinite => match raw.special()? {
                        cbor_event::Special::Break => (),
                        _ => return Err(DeserializeFailure::EndingBreakMissing.into()),
                    },
                }
                Ok(Self::SpendingDataScript(script))
            })(raw)
            {
                Ok(variant) => return Ok(variant),
                Err(_) => raw
                    .as_mut_ref()
                    .seek(SeekFrom::Start(initial_position))
                    .unwrap(),
            };
            match (|raw: &mut Deserializer<_>| -> Result<_, DeserializeError> {
                (|| -> Result<_, DeserializeError> {
                    let tag_value = raw.unsigned_integer()?;
                    if tag_value != 2 {
                        return Err(DeserializeFailure::FixedValueMismatch {
                            found: Key::Uint(tag_value),
                            expected: Key::Uint(2),
                        }
                        .into());
                    }
                    Ok(())
                })()
                .map_err(|e| e.annotate("tag"))?;
                let redeem = raw
                    .bytes()
                    .map_err(Into::<DeserializeError>::into)
                    .and_then(|bytes| {
                        PublicKey::from_raw_bytes(&bytes)
                            .map_err(|e| DeserializeFailure::InvalidStructure(Box::new(e)).into())
                    })
                    .map_err(|e: DeserializeError| e.annotate("redeem"))?;
                match len {
                    cbor_event::Len::Len(_) => (),
                    cbor_event::Len::Indefinite => match raw.special()? {
                        cbor_event::Special::Break => (),
                        _ => return Err(DeserializeFailure::EndingBreakMissing.into()),
                    },
                }
                Ok(Self::SpendingDataRedeem(redeem))
            })(raw)
            {
                Ok(variant) => return Ok(variant),
                Err(_) => raw
                    .as_mut_ref()
                    .seek(SeekFrom::Start(initial_position))
                    .unwrap(),
            };
            match len {
                cbor_event::Len::Len(_) => (),
                cbor_event::Len::Indefinite => match raw.special()? {
                    cbor_event::Special::Break => (),
                    _ => return Err(DeserializeFailure::EndingBreakMissing.into()),
                },
            }
            Err(DeserializeError::new(
                "SpendingData",
                DeserializeFailure::NoVariantMatched,
            ))
        })()
        .map_err(|e| e.annotate("SpendingData"))
    }
}

impl cbor_event::se::Serialize for StakeDistribution {
    fn serialize<'se, W: Write>(
        &self,
        serializer: &'se mut Serializer<W>,
    ) -> cbor_event::Result<&'se mut Serializer<W>> {
        match self {
            StakeDistribution::SingleKey(stakeholder_id) => {
                serializer.write_array(cbor_event::Len::Len(2))?;
                serializer.write_unsigned_integer(0u64)?;
                serializer.write_bytes(stakeholder_id.to_raw_bytes())?;
                Ok(serializer)
            }
            StakeDistribution::BootstrapEra => {
                serializer.write_array(cbor_event::Len::Len(1))?;
                serializer.write_unsigned_integer(1u64)
            }
        }
    }
}

impl Deserialize for StakeDistribution {
    fn deserialize<R: BufRead + Seek>(raw: &mut Deserializer<R>) -> Result<Self, DeserializeError> {
        (|| -> Result<_, DeserializeError> {
            let len = raw.array()?;
            let _read_len = CBORReadLen::from(len);
            let initial_position = raw.as_mut_ref().stream_position().unwrap();
            match (|raw: &mut Deserializer<_>| -> Result<_, DeserializeError> {
                (|| -> Result<_, DeserializeError> {
                    let tag_value = raw.unsigned_integer()?;
                    if tag_value != 0 {
                        return Err(DeserializeFailure::FixedValueMismatch {
                            found: Key::Uint(tag_value),
                            expected: Key::Uint(0),
                        }
                        .into());
                    }
                    Ok(())
                })()
                .map_err(|e| e.annotate("tag"))?;
                let stakeholder_id = raw
                    .bytes()
                    .map_err(Into::<DeserializeError>::into)
                    .and_then(|bytes| {
                        StakeholderId::from_raw_bytes(&bytes)
                            .map_err(|e| DeserializeFailure::InvalidStructure(Box::new(e)).into())
                    })
                    .map_err(|e: DeserializeError| e.annotate("stakeholder_id"))?;
                match len {
                    cbor_event::Len::Len(_) => (),
                    cbor_event::Len::Indefinite => match raw.special()? {
                        cbor_event::Special::Break => (),
                        _ => return Err(DeserializeFailure::EndingBreakMissing.into()),
                    },
                }
                Ok(Self::SingleKey(stakeholder_id))
            })(raw)
            {
                Ok(variant) => return Ok(variant),
                Err(_) => raw
                    .as_mut_ref()
                    .seek(SeekFrom::Start(initial_position))
                    .unwrap(),
            };
            match (|raw: &mut Deserializer<_>| -> Result<_, DeserializeError> {
                let bootstrap_era_distr_value = raw.unsigned_integer()?;
                if bootstrap_era_distr_value != 1 {
                    return Err(DeserializeFailure::FixedValueMismatch {
                        found: Key::Uint(bootstrap_era_distr_value),
                        expected: Key::Uint(1),
                    }
                    .into());
                }
                Ok(())
            })(raw)
            {
                Ok(()) => return Ok(StakeDistribution::BootstrapEra),
                Err(_) => raw
                    .as_mut_ref()
                    .seek(SeekFrom::Start(initial_position))
                    .unwrap(),
            };
            match len {
                cbor_event::Len::Len(_) => (),
                cbor_event::Len::Indefinite => match raw.special()? {
                    cbor_event::Special::Break => (),
                    _ => return Err(DeserializeFailure::EndingBreakMissing.into()),
                },
            }
            Err(DeserializeError::new(
                "StakeDistribution",
                DeserializeFailure::NoVariantMatched,
            ))
        })()
        .map_err(|e| e.annotate("StakeDistribution"))
    }
}