solana-ledger 4.2.0-beta.0

Solana ledger
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
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
//! Traits that define how data is encoded in the RocksDB-backed Blockstore.
use {
    crate::{
        blockstore::error::Result,
        blockstore_meta::{self, BlockLocation, PerfSample},
    },
    solana_clock::{Slot, UnixTimestamp},
    solana_hash::{HASH_BYTES, Hash},
    solana_pubkey::{PUBKEY_BYTES, Pubkey},
    solana_signature::{SIGNATURE_BYTES, Signature},
    solana_storage_proto::convert::generated,
    wincode::{
        ReadError, SchemaRead, SchemaReadOwned, SchemaWrite, config::DefaultConfig, io::Reader,
    },
};

pub(crate) const DEPRECATED_PROGRAM_COSTS_COLUMN_NAME: &str = "program_costs";
pub(crate) const DEPRECATED_TRANSACTION_STATUS_INDEX_NAME: &str = "transaction_status_index";

// To add a new column, declare the type below and implement the applicable
// traits for it. At the very least, Column and ColumnName will be necessary.
//
// Afterwards, update the Rocks implementation to create / load the new column.
// Lastly, remember to account for the column's cleanup so that the column does
// not grow unbounded.

pub mod columns {
    // This avoids relatively obvious `super::` qualifications required for all non-trivial type
    // references in the column doc-comments.
    #[cfg(doc)]
    use super::{Pubkey, Signature, Slot, SlotColumn, UnixTimestamp, blockstore_meta, generated};

    #[derive(Debug)]
    /// The slot metadata column.
    ///
    /// This column family tracks the status of the received shred data for a
    /// given slot.  Tracking the progress as the slot fills up allows us to
    /// know if the slot (or pieces of the slot) are ready to be replayed.
    ///
    /// * index type: `u64` (see [`SlotColumn`])
    /// * value type: [`blockstore_meta::SlotMeta`]
    pub struct SlotMeta;

    #[derive(Debug)]
    /// The alternate slot metadata column.
    ///
    /// Similar to [`SlotMeta`], however this column is only populated for alternate
    /// versions fetched via block_id based repair.
    ///
    /// * index type: `(slot: u64, block_id: Hash)`
    /// * value type: [`blockstore_meta::SlotMeta`]
    pub struct AlternateSlotMeta;

    #[derive(Debug)]
    /// The orphans column.
    ///
    /// This column family tracks whether a slot has a parent.  Slots without a
    /// parent are by definition orphan slots.  Orphans will have an entry in
    /// this column family with true value.  Once an orphan slot has a parent,
    /// its entry in this column will be deleted.
    ///
    /// * index type: `u64` (see [`SlotColumn`])
    /// * value type: `bool`
    pub struct Orphans;

    #[derive(Debug)]
    /// The dead slots column.
    /// This column family tracks whether a slot is dead.
    ///
    /// A slot is marked as dead if the validator thinks it will never be able
    /// to successfully replay this slot.  Example scenarios include errors
    /// during the replay of a slot, or the validator believes it will never
    /// receive all the shreds of a slot.
    ///
    /// If a slot has been mistakenly marked as dead, the ledger-tool's
    /// --remove-dead-slot can unmark a dead slot.
    ///
    /// * index type: `u64` (see [`SlotColumn`])
    /// * value type: `bool`
    pub struct DeadSlots;

    #[derive(Debug)]
    /// The duplicate slots column
    ///
    /// * index type: `u64` (see [`SlotColumn`])
    /// * value type: [`blockstore_meta::DuplicateSlotProof`]
    pub struct DuplicateSlots;

    #[derive(Debug)]
    /// The erasure meta column.
    ///
    /// This column family stores ErasureMeta which includes metadata about
    /// dropped network packets (or erasures) that can be used to recover
    /// missing data shreds.
    ///
    /// Its index type is `crate::shred::ErasureSetId`, which consists of a Slot ID
    /// and a FEC (Forward Error Correction) set index.
    ///
    /// * index type: `crate::shred::ErasureSetId` `(Slot, fec_set_index: u64)`
    /// * value type: [`blockstore_meta::ErasureMeta`]
    pub struct ErasureMeta;

