Skip to content

Commit

Permalink
Merge #4971
Browse files Browse the repository at this point in the history
4971: Update transaction builder to handle new auction entrypoints r=zajko a=wojcik91

Update transaction builder to properly support new auction entrypoints (`add_reservations`, `cancel_reservations` and `change_bid_public_key`) and `reserved_slots` argument for `add_bid` entrypoint.

This is required to implement new subcommands in casper-client: casper-ecosystem/casper-client-rs#198


Co-authored-by: Maciej Wójcik <maciek@wjck.pl>
  • Loading branch information
casperlabs-bors-ng[bot] and Maciej Wójcik authored Nov 25, 2024
2 parents ef376e6 + 6df51a7 commit 90eed37
Show file tree
Hide file tree
Showing 14 changed files with 416 additions and 53 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -974,19 +974,19 @@ fn should_distribute_rewards_after_restaking_delegated_funds() {
delegator_1_stake =
get_delegator_staked_amount(&mut builder, VALIDATOR_1.clone(), DELEGATOR_1.clone());

let updelegate_amount = U512::from(1_000_000);
let updelegate_result = builder.bidding(
let undelegate_amount = U512::from(1_000_000);
let undelegate_result = builder.bidding(
None,
protocol_version,
(*DELEGATOR_2_ADDR).into(),
AuctionMethod::Delegate {
max_delegators_per_validator: u32::MAX,
validator: VALIDATOR_1.clone(),
delegator: DelegatorKind::PublicKey(DELEGATOR_2.clone()),
amount: updelegate_amount,
amount: undelegate_amount,
},
);
assert!(updelegate_result.is_success(), "{:?}", updelegate_result);
assert!(undelegate_result.is_success(), "{:?}", undelegate_result);
builder.commit_transforms(builder.get_post_state_hash(), undelegate_result.effects());
delegator_2_stake =
get_delegator_staked_amount(&mut builder, VALIDATOR_1.clone(), DELEGATOR_2.clone());
Expand All @@ -998,9 +998,10 @@ fn should_distribute_rewards_after_restaking_delegated_funds() {
public_key: VALIDATOR_1.clone(),
amount,
delegation_rate: 0,
minimum_delegation_amount: updelegate_amount.as_u64(),
maximum_delegation_amount: updelegate_amount.as_u64(),
minimum_delegation_amount: undelegate_amount.as_u64(),
maximum_delegation_amount: undelegate_amount.as_u64(),
minimum_bid_amount: DEFAULT_MINIMUM_BID_AMOUNT,
reserved_slots: 0,
}
} else {
AuctionMethod::WithdrawBid {
Expand Down
23 changes: 9 additions & 14 deletions node/src/reactor/main_reactor/tests/transactions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2931,8 +2931,9 @@ async fn add_and_withdraw_bid_transaction() {
PublicKey::from(&**BOB_SECRET_KEY),
0,
bid_amount,
test.chainspec().core_config.minimum_delegation_amount,
test.chainspec().core_config.maximum_delegation_amount,
None,
None,
None,
)
.unwrap()
.with_chain_name(CHAIN_NAME)
Expand Down Expand Up @@ -3089,18 +3090,12 @@ async fn insufficient_funds_add_bid() {
let bid_amount = bob_initial_balance.total;

let mut txn = Transaction::from(
TransactionV1Builder::new_add_bid(
BOB_PUBLIC_KEY.clone(),
0,
bid_amount,
test.chainspec().core_config.minimum_delegation_amount,
test.chainspec().core_config.maximum_delegation_amount,
)
.unwrap()
.with_chain_name(CHAIN_NAME)
.with_initiator_addr(PublicKey::from(&**BOB_SECRET_KEY))
.build()
.unwrap(),
TransactionV1Builder::new_add_bid(BOB_PUBLIC_KEY.clone(), 0, bid_amount, None, None, None)
.unwrap()
.with_chain_name(CHAIN_NAME)
.with_initiator_addr(PublicKey::from(&**BOB_SECRET_KEY))
.build()
.unwrap(),
);
txn.sign(&BOB_SECRET_KEY);

Expand Down
5 changes: 5 additions & 0 deletions storage/src/data_access_layer/auction.rs
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,8 @@ pub enum AuctionMethod {
/// The minimum bid amount a validator must submit to have
/// their bid considered as valid.
minimum_bid_amount: u64,
/// Number of delegator slots which can be reserved for specific delegators
reserved_slots: u32,
},
/// Withdraw bid.
WithdrawBid {
Expand Down Expand Up @@ -188,6 +190,8 @@ impl AuctionMethod {
let maximum_delegation_amount =
Self::get_named_argument(runtime_args, auction::ARG_MAXIMUM_DELEGATION_AMOUNT)
.unwrap_or(global_maximum_delegation);
let reserved_slots =
Self::get_named_argument(runtime_args, auction::ARG_RESERVED_SLOTS).unwrap_or(0);

Ok(Self::AddBid {
public_key,
Expand All @@ -196,6 +200,7 @@ impl AuctionMethod {
minimum_delegation_amount,
maximum_delegation_amount,
minimum_bid_amount: global_minimum_bid_amount,
reserved_slots,
})
}

Expand Down
3 changes: 2 additions & 1 deletion storage/src/global_state/state/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1279,6 +1279,7 @@ pub trait StateProvider: Send + Sync + Sized {
minimum_delegation_amount,
maximum_delegation_amount,
minimum_bid_amount,
reserved_slots,
} => runtime
.add_bid(
public_key,
Expand All @@ -1288,7 +1289,7 @@ pub trait StateProvider: Send + Sync + Sized {
maximum_delegation_amount,
minimum_bid_amount,
max_delegators_per_validator,
0,
reserved_slots,
)
.map(AuctionMethodRet::UpdatedAmount)
.map_err(TrackingCopyError::Api),
Expand Down
2 changes: 1 addition & 1 deletion types/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ untrusted = "0.7.1"

[features]
json-schema = ["once_cell", "schemars", "serde-map-to-array/json-schema"]
testing = ["proptest", "proptest-derive", "rand/default", "rand_pcg", "strum", "bincode"]
testing = ["proptest", "proptest-derive", "rand/default", "rand_pcg", "strum", "bincode", "thiserror", "getrandom", "derp"]
# Includes a restricted set of std lib functionality suitable for usage e.g. in a JS environment when compiled to Wasm.
std = ["base16/std", "derp", "getrandom/std", "humantime", "itertools/use_std", "libc", "once_cell", "pem", "serde_json/preserve_order", "thiserror", "untrusted"]
# Includes a complete set of std lib functionality, including filesystem I/O operations.
Expand Down
2 changes: 1 addition & 1 deletion types/src/crypto.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ pub use asymmetric_key::{
SECP256K1_TAG, SYSTEM_ACCOUNT, SYSTEM_TAG,
};
pub use error::Error;
#[cfg(any(feature = "std", test))]
#[cfg(any(feature = "std", feature = "testing", test))]
pub use error::ErrorExt;

pub(crate) fn blake2b<T: AsRef<[u8]>>(data: T) -> [u8; BLAKE2B_DIGEST_LENGTH] {
Expand Down
20 changes: 17 additions & 3 deletions types/src/crypto/asymmetric_key.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ use core::{
iter,
marker::Copy,
};
#[cfg(any(feature = "testing", test))]
use rand::distributions::{Distribution, Standard};
#[cfg(any(feature = "std-fs-io", test))]
use std::path::Path;

Expand Down Expand Up @@ -45,7 +47,7 @@ use serde_json::json;
#[cfg(any(feature = "std", test))]
use untrusted::Input;

#[cfg(any(feature = "std", test))]
#[cfg(any(feature = "std", feature = "testing", test))]
use crate::crypto::ErrorExt;
#[cfg(any(feature = "std-fs-io", test))]
use crate::file_utils::{read_file, write_file, write_private_file};
Expand Down Expand Up @@ -221,15 +223,15 @@ impl SecretKey {
}

/// Generates a new ed25519 variant using the system's secure random number generator.
#[cfg(any(feature = "std", test))]
#[cfg(any(feature = "std", feature = "testing", test))]
pub fn generate_ed25519() -> Result<Self, ErrorExt> {
let mut bytes = [0u8; Self::ED25519_LENGTH];
getrandom::getrandom(&mut bytes[..])?;
SecretKey::ed25519_from_bytes(bytes).map_err(Into::into)
}

/// Generates a new secp256k1 variant using the system's secure random number generator.
#[cfg(any(feature = "std", test))]
#[cfg(any(feature = "std", feature = "testing", test))]
pub fn generate_secp256k1() -> Result<Self, ErrorExt> {
let mut bytes = [0u8; Self::SECP256K1_LENGTH];
getrandom::getrandom(&mut bytes[..])?;
Expand Down Expand Up @@ -703,6 +705,18 @@ impl From<&SecretKey> for PublicKey {
}
}

#[cfg(any(feature = "testing", test))]
impl Distribution<PublicKey> for Standard {
fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> PublicKey {
let secret_key = if rng.gen() {
SecretKey::generate_ed25519().unwrap()
} else {
SecretKey::generate_secp256k1().unwrap()
};
PublicKey::from(&secret_key)
}
}

#[cfg(any(feature = "testing", test))]
impl PartialEq for SecretKey {
fn eq(&self, other: &Self) -> bool {
Expand Down
8 changes: 4 additions & 4 deletions types/src/crypto/error.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use alloc::string::String;
use core::fmt::{self, Display, Formatter};
#[cfg(any(feature = "std", test))]
#[cfg(any(feature = "std", feature = "testing", test))]
use std::error::Error as StdError;

#[cfg(feature = "datasize")]
Expand All @@ -9,7 +9,7 @@ use ed25519_dalek::ed25519::Error as SignatureError;
#[cfg(any(feature = "std", test))]
use pem::PemError;
use serde::Serialize;
#[cfg(any(feature = "std", test))]
#[cfg(any(feature = "std", feature = "testing", test))]
use thiserror::Error;

#[cfg(any(feature = "std-fs-io", test))]
Expand Down Expand Up @@ -74,7 +74,7 @@ impl From<SignatureError> for Error {
}
}

#[cfg(any(feature = "std", test))]
#[cfg(any(feature = "std", feature = "testing", test))]
impl StdError for Error {
fn source(&self) -> Option<&(dyn StdError + 'static)> {
match self {
Expand All @@ -86,7 +86,7 @@ impl StdError for Error {
}

/// Cryptographic errors extended with some additional variants.
#[cfg(any(feature = "std", test))]
#[cfg(any(feature = "std", feature = "testing", test))]
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum ErrorExt {
Expand Down
16 changes: 16 additions & 0 deletions types/src/system/auction/delegator_kind.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,11 @@ use core::{
};
#[cfg(feature = "datasize")]
use datasize::DataSize;
#[cfg(any(feature = "testing", test))]
use rand::{
distributions::{Distribution, Standard},
Rng,
};
#[cfg(feature = "json-schema")]
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
Expand Down Expand Up @@ -139,6 +144,17 @@ impl CLTyped for DelegatorKind {
}
}

#[cfg(any(feature = "testing", test))]
impl Distribution<DelegatorKind> for Standard {
fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> DelegatorKind {
if rng.gen() {
DelegatorKind::PublicKey(rng.gen())
} else {
DelegatorKind::Purse(rng.gen())
}
}
}

#[cfg(test)]
mod tests {
use crate::{bytesrepr, system::auction::delegator_kind::DelegatorKind, PublicKey, SecretKey};
Expand Down
16 changes: 16 additions & 0 deletions types/src/system/auction/reservation.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
use alloc::vec::Vec;
use core::fmt::{self, Display, Formatter};
#[cfg(any(feature = "testing", test))]
use rand::{
distributions::{Distribution, Standard},
Rng,
};

#[cfg(feature = "datasize")]
use datasize::DataSize;
Expand Down Expand Up @@ -113,6 +118,17 @@ impl Display for Reservation {
}
}

#[cfg(any(feature = "testing", test))]
impl Distribution<Reservation> for Standard {
fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> Reservation {
Reservation {
delegator_kind: rng.gen(),
validator_public_key: rng.gen(),
delegation_rate: rng.gen(),
}
}
}

#[cfg(test)]
mod tests {
use crate::{bytesrepr, system::auction::Reservation, PublicKey, SecretKey};
Expand Down
16 changes: 11 additions & 5 deletions types/src/transaction/transaction_entry_point.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,10 @@ use serde::{Deserialize, Serialize};
pub enum TransactionEntryPoint {
/// The default entry point name.
Call,

/// A non-native, arbitrary entry point.
Custom(String),

/// The `transfer` native entry point, used to transfer `Motes` from a source purse to a target
/// purse.
///
Expand All @@ -55,21 +57,24 @@ pub enum TransactionEntryPoint {
)
)]
Transfer,

/// The `add_bid` native entry point, used to create or top off a bid purse.
///
/// Requires the following runtime args:
/// * "public_key": `PublicKey`
/// * "delegation_rate": `u8`
/// * "amount": `U512`
/// * "minimum_delegation_amount": `u64`
/// * "maximum_delegation_amount": `u64`
/// * "minimum_delegation_amount": `Option<u64>`
/// * "maximum_delegation_amount": `Option<u64>`
/// * "reserved_slots": `Option<u32>`
#[cfg_attr(
feature = "json-schema",
schemars(
description = "The `add_bid` native entry point, used to create or top off a bid purse."
)
)]
AddBid,

/// The `withdraw_bid` native entry point, used to decrease a stake.
///
/// Requires the following runtime args:
Expand Down Expand Up @@ -157,12 +162,12 @@ pub enum TransactionEntryPoint {
)
)]
ChangeBidPublicKey,

/// The `add_reservations` native entry point, used to add delegators to validator's reserve
/// list.
///
/// Requires the following runtime args:
/// * "validator": `PublicKey`
/// * "delegators": `&[PublicKey]`
/// * "reservations": `Vec<Reservation>`
#[cfg_attr(
feature = "json-schema",
schemars(
Expand All @@ -171,12 +176,13 @@ pub enum TransactionEntryPoint {
)
)]
AddReservations,

/// The `cancel_reservations` native entry point, used to remove delegators from validator's
/// reserve list.
///
/// Requires the following runtime args:
/// * "validator": `PublicKey`
/// * "delegators": `&[PublicKey]`
/// * "delegators": `Vec<PublicKey>`
#[cfg_attr(
feature = "json-schema",
schemars(
Expand Down
Loading

0 comments on commit 90eed37

Please sign in to comment.