dusk-rusk 1.6.0

Rusk is the Dusk Network node implementation
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
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
//
// Copyright (c) DUSK NETWORK. All rights reserved.

mod config;
mod query;

use dusk_consensus::errors::StateTransitionError;
use dusk_core::abi::ContractId;
use node_data::events::contract::ContractTxEvent;
use tracing::{debug, info};

use dusk_consensus::operations::{
    StateTransitionData, StateTransitionResult, Voter,
};
use dusk_consensus::user::provisioners::Provisioners;
use dusk_consensus::user::stake::Stake;
use dusk_core::signatures::bls::PublicKey as BlsPublicKey;
use dusk_core::stake::StakeData;
use dusk_core::transfer::Transaction as ProtocolTransaction;
use node::vm::{PreverificationResult, VMExecution};
use node_data::bls::PublicKey;
use node_data::hard_fork::{bls_version_at, hard_fork_at};
use node_data::ledger::{Block, Header, SpentTransaction, Transaction};

use super::rusk::plonk_version_at;
use super::{RuesEvent, Rusk};
pub use config::Config as RuskVmConfig;
pub use config::feature::*;
pub use config::known::WellKnownConfig as WellKnownVmConfig;
pub use config::opt::OptionalConfig as RuskOptVmConfig;

use crate::Error as RuskError;

impl VMExecution for Rusk {
    fn create_state_transition<I: Iterator<Item = Transaction>>(
        &self,
        transition_data: &StateTransitionData,
        mempool_txs: I,
    ) -> Result<
        (
            Vec<SpentTransaction>,
            Vec<Transaction>,
            StateTransitionResult,
        ),
        StateTransitionError,
    > {
        self.create_state_transition(transition_data, mempool_txs)
    }

    /// Executes a block's state transition and checks its result against the
    /// block's header
    fn verify_state_transition(
        &self,
        prev_state: [u8; 32],
        blk: &Block,
        cert_voters: &[Voter],
    ) -> Result<(), StateTransitionError> {
        debug!("Verifying state transition");

        // Execute state transition
        let (_, transition_result, _, _) =
            self.execute_state_transition(prev_state, blk, cert_voters)?;

        // Check result against header
        check_transition_result(&transition_result, blk.header())?;

        Ok(())
    }

    /// Execute and persist a block's state transition.
    ///
    /// # Arguments
    ///
    /// * `prev_state` - the root of the previous block's state.
    /// * `blk` - the block defining the state transition.
    /// * `cert_voters` - list of voters in the Certificate for the previous
    ///   block. This is used to compute rewards. It is passed as a separate
    ///   argument for convenience (voters are extracted during the Certificate
    ///   verification).
    ///
    /// # Returns
    ///
    /// * Vec<SpentTransaction> - The transactions that were spent.
    /// * Vec<ContractTxEvent> - All emitted contract events
    ///
    /// # Errors
    ///
    /// * If the state transition fails verification
    /// * If the session fails to commit
    fn accept_state_transition(
        &self,
        prev_state: [u8; 32],
        blk: &Block,
        cert_voters: &[Voter],
    ) -> Result<
        (Vec<SpentTransaction>, Vec<ContractTxEvent>),
        StateTransitionError,
    > {
        debug!("Accepting state transition");

        // Execute state transition
        let (executed_txs, transition_result, contract_events, session) =
            self.execute_state_transition(prev_state, blk, cert_voters)?;

        // Check result against header
        check_transition_result(&transition_result, blk.header())?;

        // Commit state transition
        self.commit_session(session).map_err(|err| {
            StateTransitionError::PersistenceError(format!("{err}"))
        })?;

        // Send contract events to RUES
        // NOTE: we do it here and not in accept_block because RuesEvent is part
        // of the Rusk component
        for event in contract_events.clone() {
            let rues_event = RuesEvent::from(event);
            let _ = self.event_sender.send(rues_event);
        }

        Ok((executed_txs, contract_events))
    }

    fn move_to_commit(&self, commit: [u8; 32]) -> anyhow::Result<()> {
        self.query_session(Some(commit))
            .map_err(|e| anyhow::anyhow!("Cannot open session {e}"))?;
        self.set_current_commit(commit);
        Ok(())
    }

    fn finalize_state(
        &self,
        commit: [u8; 32],
        to_merge: Vec<[u8; 32]>,
    ) -> anyhow::Result<()> {
        debug!("Received finalize request");
        self.finalize_state(commit, to_merge)
            .map_err(|e| anyhow::anyhow!("Cannot finalize state: {e}"))
    }