    #[derive(Debug)]
    /// The bank hash column.
    ///
    /// This column family persists the bank hash of a given slot.  Note that
    /// not every slot has a bank hash (e.g., a dead slot.)
    ///
    /// The bank hash of a slot is derived from hashing the delta state of all
    /// the accounts in a slot combined with the bank hash of its parent slot.
    /// A bank hash of a slot essentially represents all the account states at
    /// that slot.
    ///
    /// * index type: `u64` (see [`SlotColumn`])
    /// * value type: [`blockstore_meta::FrozenHashVersioned`]
    pub struct BankHash;

    #[derive(Debug)]
    /// The root column.
    ///
    /// This column family persists whether a slot is a root.  Slots on the
    /// main fork will be inserted into this column when they are finalized.
    ///
    /// * index type: `u64` (see [`SlotColumn`])
    /// * value type: `bool`
    pub struct Root;

    #[derive(Debug)]
    /// The index column
    ///
    /// * index type: `u64` (see [`SlotColumn`])
    /// * value type: [`blockstore_meta::Index`]
    pub struct Index;

    #[derive(Debug)]
    /// The alternate index column.
    ///
    /// Similar to [`Index`], however this column is only populated for alternate
    /// versions fetched via block_id based repair.
    ///
    /// * index type: `(slot: u64, block_id: Hash)`
    /// * value type: [`blockstore_meta::Index`]
    pub struct AlternateIndex;

    #[derive(Debug)]
    /// The shred data column
    ///
    /// * index type: `(u64, u64)`
    /// * value type: [`Vec<u8>`]
    pub struct ShredData;

    #[derive(Debug)]
    /// The shred erasure code column
    ///
    /// * index type: `(u64, u64)`
    /// * value type: [`Vec<u8>`]
    pub struct ShredCode;

    #[derive(Debug)]
    /// The alternate shred data column
    ///
    /// Similar to [`ShredData`], however this column is only populated for alternate
    /// versions fetched via block_id based repair.
    ///
    /// * index type: `(slot: u64, block_id: Hash, shred_index: u64)`
    /// * value type: [`Vec<u8>`]
    pub struct AlternateShredData;

    #[derive(Debug)]
    /// The transaction status column
    ///
    /// * index type: `(`[`Signature`]`, `[`Slot`])`
    /// * value type: [`generated::TransactionStatusMeta`]
    pub struct TransactionStatus;

    #[derive(Debug)]
    /// The address signatures column
    ///
    /// * index type: `(`[`Pubkey`]`, `[`Slot`]`, u32, `[`Signature`]`)`
    /// * value type: [`blockstore_meta::AddressSignatureMeta`]
    pub struct AddressSignatures;

    #[derive(Debug)]
    /// The transaction memos column
    ///
    /// * index type: `(`[`Signature`]`, `[`Slot`])`
    /// * value type: [`String`]
    pub struct TransactionMemos;

    #[derive(Debug)]
    /// The rewards column
    ///
    /// * index type: `u64` (see [`SlotColumn`])
    /// * value type: [`generated::Rewards`]
    pub struct Rewards;

    #[derive(Debug)]
    /// The blocktime column
    ///
    /// * index type: `u64` (see [`SlotColumn`])
    /// * value type: [`UnixTimestamp`]
    pub struct Blocktime;

    #[derive(Debug)]
    /// The performance samples column
    ///
    /// * index type: `u64` (see [`SlotColumn`])
    /// * value type: [`blockstore_meta::PerfSample`]
    pub struct PerfSamples;

    #[derive(Debug)]
    /// The block height column
    ///
    /// * index type: `u64` (see [`SlotColumn`])
    /// * value type: `u64`
    pub struct BlockHeight;

    #[derive(Debug)]
    /// The optimistic slot column
    ///
    /// * index type: `u64` (see [`SlotColumn`])
    /// * value type: [`blockstore_meta::OptimisticSlotMetaVersioned`]
    pub struct OptimisticSlots;

    #[derive(Debug)]
    /// The merkle root meta column
    ///
    /// Each merkle shred is part of a merkle tree for
    /// its FEC set. This column stores that merkle root and associated
    /// meta information about the first shred received.
    ///
    /// Its index type is (Slot, fec_set_index).
    ///
    /// * index type: `crate::shred::ErasureSetId` `(Slot, fec_set_index: u32)`
    /// * value type: [`blockstore_meta::MerkleRootMeta`]
    pub struct MerkleRootMeta;

