Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Stake contract migration #1464

Merged
merged 18 commits into from
Mar 13, 2024
Merged
Show file tree
Hide file tree
Changes from 13 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions consensus/src/user/provisioners.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,12 @@ pub struct Provisioners {
members: BTreeMap<PublicKey, Stake>,
}

impl Provisioners {
pub fn iter(&self) -> impl Iterator<Item = (&PublicKey, &Stake)> {
self.members.iter()
}
}

#[derive(Clone, Debug)]
pub struct ContextProvisioners {
current: Provisioners,
Expand Down
4 changes: 2 additions & 2 deletions node/src/chain/acceptor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -463,9 +463,9 @@ impl<DB: database::DB, VM: vm::VMExecution, N: Network> Acceptor<N, DB, VM> {
let vm = self.vm.write().await;
let txs = self.db.read().await.update(|t| {
let (txs, verification_output) = if blk.is_final() {
vm.finalize(blk.inner())?
vm.finalize(blk.inner(), provisioners_list.current())?
} else {
vm.accept(blk.inner())?
vm.accept(blk.inner(), provisioners_list.current())?
};

assert_eq!(header.state_hash, verification_output.state_root);
Expand Down
22 changes: 15 additions & 7 deletions node/src/chain/consensus.rs
Original file line number Diff line number Diff line change
Expand Up @@ -321,10 +321,12 @@ impl<DB: database::DB, VM: vm::VMExecution> Operations for Executor<DB, VM> {

let vm = self.vm.read().await;

Ok(vm.verify_state_transition(blk).map_err(|err| {
error!("failed to call VST {}", err);
Error::Failed
})?)
Ok(vm
.verify_state_transition(blk, self.provisioners.current())
.map_err(|err| {
error!("failed to call VST {}", err);
Error::Failed
})?)
}

async fn execute_state_transition(
Expand All @@ -340,9 +342,15 @@ impl<DB: database::DB, VM: vm::VMExecution> Operations for Executor<DB, VM> {
let txs = view.get_txs_sorted_by_fee().map_err(|err| {
anyhow::anyhow!("failed to get mempool txs: {}", err)
})?;
let ret = vm.execute_state_transition(&params, txs).map_err(
|err| anyhow::anyhow!("failed to call EST {}", err),
)?;
let ret = vm
.execute_state_transition(
&params,
txs,
self.provisioners.current(),
)
.map_err(|err| {
anyhow::anyhow!("failed to call EST {}", err)
})?;
Ok(ret)
})
.map_err(|err: anyhow::Error| {
Expand Down
4 changes: 4 additions & 0 deletions node/src/vm.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ pub trait VMExecution: Send + Sync + 'static {
&self,
params: &CallParams,
txs: I,
provisioners: &Provisioners,
) -> anyhow::Result<(
Vec<SpentTransaction>,
Vec<Transaction>,
Expand All @@ -28,16 +29,19 @@ pub trait VMExecution: Send + Sync + 'static {
fn verify_state_transition(
&self,
blk: &Block,
provisioners: &Provisioners,
) -> anyhow::Result<VerificationOutput>;

fn accept(
&self,
blk: &Block,
provisioners: &Provisioners,
) -> anyhow::Result<(Vec<SpentTransaction>, VerificationOutput)>;

fn finalize(
&self,
blk: &Block,
provisioners: &Provisioners,
) -> anyhow::Result<(Vec<SpentTransaction>, VerificationOutput)>;

fn preverify(&self, tx: &Transaction) -> anyhow::Result<()>;
Expand Down
2 changes: 2 additions & 0 deletions rusk/benches/block_ingestion.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ use rand::SeedableRng;
use tempfile::tempdir;

use common::state::new_state;
use dusk_consensus::user::provisioners::Provisioners;

fn load_txs() -> Vec<Transaction> {
const TXS_BYTES: &[u8] = include_bytes!("block");
Expand Down Expand Up @@ -97,6 +98,7 @@ pub fn accept_benchmark(c: &mut Criterion) {
txs,
None,
&[],
&Provisioners::empty(),
)
.expect("Accepting transactions should succeed");

Expand Down
Binary file added rusk/src/assets/stake_contract.wasm
herr-seppia marked this conversation as resolved.
Show resolved Hide resolved
Binary file not shown.
4 changes: 4 additions & 0 deletions rusk/src/bin/args.rs
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,10 @@ pub struct Args {
/// path to encrypted BLS keys
pub consensus_keys_path: Option<PathBuf>,

#[clap(long)]
/// height at which migration will be performed
pub migration_height: Option<u64>,
ureeves marked this conversation as resolved.
Show resolved Hide resolved

#[clap(long)]
/// Delay in milliseconds to mitigate UDP drops for DataBroker service in
/// localnet
Expand Down
10 changes: 10 additions & 0 deletions rusk/src/bin/config/chain.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ use crate::args::Args;
pub(crate) struct ChainConfig {
db_path: Option<PathBuf>,
consensus_keys_path: Option<PathBuf>,
migration_height: Option<u64>,
}

impl ChainConfig {
Expand All @@ -27,6 +28,11 @@ impl ChainConfig {
if let Some(db_path) = args.db_path.clone() {
self.db_path = Some(db_path);
}

// Override config migration_height
if let Some(migration_height) = args.migration_height {
self.migration_height = Some(migration_height)
}
}

pub(crate) fn db_path(&self) -> PathBuf {
Expand All @@ -52,4 +58,8 @@ impl ChainConfig {
.display()
.to_string()
}

pub(crate) fn migration_height(&self) -> Option<u64> {
self.migration_height
}
}
2 changes: 1 addition & 1 deletion rusk/src/bin/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
let (rusk, node, mut service_list) = {
let state_dir = rusk_profile::get_rusk_state_dir()?;
info!("Using state from {state_dir:?}");
let rusk = Rusk::new(state_dir)?;
let rusk = Rusk::new(state_dir, config.chain.migration_height())?;

info!("Rusk VM loaded");

Expand Down
1 change: 1 addition & 0 deletions rusk/src/lib/chain.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ pub struct Rusk {
pub(crate) tip: Arc<RwLock<RuskTip>>,
pub(crate) vm: Arc<VM>,
dir: PathBuf,
migration_height: Option<u64>,
}

#[derive(Clone)]
Expand Down
75 changes: 60 additions & 15 deletions rusk/src/lib/chain/rusk.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,14 @@ use std::{fs, io};
use parking_lot::RwLock;
use sha3::{Digest, Sha3_256};
use tokio::task;
use tracing::debug;
use tracing::{debug, error};

use crate::chain::vm::migration::Migration;
use dusk_bls12_381::BlsScalar;
use dusk_bls12_381_sign::PublicKey as BlsPublicKey;
use dusk_bytes::DeserializableSlice;
use dusk_consensus::operations::VerificationOutput;
use dusk_consensus::user::provisioners::Provisioners;
use node_data::ledger::{SpentTransaction, Transaction};
use phoenix_core::transaction::StakeData;
use phoenix_core::Transaction as PhoenixTransaction;
Expand All @@ -37,7 +39,10 @@ pub static DUSK_KEY: LazyLock<BlsPublicKey> = LazyLock::new(|| {
});

impl Rusk {
pub fn new<P: AsRef<Path>>(dir: P) -> Result<Self> {
pub fn new<P: AsRef<Path>>(
dir: P,
migration_height: Option<u64>,
) -> Result<Self> {
let dir = dir.as_ref();
let commit_id_path = to_rusk_state_id_path(dir);

Expand Down Expand Up @@ -66,6 +71,7 @@ impl Rusk {
tip,
vm,
dir: dir.into(),
migration_height,
})
}

Expand All @@ -76,9 +82,21 @@ impl Rusk {
generator: &BlsPublicKey,
txs: I,
missed_generators: &[BlsPublicKey],
provisioners: &Provisioners,
) -> Result<(Vec<SpentTransaction>, Vec<Transaction>, VerificationOutput)>
{
let mut session = self.session(block_height, None)?;
let session = self.session(block_height, None)?;

let mut session = Migration::migrate(
self.migration_height,
session,
block_height,
provisioners,
)
.map_err(|e| {
error!("Error while migrating: {e}");
e
})?;

let mut block_gas_left = block_gas_limit;

Expand Down Expand Up @@ -163,24 +181,29 @@ impl Rusk {
generator: &BlsPublicKey,
txs: &[Transaction],
missed_generators: &[BlsPublicKey],
provisioners: &Provisioners,
) -> Result<(Vec<SpentTransaction>, VerificationOutput)> {
let mut session = self.session(block_height, None)?;
let session = self.session(block_height, None)?;

accept(
&mut session,
session,
block_height,
block_gas_limit,
generator,
txs,
missed_generators,
provisioners,
self.migration_height,
)
.map(|(a, b, _)| (a, b))
}

/// Accept the given transactions.
///
/// * `consistency_check` - represents a state_root, the caller expects to
/// be returned on successful transactions execution. Passing a None
/// value disables the check.
#[allow(clippy::too_many_arguments)]
pub fn accept_transactions(
&self,
block_height: u64,
Expand All @@ -189,16 +212,19 @@ impl Rusk {
txs: Vec<Transaction>,
consistency_check: Option<VerificationOutput>,
missed_generators: &[BlsPublicKey],
provisioners: &Provisioners,
) -> Result<(Vec<SpentTransaction>, VerificationOutput)> {
let mut session = self.session(block_height, None)?;
let session = self.session(block_height, None)?;

let (spent_txs, verification_output) = accept(
&mut session,
let (spent_txs, verification_output, session) = accept(
session,
block_height,
block_gas_limit,
&generator,
&txs[..],
missed_generators,
provisioners,
self.migration_height,
)?;

if let Some(expected_verification) = consistency_check {
Expand All @@ -219,6 +245,7 @@ impl Rusk {
/// * `consistency_check` - represents a state_root, the caller expects to
/// be returned on successful transactions execution. Passing None value
/// disables the check.
#[allow(clippy::too_many_arguments)]
pub fn finalize_transactions(
&self,
block_height: u64,
Expand All @@ -227,16 +254,19 @@ impl Rusk {
txs: Vec<Transaction>,
consistency_check: Option<VerificationOutput>,
missed_generators: &[BlsPublicKey],
provisioners: &Provisioners,
) -> Result<(Vec<SpentTransaction>, VerificationOutput)> {
let mut session = self.session(block_height, None)?;
let session = self.session(block_height, None)?;

let (spent_txs, verification_output) = accept(
&mut session,
let (spent_txs, verification_output, session) = accept(
session,
block_height,
block_gas_limit,
&generator,
&txs[..],
missed_generators,
provisioners,
self.migration_height,
)?;

if let Some(expected_verification) = consistency_check {
Expand Down Expand Up @@ -363,14 +393,28 @@ async fn delete_commits(vm: Arc<VM>, commits: Vec<[u8; 32]>) {
}
}

#[allow(clippy::too_many_arguments)]
fn accept(
session: &mut Session,
session: Session,
block_height: u64,
block_gas_limit: u64,
generator: &BlsPublicKey,
txs: &[Transaction],
missed_generators: &[BlsPublicKey],
) -> Result<(Vec<SpentTransaction>, VerificationOutput)> {
provisioners: &Provisioners,
migration_height: Option<u64>,
) -> Result<(Vec<SpentTransaction>, VerificationOutput, Session)> {
let mut session = Migration::migrate(
migration_height,
session,
block_height,
provisioners,
)
.map_err(|e| {
error!("Error while migrating: {e}");
e
})?;

let mut block_gas_left = block_gas_limit;

let mut spent_txs = Vec::with_capacity(txs.len());
Expand All @@ -380,7 +424,7 @@ fn accept(

for unspent_tx in txs {
let tx = &unspent_tx.inner;
let receipt = execute(session, tx)?;
let receipt = execute(&mut session, tx)?;

update_hasher(&mut event_hasher, &receipt.events);
let gas_spent = receipt.gas_spent;
Expand All @@ -400,7 +444,7 @@ fn accept(
}

reward_slash_and_update_root(
session,
&mut session,
block_height,
dusk_spent,
generator,
Expand All @@ -417,6 +461,7 @@ fn accept(
state_root,
event_hash,
},
session,
))
}

Expand Down
Loading