1313static constexpr uint8_t DB_BLOCK_HASH{' s' };
1414static constexpr uint8_t DB_BLOCK_HEIGHT{' t' };
1515
16- struct DBHeightKey {
17- int height;
18-
19- explicit DBHeightKey (int height_in) : height(height_in) {}
20-
21- template <typename Stream>
22- void Serialize (Stream& s) const
23- {
24- ser_writedata8 (s, DB_BLOCK_HEIGHT);
25- ser_writedata32be (s, height);
16+ template <uint8_t Prefix, typename T, auto SerializeFunc, auto UnserializeFunc>
17+ struct DBKey {
18+ T value;
19+ explicit DBKey (const T& v) : value(v) {}
20+
21+ template <typename S>
22+ void Serialize (S& s) const {
23+ ser_writedata8 (s, Prefix);
24+ SerializeFunc (s, value);
2625 }
2726
28- template <typename Stream>
29- void Unserialize (Stream& s)
30- {
31- const uint8_t prefix{ser_readdata8 (s)};
32- if (prefix != DB_BLOCK_HEIGHT) {
33- throw std::ios_base::failure (" Invalid format for index DB height key" );
34- }
35- height = ser_readdata32be (s);
27+ template <typename S>
28+ void Unserialize (S& s) {
29+ if (ser_readdata8 (s) != Prefix)
30+ throw std::ios_base::failure (" Invalid DB key prefix" );
31+ UnserializeFunc (s, value);
3632 }
3733};
3834
39- struct DBHashKey {
40- uint256 hash;
41-
42- explicit DBHashKey (const uint256& hash_in) : hash(hash_in) {}
35+ using DBHeightKey = DBKey<DB_BLOCK_HEIGHT, int ,
36+ [](auto & s, int v) { ser_writedata32be (s, v); },
37+ [](auto & s, int & v) { v = ser_readdata32be (s); }>;
4338
44- SERIALIZE_METHODS (DBHashKey, obj) {
45- uint8_t prefix{DB_BLOCK_HASH};
46- READWRITE (prefix);
47- if (prefix != DB_BLOCK_HASH) {
48- throw std::ios_base::failure (" Invalid format for index DB hash key" );
49- }
50-
51- READWRITE (obj.hash );
52- }
53- };
39+ using DBHashKey = DBKey<DB_BLOCK_HASH, uint256,
40+ [](auto & s, const uint256& v) { ::Serialize (s, const_cast <uint256&>(v)); },
41+ [](auto & s, uint256& v) { ::Unserialize (s, v); }>;
5442
5543template <typename DBVal>
5644[[nodiscard]] static bool CopyHeightIndexToHashIndex (CDBIterator& db_it, CDBBatch& batch,
@@ -59,7 +47,7 @@ template <typename DBVal>
5947 DBHeightKey key (height);
6048 db_it.Seek (key);
6149
62- if (!db_it.GetKey (key) || key.height != height) {
50+ if (!db_it.GetKey (key) || key.value != height) {
6351 LogError (" unexpected key in %s: expected (%c, %d)" ,
6452 index_name, DB_BLOCK_HEIGHT, height);
6553 return false ;
0 commit comments