    #[derive(Debug)]
    /// The alternate merkle root meta column
    ///
    /// Similar to [`MerkleRootMeta`], however this column is only populated for alternate
    /// versions fetched via block_id based repair.
    ///
    /// * index type: `(slot: u64, block_id: Hash, fec_set_index: u32)`
    /// * value type: [`blockstore_meta::MerkleRootMeta`]
    pub struct AlternateMerkleRootMeta;

    #[derive(Debug)]
    /// The double merkle root metadata column
    ///
    /// This column stores details about the double merkle root of a block.
    /// We update this column when we finish ingesting all the shreds of the block.
    ///
    /// * index type: `(Slot, BlockLocation)`
    /// * value type: [`blockstore_meta::DoubleMerkleMeta`]
    pub struct DoubleMerkleMeta;
}

macro_rules! convert_column_index_to_key_bytes {
    ($key:ident, $($range:expr => $bytes:expr),* $(,)?) => {{
        let mut key = [0u8; std::mem::size_of::<Self::$key>()];
        debug_assert_eq!(0 $(+$bytes.len())*, key.len());
        $(key[$range].copy_from_slice($bytes);)*
        key
    }};
}

macro_rules! convert_column_key_bytes_to_index {
    ($k:ident, $($a:literal..$b:literal => $f:expr),* $(,)?) => {{
        ($($f(<[u8; $b-$a]>::try_from(&$k[$a..$b]).unwrap())),*)
    }};
}

// TODO: replace with dedicated wincode API on wincode>=0.5.1
fn deserialize_reject_trailing<'de, T>(src: &'de [u8]) -> Result<T>
where
    T: SchemaRead<'de, DefaultConfig, Dst = T>,
{
    let mut reader = src;
    let value = <T as SchemaRead<'de, DefaultConfig>>::get(reader.by_ref())?;
    if reader.is_empty() {
        Ok(value)
    } else {
        Err(ReadError::Custom("trailing bytes").into())
    }
}

pub trait Column {
    // The logical key for how data will be accessed in this column
    type Index;
    // Byte array representation of the Index type; this is the format RocksDB accepts
    type Key: AsRef<[u8]>;
    // Converts Self::Index to Self::Key
    fn key(index: &Self::Index) -> Self::Key;
    // Converts Self::Key to Self::Index
    fn index(key: &[u8]) -> Self::Index;
    // This trait method is primarily used by `Database::delete_range_cf()`, and is therefore only
    // relevant for columns keyed by Slot: ie. SlotColumns and columns that feature a Slot as the
    // first item in the key.
    fn as_index(slot: Slot) -> Self::Index;
    fn slot(index: Self::Index) -> Slot;
}

// RocksDB has a notion of columns families to group related data. The columns are refer
pub trait ColumnName {
    const NAME: &'static str;
}

// Columns that serialize data on insertion and deserialize on fetch
pub trait TypedColumn: Column {
    type Type: SchemaWrite<DefaultConfig, Src = Self::Type>
        + SchemaReadOwned<DefaultConfig, Dst = Self::Type>;

    #[inline]
    fn deserialize(data: &[u8]) -> Result<Self::Type> {
        Ok(wincode::deserialize(data)?)
    }

    #[inline]
    fn serialize(data: &Self::Type) -> Result<Vec<u8>> {
        Ok(wincode::serialize(data)?)
    }
}

pub trait ProtobufColumn: Column {
    type Type: prost::Message + Default;
}

/// SlotColumn is a trait for slot-based column families.  Its index is
/// essentially Slot (or more generally speaking, has a 1:1 mapping to Slot).
///
/// The clean-up of any LedgerColumn that implements SlotColumn is managed by
/// `LedgerCleanupService`, which will periodically deprecate and purge
/// oldest entries that are older than the latest root in order to maintain the
/// configured --limit-ledger-size under the validator argument.
pub trait SlotColumn<Index = Slot> {}

pub enum IndexError {
    UnpackError,
}

