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

Add back the simple test of Random to cluster-test #18594

Merged
merged 2 commits into from
Jul 10, 2024
Merged
Show file tree
Hide file tree
Changes from all 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
4 changes: 3 additions & 1 deletion crates/sui-cluster-test/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,8 @@ use test_case::{
coin_index_test::CoinIndexTest, coin_merge_split_test::CoinMergeSplitTest,
fullnode_build_publish_transaction_test::FullNodeBuildPublishTransactionTest,
fullnode_execute_transaction_test::FullNodeExecuteTransactionTest,
native_transfer_test::NativeTransferTest, shared_object_test::SharedCounterTest,
native_transfer_test::NativeTransferTest, random_beacon_test::RandomBeaconTest,
shared_object_test::SharedCounterTest,
};
use tokio::time::{self, Duration};
use tracing::{error, info};
Expand Down Expand Up @@ -308,6 +309,7 @@ impl ClusterTest {
TestCase::new(FullNodeExecuteTransactionTest {}),
TestCase::new(FullNodeBuildPublishTransactionTest {}),
TestCase::new(CoinIndexTest {}),
TestCase::new(RandomBeaconTest {}),
];

// TODO: improve the runner parallelism for efficiency
Expand Down
1 change: 1 addition & 0 deletions crates/sui-cluster-test/src/test_case.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,5 @@ pub mod coin_merge_split_test;
pub mod fullnode_build_publish_transaction_test;
pub mod fullnode_execute_transaction_test;
pub mod native_transfer_test;
pub mod random_beacon_test;
pub mod shared_object_test;
72 changes: 72 additions & 0 deletions crates/sui-cluster-test/src/test_case/random_beacon_test.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
// Copyright (c) Mysten Labs, Inc.
// SPDX-License-Identifier: Apache-2.0

use crate::{TestCaseImpl, TestContext};
use async_trait::async_trait;
use sui_json_rpc_types::{SuiExecutionStatus, SuiTransactionBlockEffectsAPI};
use sui_sdk::wallet_context::WalletContext;
use sui_test_transaction_builder::{emit_new_random_u128, publish_basics_package};
use tracing::info;

pub struct RandomBeaconTest;

#[async_trait]
impl TestCaseImpl for RandomBeaconTest {
fn name(&self) -> &'static str {
"RandomBeacon"
}

fn description(&self) -> &'static str {
"Test publishing basics packages and emitting an event that depends on a random value."
}

async fn run(&self, ctx: &mut TestContext) -> Result<(), anyhow::Error> {
let wallet_context: &WalletContext = ctx.get_wallet();
// Test only if the beacon is enabled.
if !Self::is_beacon_enabled(wallet_context).await {
info!("Random beacon is not enabled. Skipping test.");
return Ok(());
}

info!("Testing a transaction that uses Random.");

let sui_objs = ctx.get_sui_from_faucet(Some(1)).await;
assert!(!sui_objs.is_empty());

let package_ref = publish_basics_package(wallet_context).await;

let response = emit_new_random_u128(wallet_context, package_ref.0).await;
assert_eq!(
*response.effects.as_ref().unwrap().status(),
SuiExecutionStatus::Success,
"Generate new random value txn failed: {:?}",
*response.effects.as_ref().unwrap().status()
);

// Check that only the expected event was emitted.
let events = response.events.unwrap();
assert_eq!(
1,
events.data.len(),
"Expected 1 event, got {:?}",
events.data.len()
);
assert_eq!(
"RandomU128Event".to_string(),
events.data[0].type_.name.to_string()
);

// Verify fullnode observes the txn
ctx.let_fullnode_sync(vec![response.digest], 5).await;

Ok(())
}
}

impl RandomBeaconTest {
async fn is_beacon_enabled(wallet_context: &WalletContext) -> bool {
let client = wallet_context.get_client().await.unwrap();
let config = client.read_api().get_protocol_config(None).await.unwrap();
*config.feature_flags.get("random_beacon").unwrap()
}
}
47 changes: 46 additions & 1 deletion crates/sui-test-transaction-builder/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@ use std::path::PathBuf;
use sui_genesis_builder::validator_info::GenesisValidatorMetadata;
use sui_move_build::{BuildConfig, CompiledPackage};
use sui_sdk::rpc_types::{
get_new_package_obj_from_response, SuiTransactionBlockEffectsAPI, SuiTransactionBlockResponse,
get_new_package_obj_from_response, SuiObjectDataOptions, SuiTransactionBlockEffectsAPI,
SuiTransactionBlockResponse,
};
use sui_sdk::wallet_context::WalletContext;
use sui_types::base_types::{ObjectID, ObjectRef, SequenceNumber, SuiAddress};
Expand All @@ -23,6 +24,7 @@ use sui_types::transaction::{
DEFAULT_VALIDATOR_GAS_PRICE, TEST_ONLY_GAS_UNIT_FOR_HEAVY_COMPUTATION_STORAGE,
TEST_ONLY_GAS_UNIT_FOR_TRANSFER,
};
use sui_types::SUI_RANDOMNESS_STATE_OBJECT_ID;
use sui_types::{TypeTag, SUI_SYSTEM_PACKAGE_ID};

pub struct TestTransactionBuilder {
Expand Down Expand Up @@ -606,6 +608,49 @@ pub async fn increment_counter(
context.execute_transaction_must_succeed(txn).await
}

/// Executes a transaction that generates a new random u128 using Random and emits it as an event.
pub async fn emit_new_random_u128(
context: &WalletContext,
package_id: ObjectID,
) -> SuiTransactionBlockResponse {
let (sender, gas_object) = context.get_one_gas_object().await.unwrap().unwrap();
let rgp = context.get_reference_gas_price().await.unwrap();

let client = context.get_client().await.unwrap();
let random_obj = client
.read_api()
.get_object_with_options(
SUI_RANDOMNESS_STATE_OBJECT_ID,
SuiObjectDataOptions::new().with_owner(),
)
.await
.unwrap()
.into_object()
.unwrap();
let random_obj_owner = random_obj
.owner
.expect("Expect Randomness object to have an owner");

let Owner::Shared {
initial_shared_version,
} = random_obj_owner
else {
panic!("Expect Randomness to be shared object")
};
let random_call_arg = CallArg::Object(ObjectArg::SharedObject {
id: SUI_RANDOMNESS_STATE_OBJECT_ID,
initial_shared_version,
mutable: false,
});

let txn = context.sign_transaction(
&TestTransactionBuilder::new(sender, gas_object, rgp)
.move_call(package_id, "random", "new", vec![random_call_arg])
.build(),
);
context.execute_transaction_must_succeed(txn).await
}

/// Executes a transaction to publish the `nfts` package and returns the package id, id of the gas
/// object used, and the digest of the transaction.
pub async fn publish_nfts_package(
Expand Down
18 changes: 18 additions & 0 deletions sui_programmability/examples/basics/sources/random.move
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
// Copyright (c) Mysten Labs, Inc.
// SPDX-License-Identifier: Apache-2.0

/// This example demonstrates emitting a random u128 (e.g., for an offchain lottery)
module basics::random {
use sui::event;
use sui::random::Random;

public struct RandomU128Event has copy, drop {
value: u128,
}

entry fun new(r: &Random, ctx: &mut TxContext) {
let mut gen = r.new_generator(ctx);
let value = gen.generate_u128();
event::emit(RandomU128Event { value });
}
}
Loading