hotshot_types/
stake_table.rs

1// Copyright (c) 2021-2024 Espresso Systems (espressosys.com)
2// This file is part of the HotShot repository.
3
4// You should have received a copy of the MIT License
5// along with the HotShot repository. If not, see <https://mit-license.org/>.
6
7//! Types and structs related to the stake table
8
9use alloy::primitives::U256;
10use ark_ff::PrimeField;
11use derive_more::derive::{Deref, DerefMut};
12use jf_crhf::CRHF;
13use jf_rescue::crhf::VariableLengthRescueCRHF;
14use serde::{Deserialize, Serialize};
15
16use crate::{
17    light_client::{CircuitField, StakeTableState, ToFieldsLightClientCompat},
18    traits::signature_key::{SignatureKey, StakeTableEntryType},
19    NodeType, PeerConfig,
20};
21
22/// Stake table entry
23#[derive(Serialize, Deserialize, PartialEq, Clone, Hash, Eq)]
24#[serde(bound(deserialize = ""))]
25pub struct StakeTableEntry<K: SignatureKey> {
26    /// The public key
27    pub stake_key: K,
28    /// The associated stake amount
29    pub stake_amount: U256,
30}
31
32impl<K: SignatureKey> StakeTableEntryType<K> for StakeTableEntry<K> {
33    /// Get the stake amount
34    fn stake(&self) -> U256 {
35        self.stake_amount
36    }
37
38    /// Get the public key
39    fn public_key(&self) -> K {
40        self.stake_key.clone()
41    }
42}
43
44impl<K: SignatureKey> StakeTableEntry<K> {
45    /// Get the public key
46    pub fn key(&self) -> &K {
47        &self.stake_key
48    }
49}
50
51impl<K: SignatureKey> std::fmt::Debug for StakeTableEntry<K> {
52    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
53        f.debug_struct("StakeTableEntry")
54            .field("stake_key", &format_args!("{}", self.stake_key))
55            .field("stake_amount", &self.stake_amount)
56            .finish()
57    }
58}
59
60#[derive(Debug, Clone, PartialEq, Eq, Hash, Default, Deref, DerefMut)]
61pub struct HSStakeTable<TYPES: NodeType>(pub Vec<PeerConfig<TYPES>>);
62
63impl<TYPES: NodeType> From<Vec<PeerConfig<TYPES>>> for HSStakeTable<TYPES> {
64    fn from(peers: Vec<PeerConfig<TYPES>>) -> Self {
65        Self(peers)
66    }
67}
68
69#[inline]
70/// A helper function to compute the quorum threshold given a total amount of stake.
71pub fn one_honest_threshold(total_stake: U256) -> U256 {
72    total_stake / U256::from(3) + U256::from(1)
73}
74
75#[inline]
76fn u256_to_field(amount: U256) -> CircuitField {
77    let amount_bytes: [u8; 32] = amount.to_le_bytes();
78    CircuitField::from_le_bytes_mod_order(&amount_bytes)
79}
80
81impl<TYPES: NodeType> std::iter::IntoIterator for HSStakeTable<TYPES> {
82    type Item = PeerConfig<TYPES>;
83    type IntoIter = std::vec::IntoIter<PeerConfig<TYPES>>;
84
85    fn into_iter(self) -> Self::IntoIter {
86        self.0.into_iter()
87    }
88}
89
90impl<TYPES: NodeType> HSStakeTable<TYPES> {
91    pub fn commitment(&self, stake_table_capacity: usize) -> anyhow::Result<StakeTableState> {
92        if stake_table_capacity < self.0.len() {
93            return Err(anyhow::anyhow!(
94                "Stake table over capacity: {} < {}",
95                stake_table_capacity,
96                self.0.len(),
97            ));
98        }
99        let padding_len = stake_table_capacity - self.0.len();
100        let mut bls_preimage = vec![];
101        let mut schnorr_preimage = vec![];
102        let mut amount_preimage = vec![];
103        let mut total_stake = U256::from(0);
104        for peer in &self.0 {
105            bls_preimage.extend(peer.stake_table_entry.public_key().to_fields());
106            schnorr_preimage.extend(peer.state_ver_key.to_fields());
107            amount_preimage.push(u256_to_field(peer.stake_table_entry.stake()));
108            total_stake += peer.stake_table_entry.stake();
109        }
110        bls_preimage.resize(
111            <TYPES::SignatureKey as ToFieldsLightClientCompat>::SIZE * stake_table_capacity,
112            CircuitField::default(),
113        );
114        // Nasty tech debt
115        schnorr_preimage.extend(
116            std::iter::repeat_n(TYPES::StateSignatureKey::default().to_fields(), padding_len)
117                .flatten(),
118        );
119        amount_preimage.resize(stake_table_capacity, CircuitField::default());
120        let threshold = u256_to_field(one_honest_threshold(total_stake));
121        Ok(StakeTableState {
122            bls_key_comm: VariableLengthRescueCRHF::<CircuitField, 1>::evaluate(bls_preimage)
123                .unwrap()[0],
124            schnorr_key_comm: VariableLengthRescueCRHF::<CircuitField, 1>::evaluate(
125                schnorr_preimage,
126            )
127            .unwrap()[0],
128            amount_comm: VariableLengthRescueCRHF::<CircuitField, 1>::evaluate(amount_preimage)
129                .unwrap()[0],
130            threshold,
131        })
132    }
133
134    pub fn total_stakes(&self) -> U256 {
135        self.0
136            .iter()
137            .map(|peer| peer.stake_table_entry.stake())
138            .sum()
139    }
140}
141
142pub struct StakeTableEntries<TYPES: NodeType>(
143    pub Vec<<<TYPES as NodeType>::SignatureKey as SignatureKey>::StakeTableEntry>,
144);
145
146impl<TYPES: NodeType> From<Vec<PeerConfig<TYPES>>> for StakeTableEntries<TYPES> {
147    fn from(peers: Vec<PeerConfig<TYPES>>) -> Self {
148        Self(
149            peers
150                .into_iter()
151                .map(|peer| peer.stake_table_entry)
152                .collect::<Vec<_>>(),
153        )
154    }
155}
156
157impl<TYPES: NodeType> From<HSStakeTable<TYPES>> for StakeTableEntries<TYPES> {
158    fn from(stake_table: HSStakeTable<TYPES>) -> Self {
159        Self::from(stake_table.0)
160    }
161}