impl TypedColumn for columns::AddressSignatures {
    type Type = blockstore_meta::AddressSignatureMeta;
}

impl TypedColumn for columns::TransactionMemos {
    type Type = String;
}

impl<T: SlotColumn> Column for T {
    type Index = Slot;
    type Key = [u8; std::mem::size_of::<Slot>()];

    #[inline]
    fn key(slot: &Self::Index) -> Self::Key {
        slot.to_be_bytes()
    }

    /// Converts a RocksDB key to its u64 Index.
    fn index(key: &[u8]) -> Self::Index {
        convert_column_key_bytes_to_index!(key, 0..8 => Slot::from_be_bytes)
    }

    fn slot(index: Self::Index) -> Slot {
        index
    }

    /// Converts a Slot to its u64 Index.
    fn as_index(slot: Slot) -> u64 {
        slot
    }
}

impl Column for columns::TransactionStatus {
    type Index = (Signature, Slot);
    type Key = [u8; SIGNATURE_BYTES + std::mem::size_of::<Slot>()];

    #[inline]
    fn key((signature, slot): &Self::Index) -> Self::Key {
        convert_column_index_to_key_bytes!(Key,
            ..64 => signature.as_ref(),
            64.. => &slot.to_be_bytes(),
        )
    }

    fn index(key: &[u8]) -> (Signature, Slot) {
        convert_column_key_bytes_to_index!(key,
             0..64 => Signature::from,
            64..72 => Slot::from_be_bytes,
        )
    }

    fn slot(index: Self::Index) -> Slot {
        index.1
    }

    // The TransactionStatus column is not keyed by slot so this method is meaningless
    // See Column::as_index() declaration for more details
    fn as_index(_index: u64) -> Self::Index {
        (Signature::default(), 0)
    }
}
impl ColumnName for columns::TransactionStatus {
    const NAME: &'static str = "transaction_status";
}
impl ProtobufColumn for columns::TransactionStatus {
    type Type = generated::TransactionStatusMeta;
}

impl Column for columns::AddressSignatures {
    type Index = (Pubkey, Slot, /*transaction index:*/ u32, Signature);
    type Key = [u8; PUBKEY_BYTES
        + std::mem::size_of::<Slot>()
        + std::mem::size_of::<u32>()
        + SIGNATURE_BYTES];

    #[inline]
    fn key((pubkey, slot, transaction_index, signature): &Self::Index) -> Self::Key {
        convert_column_index_to_key_bytes!(Key,
              ..32 => pubkey.as_ref(),
            32..40 => &slot.to_be_bytes(),
            40..44 => &transaction_index.to_be_bytes(),
            44..   => signature.as_ref(),
        )
    }

    fn index(key: &[u8]) -> Self::Index {
        convert_column_key_bytes_to_index!(key,
             0..32  => Pubkey::from,
            32..40  => Slot::from_be_bytes,
            40..44  => u32::from_be_bytes,  // transaction index
            44..108 => Signature::from,
        )
    }

    fn slot(index: Self::Index) -> Slot {
        index.1
    }

    // The AddressSignatures column is not keyed by slot so this method is meaningless
    // See Column::as_index() declaration for more details
    fn as_index(_index: u64) -> Self::Index {
        (Pubkey::default(), 0, 0, Signature::default())
    }
}
impl ColumnName for columns::AddressSignatures {
    const NAME: &'static str = "address_signatures";
}

impl Column for columns::TransactionMemos {
    type Index = (Signature, Slot);
    type Key = [u8; SIGNATURE_BYTES + std::mem::size_of::<Slot>()];

    #[inline]
    fn key((signature, slot): &Self::Index) -> Self::Key {
        convert_column_index_to_key_bytes!(Key,
            ..64 => signature.as_ref(),
            64.. => &slot.to_be_bytes(),
        )
    }

    fn index(key: &[u8]) -> Self::Index {
        convert_column_key_bytes_to_index!(key,
             0..64 => Signature::from,
            64..72 => Slot::from_be_bytes,
        )
    }

    fn slot(index: Self::Index) -> Slot {
        index.1
    }

    fn as_index(index: u64) -> Self::Index {
        (Signature::default(), index)
    }
}
impl ColumnName for columns::TransactionMemos {
    const NAME: &'static str = "transaction_memos";
}