    fn preverify(
        &self,
        tx: &Transaction,
        tip_height: u64,
    ) -> anyhow::Result<PreverificationResult> {
        info!("Received preverify request");
        let tx = &tx.inner;

        match tx {
            ProtocolTransaction::Phoenix(tx) => {
                let tx_nullifiers = tx.nullifiers().to_vec();
                let existing_nullifiers =
                    self.existing_nullifiers(&tx_nullifiers).map_err(|e| {
                        anyhow::anyhow!("Cannot check nullifiers: {e}")
                    })?;

                if !existing_nullifiers.is_empty() {
                    let err =
                        RuskError::RepeatingNullifiers(existing_nullifiers);
                    return Err(anyhow::anyhow!("{err}"));
                }

                if !has_unique_elements(tx_nullifiers) {
                    let err = RuskError::DoubleNullifiers;
                    return Err(anyhow::anyhow!("{err}"));
                }

                let next_block_height = tip_height.saturating_add(1);
                let version = plonk_version_at(
                    &self.vm_config,
                    next_block_height,
                    hard_fork_at(next_block_height),
                );

                match crate::verifier::verify_proof_with_version(tx, version) {
                    Ok(true) => Ok(PreverificationResult::Valid),
                    Ok(false) => Err(anyhow::anyhow!("Invalid proof")),
                    Err(e) => {
                        Err(anyhow::anyhow!("Cannot verify the proof: {e}"))
                    }
                }
            }
            ProtocolTransaction::Moonlight(tx) => {
                let next_block_height = tip_height.saturating_add(1);
                let account_data = self.account(tx.sender()).map_err(|e| {
                    anyhow::anyhow!("Cannot check account: {e}")
                })?;

                let max_value = tx
                    .gas_limit()
                    .checked_mul(tx.gas_price())
                    .and_then(|v| v.checked_add(tx.value()))
                    .and_then(|v| v.checked_add(tx.deposit()))
                    .ok_or(anyhow::anyhow!("Value spent will overflow"))?;

                if max_value > account_data.balance {
                    return Err(anyhow::anyhow!(
                        "Value spent larger than account holds"
                    ));
                }

                if tx.nonce() <= account_data.nonce {
                    let err = RuskError::RepeatingNonce(
                        (*tx.sender()).into(),
                        tx.nonce(),
                    );
                    return Err(anyhow::anyhow!("{err}"));
                }

                let result = if tx.nonce() > account_data.nonce + 1 {
                    PreverificationResult::FutureNonce {
                        account: *tx.sender(),
                        state: account_data,
                        nonce_used: tx.nonce(),
                    }
                } else {
                    PreverificationResult::Valid
                };

                let blob_converted = tx.blob_to_memo();
                let verify_tx = blob_converted.as_ref().unwrap_or(tx);
                let verify_result = dusk_core::signatures::bls::verify(
                    verify_tx.sender(),
                    verify_tx.signature(),
                    &verify_tx.signature_message(),
                    bls_version_at(next_block_height),
                );

                match verify_result {
                    Ok(()) => Ok(result),
                    Err(_) => Err(anyhow::anyhow!("Invalid signature")),
                }
            }
        }
    }

    fn get_provisioners(
        &self,
        base_commit: [u8; 32],
    ) -> anyhow::Result<Provisioners> {
        self.query_provisioners(Some(base_commit))
    }

    fn get_changed_provisioners(
        &self,
        base_commit: [u8; 32],
    ) -> anyhow::Result<Vec<(PublicKey, Option<Stake>)>> {
        self.query_provisioners_change(Some(base_commit))
    }

    fn get_provisioner(
        &self,
        pk: &BlsPublicKey,
    ) -> anyhow::Result<Option<Stake>> {
        let stake = self
            .provisioner(pk)
            .map_err(|e| anyhow::anyhow!("Cannot get provisioner {e}"))?
            .map(Self::to_stake);
        Ok(stake)
    }

    fn get_state_root(&self) -> anyhow::Result<[u8; 32]> {
        Ok(self.state_root())
    }

    fn get_finalized_state_root(&self) -> anyhow::Result<[u8; 32]> {
        Ok(self.base_root())
    }

    fn revert(&self, state_hash: [u8; 32]) -> anyhow::Result<[u8; 32]> {
        let state_hash = self
            .revert(state_hash)
            .map_err(|inner| anyhow::anyhow!("Cannot revert: {inner}"))?;

        Ok(state_hash)
    }

    fn revert_to_finalized(&self) -> anyhow::Result<[u8; 32]> {
        let state_hash = self.revert_to_base_root().map_err(|inner| {
            anyhow::anyhow!("Cannot revert to finalized: {inner}")
        })?;

        Ok(state_hash)
    }

