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
use crate::shared::wasm_config::WasmConfig;
use casper_types::{
    bytesrepr::{self, FromBytes, ToBytes},
    ContractHash, HashAddr,
};
use std::collections::BTreeMap;

const DEFAULT_ADDRESS: [u8; 32] = [0; 32];

/// Represents a protocol's data. Intended to be associated with a given protocol version.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub struct ProtocolData {
    wasm_config: WasmConfig,
    mint: ContractHash,
    proof_of_stake: ContractHash,
    standard_payment: ContractHash,
    auction: ContractHash,
}

/// Provides a default instance with non existing urefs and empty costs table.
///
/// Used in contexts where PoS or Mint contract is not ready yet, and pos, and
/// mint installers are ran. For use with caution.
impl Default for ProtocolData {
    fn default() -> ProtocolData {
        ProtocolData {
            wasm_config: WasmConfig::default(),
            mint: DEFAULT_ADDRESS,
            proof_of_stake: DEFAULT_ADDRESS,
            standard_payment: DEFAULT_ADDRESS,
            auction: DEFAULT_ADDRESS,
        }
    }
}

impl ProtocolData {
    /// Creates a new [`ProtocolData`] value from a given [`WasmCosts`] value.
    pub fn new(
        wasm_config: WasmConfig,
        mint: ContractHash,
        proof_of_stake: ContractHash,
        standard_payment: ContractHash,
        auction: ContractHash,
    ) -> Self {
        ProtocolData {
            wasm_config,
            mint,
            proof_of_stake,
            standard_payment,
            auction,
        }
    }

    /// Creates a new, partially-valid [`ProtocolData`] value where only the mint URef is known.
    ///
    /// Used during `commit_genesis` before all system contracts' URefs are known.
    pub fn partial_with_mint(mint: ContractHash) -> Self {
        ProtocolData {
            mint,
            ..Default::default()
        }
    }

    /// Creates a new, partially-valid [`ProtocolData`] value where all but the standard payment
    /// uref is known.
    ///
    /// Used during `commit_genesis` before all system contracts' URefs are known.
    pub fn partial_without_standard_payment(
        wasm_config: WasmConfig,
        mint: ContractHash,
        proof_of_stake: ContractHash,
    ) -> Self {
        ProtocolData {
            wasm_config,
            mint,
            proof_of_stake,
            ..Default::default()
        }
    }

    /// Gets the [`WasmCosts`] value from a given [`ProtocolData`] value.
    pub fn wasm_config(&self) -> &WasmConfig {
        &self.wasm_config
    }

    pub fn mint(&self) -> ContractHash {
        self.mint
    }

    pub fn proof_of_stake(&self) -> ContractHash {
        self.proof_of_stake
    }

    pub fn standard_payment(&self) -> ContractHash {
        self.standard_payment
    }

    pub fn auction(&self) -> ContractHash {
        self.auction
    }

    /// Retrieves all valid system contracts stored in protocol version
    pub fn system_contracts(&self) -> Vec<ContractHash> {
        let mut vec = Vec::with_capacity(3);
        if self.mint != DEFAULT_ADDRESS {
            vec.push(self.mint)
        }
        if self.proof_of_stake != DEFAULT_ADDRESS {
            vec.push(self.proof_of_stake)
        }
        if self.standard_payment != DEFAULT_ADDRESS {
            vec.push(self.standard_payment)
        }
        if self.auction != DEFAULT_ADDRESS {
            vec.push(self.auction)
        }
        vec
    }

    pub fn update_from(&mut self, updates: BTreeMap<ContractHash, ContractHash>) -> bool {
        for (old_hash, new_hash) in updates {
            if old_hash == self.mint {
                self.mint = new_hash;
            } else if old_hash == self.proof_of_stake {
                self.proof_of_stake = new_hash;
            } else if old_hash == self.standard_payment {
                self.standard_payment = new_hash;
            } else if old_hash == self.auction {
                self.auction = new_hash;
            } else {
                return false;
            }
        }
        true
    }
}