impl SlotColumn for columns::Rewards {}
impl ColumnName for columns::Rewards {
    const NAME: &'static str = "rewards";
}
impl ProtobufColumn for columns::Rewards {
    type Type = generated::Rewards;
}

impl SlotColumn for columns::Blocktime {}
impl ColumnName for columns::Blocktime {
    const NAME: &'static str = "blocktime";
}
impl TypedColumn for columns::Blocktime {
    type Type = UnixTimestamp;
}

impl SlotColumn for columns::PerfSamples {}
impl ColumnName for columns::PerfSamples {
    const NAME: &'static str = "perf_samples";
}

impl TypedColumn for columns::PerfSamples {
    type Type = PerfSample;
}

impl SlotColumn for columns::BlockHeight {}
impl ColumnName for columns::BlockHeight {
    const NAME: &'static str = "block_height";
}
impl TypedColumn for columns::BlockHeight {
    type Type = u64;
}

impl Column for columns::ShredCode {
    type Index = (Slot, /*shred index:*/ u64);
    type Key = <columns::ShredData as Column>::Key;

    #[inline]
    fn key(index: &Self::Index) -> Self::Key {
        // ShredCode and ShredData have the same key format
        <columns::ShredData as Column>::key(index)
    }

    fn index(key: &[u8]) -> Self::Index {
        columns::ShredData::index(key)
    }

    fn slot(index: Self::Index) -> Slot {
        index.0
    }

    fn as_index(slot: Slot) -> Self::Index {
        (slot, 0)
    }
}
impl ColumnName for columns::ShredCode {
    const NAME: &'static str = "code_shred";
}

impl Column for columns::ShredData {
    type Index = (Slot, /*shred index:*/ u64);
    type Key = [u8; std::mem::size_of::<Slot>() + std::mem::size_of::<u64>()];

    #[inline]
    fn key((slot, index): &Self::Index) -> Self::Key {
        convert_column_index_to_key_bytes!(Key,
            ..8 => &slot.to_be_bytes(),
            8.. => &index.to_be_bytes(),
        )
    }

    fn index(key: &[u8]) -> Self::Index {
        convert_column_key_bytes_to_index!(key,
            0..8  => Slot::from_be_bytes,
            8..16 => u64::from_be_bytes,  // shred index
        )
    }

    fn slot(index: Self::Index) -> Slot {
        index.0
    }

    fn as_index(slot: Slot) -> Self::Index {
        (slot, 0)
    }
}
impl ColumnName for columns::ShredData {
    const NAME: &'static str = "data_shred";
}

impl Column for columns::AlternateShredData {
    type Index = (Slot, /* block_id */ Hash, /* shred index: */ u64);
    type Key = [u8; std::mem::size_of::<Slot>() + std::mem::size_of::<u64>() + HASH_BYTES];

    #[inline]
    fn key((slot, block_id, index): &Self::Index) -> Self::Key {
        convert_column_index_to_key_bytes!(Key,
            ..8 => &slot.to_be_bytes(),
            8..40 => &block_id.to_bytes(),
            40.. => &index.to_be_bytes(),
        )
    }

    fn index(key: &[u8]) -> Self::Index {
        convert_column_key_bytes_to_index!(key,
            0..8  => Slot::from_be_bytes,
            8..40 => Hash::new_from_array, // block_id
            40..48 => u64::from_be_bytes,  // shred index
        )
    }

    fn slot(index: Self::Index) -> Slot {
        index.0
    }

    fn as_index(slot: Slot) -> Self::Index {
        (slot, Hash::default(), 0)
    }
}
impl ColumnName for columns::AlternateShredData {
    const NAME: &'static str = "alt_data_shred";
}

impl SlotColumn for columns::Index {}
impl ColumnName for columns::Index {
    const NAME: &'static str = "index";
}
impl TypedColumn for columns::Index {
    type Type = blockstore_meta::Index;

    #[inline]
    fn deserialize(data: &[u8]) -> Result<Self::Type> {
        deserialize_reject_trailing(data)
    }
}