    fn get_block_gas_limit(&self) -> u64 {
        self.vm_config.block_gas_limit
    }

    fn gas_per_deploy_byte(&self) -> u64 {
        self.vm_config.gas_per_deploy_byte
    }

    fn min_deployment_gas_price(&self) -> u64 {
        self.vm_config.min_deployment_gas_price
    }

    fn min_gas_limit(&self) -> u64 {
        self.min_gas_limit
    }

    fn min_deploy_points(&self) -> u64 {
        self.vm_config.min_deploy_points
    }

    fn gas_per_blob(&self) -> u64 {
        self.vm_config.gas_per_blob
    }

    fn blob_active(&self, block_height: u64) -> bool {
        self.vm_config
            .feature(FEATURE_BLOB)
            .map(|activation| activation.is_active_at(block_height))
            .unwrap_or(false)
    }

    fn wasm64_disabled(&self, block_height: u64) -> bool {
        self.vm_config
            .feature(FEATURE_DISABLE_WASM64)
            .map(|activation| activation.is_active_at(block_height))
            .unwrap_or(false)
    }

    fn wasm32_disabled(&self, block_height: u64) -> bool {
        self.vm_config
            .feature(FEATURE_DISABLE_WASM32)
            .map(|activation| activation.is_active_at(block_height))
            .unwrap_or(false)
    }

    fn third_party_disabled(&self, block_height: u64) -> bool {
        self.vm_config
            .feature(FEATURE_DISABLE_3RD_PARTY)
            .map(|activation| activation.is_active_at(block_height))
            .unwrap_or(false)
    }

    fn phoenix_refund_check_active(&self, block_height: u64) -> bool {
        self.vm_config
            .feature(FEATURE_HARDFORK_AEGIS)
            .map(|activation| activation.is_active_at(block_height))
            .unwrap_or(false)
    }

    fn shade_3rd_party(&self, contract_id: ContractId) -> anyhow::Result<()> {
        self.shade_3rd_party(contract_id).map_err(|inner| {
            anyhow::anyhow!("Cannot remove 3rd party: {inner}")
        })
    }

    fn enable_3rd_party(&self, contract_id: ContractId) -> anyhow::Result<()> {
        self.recompile_3rd_party(contract_id).map_err(|inner| {
            anyhow::anyhow!("Cannot enable 3rd party: {inner}")
        })
    }
}

fn has_unique_elements<T>(iter: T) -> bool
where
    T: IntoIterator,
    T::Item: Eq + std::hash::Hash,
{
    let mut uniq = std::collections::HashSet::new();
    iter.into_iter().all(move |x| uniq.insert(x))
}

impl Rusk {
    fn query_provisioners(
        &self,
        base_commit: Option<[u8; 32]>,
    ) -> anyhow::Result<Provisioners> {
        info!("Received get_provisioners request");
        let provisioners = self
            .provisioners(base_commit)
            .map_err(|e| anyhow::anyhow!("Cannot get provisioners {e}"))?
            .map(|(pk, stake)| {
                (PublicKey::new(pk.account), Self::to_stake(stake))
            });
        let mut ret = Provisioners::empty();
        for (pubkey_bls, stake) in provisioners {
            // Only include active provisioners
            if stake.value() > 0 {
                ret.add_provisioner(pubkey_bls, stake);
            }
        }

        Ok(ret)
    }

    fn query_provisioners_change(
        &self,
        base_commit: Option<[u8; 32]>,
    ) -> anyhow::Result<Vec<(PublicKey, Option<Stake>)>> {
        info!("Received get_provisioners_change request");
        Ok(self
            .last_provisioners_change(base_commit)
            .map_err(|e| {
                anyhow::anyhow!("Cannot get provisioners change: {e}")
            })?
            .into_iter()
            .map(|(pk, stake)| (PublicKey::new(pk), stake.map(Self::to_stake)))
            .collect())
    }

    fn to_stake(stake: StakeData) -> Stake {
        let stake_amount = stake.amount.unwrap_or_default();

        let value = stake_amount.value;

        Stake::new(value, stake_amount.eligibility)
    }
}

/// Check a state transition result against the block header
fn check_transition_result(
    transition_result: &StateTransitionResult,
    header: &Header,
) -> Result<(), StateTransitionError> {
    // Check state root
    if transition_result.state_root != header.state_hash {
        return Err(StateTransitionError::StateRootMismatch(
            transition_result.state_root,
            header.state_hash,
        ));
    }

    // Check event bloom
    if transition_result.event_bloom != header.event_bloom {
        return Err(StateTransitionError::EventBloomMismatch(
            Box::new(transition_result.event_bloom),
            Box::new(header.event_bloom),
        ));
    }

    Ok(())
}