impl ToBytes for ProtocolData {
    fn to_bytes(&self) -> Result<Vec<u8>, bytesrepr::Error> {
        let mut ret = bytesrepr::unchecked_allocate_buffer(self);
        ret.append(&mut self.wasm_config.to_bytes()?);
        ret.append(&mut self.mint.to_bytes()?);
        ret.append(&mut self.proof_of_stake.to_bytes()?);
        ret.append(&mut self.standard_payment.to_bytes()?);
        ret.append(&mut self.auction.to_bytes()?);
        Ok(ret)
    }

    fn serialized_length(&self) -> usize {
        self.wasm_config.serialized_length()
            + self.mint.serialized_length()
            + self.proof_of_stake.serialized_length()
            + self.standard_payment.serialized_length()
            + self.auction.serialized_length()
    }
}

impl FromBytes for ProtocolData {
    fn from_bytes(bytes: &[u8]) -> Result<(Self, &[u8]), bytesrepr::Error> {
        let (wasm_config, rem) = WasmConfig::from_bytes(bytes)?;
        let (mint, rem) = HashAddr::from_bytes(rem)?;
        let (proof_of_stake, rem) = HashAddr::from_bytes(rem)?;
        let (standard_payment, rem) = HashAddr::from_bytes(rem)?;
        let (auction, rem) = HashAddr::from_bytes(rem)?;

        Ok((
            ProtocolData {
                wasm_config,
                mint,
                proof_of_stake,
                standard_payment,
                auction,
            },
            rem,
        ))
    }
}

#[cfg(test)]
pub(crate) mod gens {
    use proptest::prop_compose;

    use crate::shared::wasm_config::gens::wasm_config_arb;
    use casper_types::gens;

    use super::ProtocolData;

    prop_compose! {
        pub fn protocol_data_arb()(
            wasm_config in wasm_config_arb(),
            mint in gens::u8_slice_32(),
            proof_of_stake in gens::u8_slice_32(),
            standard_payment in gens::u8_slice_32(),
            auction in gens::u8_slice_32(),
        ) -> ProtocolData {
            ProtocolData {
                wasm_config,
                mint,
                proof_of_stake,
                standard_payment,
                auction,
            }
        }
    }
}

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

    use crate::shared::wasm_config::WasmConfig;
    use casper_types::{bytesrepr, ContractHash};

    use super::{gens, ProtocolData};

    #[test]
    fn should_return_all_system_contracts() {
        let mint_reference = [1u8; 32];
        let proof_of_stake_reference = [2u8; 32];
        let standard_payment_reference = [3u8; 32];
        let auction_reference = [4u8; 32];
        let protocol_data = {
            let wasm_config = WasmConfig::default();
            ProtocolData::new(
                wasm_config,
                mint_reference,
                proof_of_stake_reference,
                standard_payment_reference,
                auction_reference,
            )
        };

        let actual = {
            let mut items = protocol_data.system_contracts();
            items.sort();
            items
        };

        assert_eq!(actual.len(), 4);
        assert_eq!(actual[0], mint_reference);
        assert_eq!(actual[1], proof_of_stake_reference);
        assert_eq!(actual[2], standard_payment_reference);
        assert_eq!(actual[3], auction_reference);
    }

    #[test]
    fn should_return_only_valid_system_contracts() {
        let expected: Vec<ContractHash> = vec![];
        assert_eq!(ProtocolData::default().system_contracts(), expected);

        let mint_reference = [0u8; 32]; // <-- invalid addr
        let proof_of_stake_reference = [2u8; 32];
        let standard_payment_reference = [3u8; 32];
        let auction_reference = [4u8; 32];
        let protocol_data = {
            let wasm_config = WasmConfig::default();
            ProtocolData::new(
                wasm_config,
                mint_reference,
                proof_of_stake_reference,
                standard_payment_reference,
                auction_reference,
            )
        };

        let actual = {
            let mut items = protocol_data.system_contracts();
            items.sort();
            items
        };

        assert_eq!(actual.len(), 3);
        assert_eq!(actual[0], proof_of_stake_reference);
        assert_eq!(actual[1], standard_payment_reference);
        assert_eq!(actual[2], auction_reference);
    }

    proptest! {
        #[test]
        fn should_serialize_and_deserialize_with_arbitrary_values(
            protocol_data in gens::protocol_data_arb()
        ) {
            bytesrepr::test_serialization_roundtrip(&protocol_data);
        }
    }
}