impl Column for columns::AlternateIndex {
    // AlternateIndex and AlternateSlotMeta share the same key type so reuse code here
    type Index = <columns::AlternateSlotMeta as Column>::Index;
    type Key = <columns::AlternateSlotMeta as Column>::Key;

    #[inline]
    fn key(index: &Self::Index) -> Self::Key {
        <columns::AlternateSlotMeta as Column>::key(index)
    }

    fn index(key: &[u8]) -> Self::Index {
        <columns::AlternateSlotMeta as Column>::index(key)
    }

    fn slot(index: Self::Index) -> Slot {
        <columns::AlternateSlotMeta as Column>::slot(index)
    }

    fn as_index(slot: Slot) -> Self::Index {
        <columns::AlternateSlotMeta as Column>::as_index(slot)
    }
}
impl ColumnName for columns::AlternateIndex {
    const NAME: &'static str = "alt_index";
}
impl TypedColumn for columns::AlternateIndex {
    type Type = <columns::Index as TypedColumn>::Type;

    fn deserialize(data: &[u8]) -> Result<Self::Type> {
        <columns::Index as TypedColumn>::deserialize(data)
    }
}

impl SlotColumn for columns::DeadSlots {}
impl ColumnName for columns::DeadSlots {
    const NAME: &'static str = "dead_slots";
}
impl TypedColumn for columns::DeadSlots {
    type Type = bool;
}

impl SlotColumn for columns::DuplicateSlots {}
impl ColumnName for columns::DuplicateSlots {
    const NAME: &'static str = "duplicate_slots";
}
impl TypedColumn for columns::DuplicateSlots {
    type Type = blockstore_meta::DuplicateSlotProof;
}

impl SlotColumn for columns::Orphans {}
impl ColumnName for columns::Orphans {
    const NAME: &'static str = "orphans";
}
impl TypedColumn for columns::Orphans {
    type Type = bool;
}

impl SlotColumn for columns::BankHash {}
impl ColumnName for columns::BankHash {
    const NAME: &'static str = "bank_hashes";
}
impl TypedColumn for columns::BankHash {
    type Type = blockstore_meta::FrozenHashVersioned;
}

impl SlotColumn for columns::Root {}
impl ColumnName for columns::Root {
    const NAME: &'static str = "root";
}
impl TypedColumn for columns::Root {
    type Type = bool;
}

impl SlotColumn for columns::SlotMeta {}
impl ColumnName for columns::SlotMeta {
    const NAME: &'static str = "meta";
}
impl TypedColumn for columns::SlotMeta {
    type Type = blockstore_meta::SlotMeta;
}

impl Column for columns::AlternateSlotMeta {
    type Index = (Slot, /* block_id */ Hash);
    type Key = [u8; std::mem::size_of::<Slot>() + HASH_BYTES];

    #[inline]
    fn key((slot, block_id): &Self::Index) -> Self::Key {
        convert_column_index_to_key_bytes!(Key,
            ..8 => &slot.to_be_bytes(),
            8.. => &block_id.to_bytes(),
        )
    }

    fn index(key: &[u8]) -> Self::Index {
        convert_column_key_bytes_to_index!(key,
            0..8  => Slot::from_be_bytes,
            8..40 => Hash::new_from_array,
        )
    }

    fn slot(index: Self::Index) -> Slot {
        index.0
    }

    fn as_index(slot: Slot) -> Self::Index {
        (slot, Hash::default())
    }
}
impl ColumnName for columns::AlternateSlotMeta {
    const NAME: &'static str = "alt_meta";
}
impl TypedColumn for columns::AlternateSlotMeta {
    type Type = <columns::SlotMeta as TypedColumn>::Type;
}

impl Column for columns::ErasureMeta {
    type Index = (Slot, /*fec_set_index:*/ u64);
    type Key = [u8; std::mem::size_of::<Slot>() + std::mem::size_of::<u64>()];

    #[inline]
    fn key((slot, fec_set_index): &Self::Index) -> Self::Key {
        convert_column_index_to_key_bytes!(Key,
            ..8 => &slot.to_be_bytes(),
            8.. => &fec_set_index.to_be_bytes(),
        )
    }

    fn index(key: &[u8]) -> Self::Index {
        convert_column_key_bytes_to_index!(key,
            0..8  => Slot::from_be_bytes,
            8..16 => u64::from_be_bytes,  // fec_set_index
        )
    }

    fn slot(index: Self::Index) -> Slot {
        index.0
    }

    fn as_index(slot: Slot) -> Self::Index {
        (slot, 0)
    }
}
impl ColumnName for columns::ErasureMeta {
    const NAME: &'static str = "erasure_meta";
}
impl TypedColumn for columns::ErasureMeta {
    type Type = blockstore_meta::ErasureMeta;
}

impl SlotColumn for columns::OptimisticSlots {}
impl ColumnName for columns::OptimisticSlots {
    const NAME: &'static str = "optimistic_slots";
}
impl TypedColumn for columns::OptimisticSlots {
    type Type = blockstore_meta::OptimisticSlotMetaVersioned;
}

impl Column for columns::MerkleRootMeta {
    type Index = (Slot, /*fec_set_index:*/ u32);
    type Key = [u8; std::mem::size_of::<Slot>() + std::mem::size_of::<u32>()];

    #[inline]
    fn key((slot, fec_set_index): &Self::Index) -> Self::Key {
        convert_column_index_to_key_bytes!(Key,
            ..8 => &slot.to_be_bytes(),
            8.. => &fec_set_index.to_be_bytes(),
        )
    }

    fn index(key: &[u8]) -> Self::Index {
        convert_column_key_bytes_to_index!(key,
            0..8  => Slot::from_be_bytes,
            8..12 => u32::from_be_bytes,  // fec_set_index
        )
    }

    fn slot((slot, _fec_set_index): Self::Index) -> Slot {
        slot
    }

    fn as_index(slot: Slot) -> Self::Index {
        (slot, 0)
    }
}

impl ColumnName for columns::MerkleRootMeta {
    const NAME: &'static str = "merkle_root_meta";
}
impl TypedColumn for columns::MerkleRootMeta {
    type Type = blockstore_meta::MerkleRootMeta;
}

impl Column for columns::AlternateMerkleRootMeta {
    type Index = (Slot, /* block_id */ Hash, /*fec_set_index:*/ u32);
    type Key = [u8; std::mem::size_of::<Slot>() + std::mem::size_of::<u32>() + HASH_BYTES];

    #[inline]
    fn key((slot, block_id, fec_set_index): &Self::Index) -> Self::Key {
        convert_column_index_to_key_bytes!(Key,
            ..8 => &slot.to_be_bytes(),
            8..40 => &block_id.to_bytes(),
            40.. => &fec_set_index.to_be_bytes(),
        )
    }

    fn index(key: &[u8]) -> Self::Index {
        convert_column_key_bytes_to_index!(key,
            0..8  => Slot::from_be_bytes,
            8..40 => Hash::new_from_array, // block_id
            40..44 => u32::from_be_bytes,  // fec_set_index
        )
    }

    fn slot((slot, _block_id, _fec_set_index): Self::Index) -> Slot {
        slot
    }

    fn as_index(slot: Slot) -> Self::Index {
        (slot, Hash::default(), 0)
    }
}

impl ColumnName for columns::AlternateMerkleRootMeta {
    const NAME: &'static str = "alt_merkle_root_meta";
}
impl TypedColumn for columns::AlternateMerkleRootMeta {
    type Type = blockstore_meta::MerkleRootMeta;
}

impl Column for columns::DoubleMerkleMeta {
    type Index = (Slot, BlockLocation);
    // Key size: Slot (8 bytes) + Hash (32 bytes)
    // When BlockLocation::Original, the hash is Hash::default().
    type Key = [u8; std::mem::size_of::<Slot>() + HASH_BYTES];

    #[inline]
    fn key((slot, location): &Self::Index) -> Self::Key {
        debug_assert_eq!(std::mem::size_of::<Slot>(), 8);
        convert_column_index_to_key_bytes!(Key,
            ..8 => &slot.to_be_bytes(),
            8.. => &location.as_bytes()
        )
    }

    fn index(key: &[u8]) -> Self::Index {
        convert_column_key_bytes_to_index!(key,
            0..8 => Slot::from_be_bytes,
            8..40 => BlockLocation::from_bytes,
        )
    }

    fn as_index(slot: Slot) -> Self::Index {
        (slot, BlockLocation::Original)
    }

    fn slot((slot, _location): Self::Index) -> Slot {
        slot
    }
}

impl ColumnName for columns::DoubleMerkleMeta {
    const NAME: &'static str = "double_merkle_meta";
}

impl TypedColumn for columns::DoubleMerkleMeta {
    type Type = blockstore_meta::DoubleMerkleMeta;
}

#[cfg(test)]
mod tests {
    use {
        super::*,
        crate::blockstore_meta::{CompletedDataIndexes, ConnectedFlags},
        solana_hash::Hash,
        wincode,
    };

    #[test]
    fn test_slot_meta_column_roundtrip() {
        let meta = blockstore_meta::SlotMeta {
            slot: 42,
            consumed: 10,
            received: 15,
            first_shred_timestamp: 1234567890,
            last_index: Some(14),
            parent_slot: Some(41),
            next_slots: vec![43, 44],
            connected_flags: ConnectedFlags::CONNECTED | ConnectedFlags::PARENT_CONNECTED,
            completed_data_indexes: [0u32, 5, 10].into_iter().collect(),
            parent_block_id: Hash::new_unique(),
            replay_fec_set_index: 7,
        };

        let bytes = <columns::SlotMeta as TypedColumn>::serialize(&meta).unwrap();
        let deserialized = <columns::SlotMeta as TypedColumn>::deserialize(&bytes).unwrap();
        assert_eq!(meta, deserialized);
    }

    #[test]
    fn test_slot_meta_column_deserialize_from_v2_bytes() {
        let v2 = blockstore_meta::SlotMetaV2 {
            slot: 42,
            consumed: 10,
            received: 15,
            first_shred_timestamp: 1234567890,
            last_index: Some(14),
            parent_slot: Some(41),
            next_slots: vec![43, 44],
            connected_flags: ConnectedFlags::CONNECTED | ConnectedFlags::PARENT_CONNECTED,
            completed_data_indexes: [0u32, 5, 10].into_iter().collect(),
        };
        let v2_bytes = wincode::serialize(&v2).unwrap();

        let deserialized = <columns::SlotMeta as TypedColumn>::deserialize(&v2_bytes).unwrap();
        let expected = blockstore_meta::SlotMeta {
            slot: 42,
            consumed: 10,
            received: 15,
            first_shred_timestamp: 1234567890,
            last_index: Some(14),
            parent_slot: Some(41),
            next_slots: vec![43, 44],
            connected_flags: ConnectedFlags::CONNECTED | ConnectedFlags::PARENT_CONNECTED,
            completed_data_indexes: [0u32, 5, 10].into_iter().collect(),
            ..Default::default()
        };
        assert_eq!(deserialized, expected);
    }

    #[test]
    fn test_default_wincode_deserialize_handles_v2_bytes() {
        let v2 = blockstore_meta::SlotMetaV2 {
            slot: 1,
            consumed: 0,
            received: 0,
            first_shred_timestamp: 0,
            last_index: None,
            parent_slot: Some(0),
            next_slots: vec![],
            connected_flags: ConnectedFlags::empty(),
            completed_data_indexes: CompletedDataIndexes::default(),
        };
        let v2_bytes = wincode::serialize(&v2).unwrap();
        let deserialized = wincode::deserialize::<blockstore_meta::SlotMeta>(&v2_bytes).unwrap();
        assert_eq!(deserialized.parent_block_id, Hash::default());
        assert_eq!(deserialized.replay_fec_set_index, 0);

        let v3 = blockstore_meta::SlotMeta {
            slot: 1,
            consumed: 0,
            received: 0,
            first_shred_timestamp: 0,
            last_index: None,
            parent_slot: Some(0),
            next_slots: vec![],
            connected_flags: ConnectedFlags::empty(),
            completed_data_indexes: CompletedDataIndexes::default(),
            parent_block_id: Hash::new_unique(),
            replay_fec_set_index: 7,
        };
        let v3_bytes = wincode::serialize(&v3).unwrap();
        let deserialized = wincode::deserialize::<blockstore_meta::SlotMeta>(&v3_bytes).unwrap();
        assert_eq!(deserialized, v3);
    }
}